简体   繁体   中英

How to assign roles with a command - discord.js

I wanted to give my bot the functionality to assign roles with a command

For example, +mod @user would give @user the role of Mod.

Code in my main.js :

if(command == 'mod'){
    client.commands.get('mod').execute(message, args);
}

Code in my mod.js file:

module.exports = {
    name: 'mod',
    description: "This command gives member the Mod role",
    execute(message, args){
        const member = message.mentions.users.first();
        member.roles.add('role ID xxxx');
    }
}

I get an error saying the member is empty. Am I doing something wrong?

I don't think it said member is empty. users don't have roles though, members have. So you will need to get the first mentioned member instead.

module.exports = {
  name: 'mod',
  description: 'This command gives member the Mod role',
  async execute(message, args) {
    const member = message.mentions.members.first();
    if (!member) {
      return message.reply('you need to mention someone');
    }
    try {
      await member.roles.add('ROLE_ID');
      message.reply(`${member} is now a mod 🎉`);
    } catch (error) {
      console.log(error);
      message.reply('Oops, there was an error');
    }
  },
};

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