TypeError: Cannot read property 'first' of undefined

Viewed 1162
client.on('message', (message) => {
 const { member, mentions } = message;

 const tag = `<@${member.id}>`;

 if (message.content.startsWith(`${prefix}ban`)) {
  if (
   member.hasPermission('ADMINISTRATOR') ||
   member.hasPermission('BAN_MEMBERS')
  ) {
   const target = mentions.user.first();
   if (target) {
    const targetMember = message.guild.members.cache.get(target.id);
    targetMember.ban();
    message.channel.send(
     `${tag} Cet.te ancien.ne membre a été bannii avec succès !`
    );
   } else {
    message.channel.send(`${tag} Merci de spécifier le membre à bannir.`);
   }
  } else {
   message.channel.send(
    `${tag} Tu n'as pas la permission d'effectuer cette commande.`
   );
  }
 }
});

I'm not sure what the error in my code is, any help is appreciated! I would also take any suggestions on how to improve this code in general.

2 Answers

It's actually mentions.users.first(). See docs.

user is not a property of mentions. Instead use users:

mentions.users.first();

MessageMentions docs


Also, as a bit of a suggestion, instead of getting the mention as a User object, then turning it into a GuildMember object, you could just skip straight to the GuildMember object.

// instead of:
const target = mentions.users.first();

// use:
const target = mentions.members.first();

mentions.users returns a collection of every user that was mentioned in that message. You are taking the first User object (first mention).

You are then turning that User object into a GuildMember object using the Guild.member() function:

message.guild.members.cache.get(target.id);

However, message.members returns a collection of every GuildMember that was mentioned, eliminating the need to convert a User object to a GuildMember later in your code, as it would already be a GuildMember.

Related