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?

11 thoughts on “How to assign roles with a command – discord.js”

  1. 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');
        }
      },
    };
    
    Reply

Leave a Comment