简体   繁体   中英

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!

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.")
}

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. }

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.")
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM