zEooT
zEooT

Reputation: 1

Specific Role Commands for Discord Bot

I'm trying to create a command for my Disc bot and I'm trying to make it role-related.

I've looked through other questions on this site but they're all in Python not JS; and on discord.js their examples are completely different from what I want to do. Everything up to this point works completely fine, it's just when it gets to this part (there isn't anything above or below this)

if (message.member.roles.name == "Owner") {
    return message.reply("You can use this command!")
  }
  if (message.member.roles.name != "Owner") {
    return message.reply("Sorry, an error occurred.")
  }

I want to be able to see "You can use this command!

Upvotes: 0

Views: 4174

Answers (3)

IcyTea
IcyTea

Reputation: 1

I think you should write it like this. It can prevents many errors like "message.member.roles.name is not a function"

Here is my code:

client.on('message', message => {
            const roleName = message.member.roles.cache.find(r => r.name === "Owner")
            if (roleName) {
                return message.reply("You can use this command.")
            } else {
                return message.reply("Sorry, an error occured.")
            }

Upvotes: 0

Lane
Lane

Reputation: 76

Another alternative is, you could get the role by their ID (as they probably don't change regularly) and then check if the user has that role.

let ownerRole = message.guild.roles.get('123456789');
let moderatorRole = message.guild.roles.get('123456789');

if(msg.member.roles.has(ownerRole.id)) {
    // the user has the role
} else {
    // the user doesn't have the role.
}

Upvotes: 0

Snel23
Snel23

Reputation: 1379

The problem is that message.member.roles isn't going to be a single item, it will be a Collection of roles that the user has, so you need to search through the roles to check if the user has a role.

You can use the .find() function to see if the user has a role. It takes a function (in this case, a lambda function) that passes r (being the role), and checks if r.name is equal to your role (in this case, Owner)

if(message.member.roles.find(r => r.name === "Owner")){
  return message.reply("You can use this command!")
} else {
  return message.reply("Sorry, an error occurred.")
}

Upvotes: 1

Related Questions