How to make Discord Bot make sure your pinging someone in a command

Tags: , , ,



I’m trying to make the bot say the name of someone I pinged and give that person a role. Right now, if you don’t ping someone, the whole bot breaks.

Here is my code:

const taggedUser0 = msg.mentions.members.first();
if (!args.length) {
  msg.author.send(`You didn't ping, ${msg.author}!`);
  msg.delete(); // Deletes command
} else if (msg.member.roles.holds(role)) {
    // checks if the person mentioned already has a role
    return;
  } else {
    taggedUser0.roles.add(role); // adds role
  }
  msg.author.send(`${taggedUser0}.`);
  msg.delete(); // Deletes command
}

Answer

I see a few problems with your code:


First of all, else if() will always return an error.

if (false) console.log(false)
else if () console.log(true) // wrong usage

if (false) console.log(false)
else console.log(true) // correct usage

Second of all, you should switch this if statement:

if (!args.length)

// to:

if (!taggedUser0)

Someone could have added an arg and still not have mentioned anyone.


Third of all, GuildMember.roles returns a Manager, not a Collection, so make sure you pass through the cache property:

taggedUser0.roles.cache.holds()

Also, Collection.holds() is not a function. Instead, use Collection.has() (and make sure the passed parameter is the role ID, not the role object):

taggedUser0.roles.cache.has('ID Here');

Lastly, to ping someone, you should use this format:

message.channel.send(`<@${taggedUser0.id}>`);


Source: stackoverflow