Search code examples
discord.jsroles

How do you assign any role to a user in discord.js?


I don't want a command that whenever you do -role, it already has only one in place to give to a user. I would like one that whatever you put a role as the second argument, it gives that user that role (unless of course that role doesn't exist). So if you do -role @user Blue, it gives them the 'Blue' role, if you do -role @user Red, it gives them the 'Red' role.

I guess best similarity to this would be the Dyno bot, whatever role you put as the second argument, it gives that role to the user.


Solution

  • Try the following:

    I suppose you use the command handler from the discordjs guide, so the args array is the array of words (arguments) after the command itself.

    //search the role based on the name that the user provided:
    let role = message.guild.roles.cache.find(role => role.name === args[1]);
    //if the role doesn't exist, create it
    if (!role) {
      role = await message.guild.roles.create({ data: { name: args[1] } });
    }
    //get the mentioned user
    const member = message.mentions.members.first();
    //add the role to the user
    member.roles.add(role);