Search code examples
javascriptdiscorddiscord.js

How to add role to user after message is sent


I am using Discord.js to make my bot. I want to add a role to a user after they use a command. The command is !attack it will "kill" the person you pinged.

I think it might have something to do with Intents but I'm not sure. Here are my Intents right now,

const client = new Discord.Client({ 
    intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
  }, {
    partials: ["MESSAGE", "CHANNEL", "REACTION"]
  });

Also, here is the code for the !attack command,

var user;
var rollNum;
var role;

module.exports = {
  name: "attack",
  category: "info",
  permissions: [],
  devOnly: false,
  run: async ({client, message, args}) => {
    user = message.content.toLowerCase().split(" ");
    if(user[1] === `<@${message.author.id}>`){
      message.reply("You are not allowed to kill yourself.")
    }
    else{
      message.reply("Rolling...");
      rollNum = Math.floor(Math.random() * 10);
      if(rollNum >= 4){
        message.reply(`${user[1]} could not be killed. They are too strong for you lol.`);
      }
      else{
        message.reply(`${user[1]} is dead... R.I.P.`);
      }
    }
  }
}

Solution

  • To give a user a role, you need the MANAGE_ROLES permission and the bot also cannot give a role which has a higher position than its own. Other than that, the syntax for adding a role is pretty simple. First, you have to fetch the role, then you can add it to the user. To fetch the role, you can use .get() if you have the role id or .find() if you have the role name. Your code might look something like this:

    const role = message.guild.roles.cache.get('roleid') // Or message.guild.roles.cache.find(r => r.name === 'rolename')
    message.member.roles.add(role.id).then(m => {
        message.channel.send('Successfully added the role!')
    }).catch(err => {
        message.channel.send('There was an error while adding the role!')
    })