Latepate
Latepate

Reputation: 117

How to check multiple roles discord.js v12

I'm very new/bad at discord js. But I want to make a command with "allowed roles" so only admin, owner and mod can use it. But I don't know how.

I have tried this:

client.on('message', message => {
 if(message.content === 'test') {
 let allowedRole = message.guild.roles.cache.find(r => r.name === "owner");
let allowedRole1 = message.guild.roles.cache.find(r => r.name === "mod");
let allowedRole2 = message.guild.roles.cache.find(r => r.name === "admin");
if (message.member.roles.cache.has(allowedRole.id) && message.member.roles.cache.has(allowedRole1.id) && message.member.roles.cache.has(allowedRole2.id)) {
message.channel.send('hello');
} else { 
   message.channel.send('bad');
}
}});

Upvotes: 1

Views: 271

Answers (2)

Christoph Blüm
Christoph Blüm

Reputation: 975

in your example, only users with all three roles are accepted (due to the logical AND operator).

Replace && with || and it should work as expected.

client.on('message', async message => {
  if (message.content === 'test') {
    let allowedRole = await message.guild.roles.cache.find(
      r => r.name === 'owner'
    );
    let allowedRole1 = await message.guild.roles.cache.find(
      r => r.name === 'mod'
    );
    let allowedRole2 = await message.guild.roles.cache.find(
      r => r.name === 'admin'
    );

    if (
      message.member.roles.cache.has(allowedRole.id) ||
      message.member.roles.cache.has(allowedRole1.id) ||
      message.member.roles.cache.has(allowedRole2.id)
    ) {
      message.channel.send('hello');
    } else {
      message.channel.send('bad');
    }
  }
});

Upvotes: 4

MegaMix_Craft
MegaMix_Craft

Reputation: 2210

As Christoph said, you can use their code but I'd recommend to use role IDs intead because role name can be changed at any time:

if (!message.member.roles.cache.has(<1st_role_id>) || !message.member.roles.cache.has(<2nd_role_id>) || !message.member.roles.cache.has(<3rd_role_id>)) 
return message.reply("You can't execute this command!")
// your code

WARNING

It's only a solution if you are running private bot and not public, which is for a lot of servers

Upvotes: 1

Related Questions