'TypeError: Cannot read property 'user' of undefined error while trying to make a command

I was trying to make a command to ping a random user each time the command is run but I seem to have run into a problem.

Here's my code:

const DiscordCommand = require('../../contracts/DiscordCommand');
class KickCommand extends DiscordCommand {
  onCommand(message) {
    message.delete();
    const userList = message.guild.members.cache.array();
    var randomNumber = Math.round(Math.random() * message.guild.memberCount);
    var pingPerson = userList[randomNumber];
    message.channel.send('<@' + pingPerson.user.id + '>').then((msg) => {
      msg.delete({ timeout: 100 });
    });
  }
}

module.exports = KickCommand;

The error I get:

TypeError: Cannot read property 'user' of undefined


Solution 1:[1]

The problem is that Math.round(Math.random() * message.guild.memberCount) can return numbers larger than than the last index as you use round() instead of floor().

However; instead of creating a random generator function, you could use Collection#random() to obtain unique random value(s) from a collection.

message.guild.members.cache returns a collection, so you could use it like this:

class KickCommand extends DiscordCommand {
  onCommand(message) {
    message.delete();
    const pingPerson = message.guild.members.cache.random();
    message.channel.send('<@' + pingPerson.user.id + '>').then((msg) => {
      msg.delete({ timeout: 100 });
    });
  }
}

It's probably also a good idea to fetch the users first:

class KickCommand extends DiscordCommand {
  async onCommand(message) {
    message.delete();
    await message.guild.members.fetch();
    
    const pingPerson = message.guild.members.cache.random();
    const msg = await message.channel.send('<@' + pingPerson.user.id + '>');

    // msg.delete() doesn't take any parameters in v13, so use setTimeout instead
    setTimeout(() => msg.delete(), 100);
  }
}

And make sure that the GUILD_MEMBERS intent is enabled.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1