Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

302
Views
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
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!