Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

301
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda