简体   繁体   中英

Discord.js add custom role to a mentioned user

I have a problem adding a custom role to a user. The command should look like this: ${prefix}addrole @user <role name> . The user should receive a custom role and the bot should send a confirmation message. This is my code:

client.on('message', (message) => {
  if (message.content.startsWith(`${prefix}addrole`)) {
    module.exports.run = async (bot, message, args) => {
      if (!message.member.hasPermissions('MANAGE_MEMBERS'))
        return message.reply("You don't have acces!");
      const rMember =
        message.guild.member(message.mentions.user.first()) ||
        message.guild.members.get(args[0]);
      if (!rMember) return message.reply("I couldn't find that user!");
      const role = args.join(' ').slice(22);
      if (!role) return message.reply('Please type a role!');
      const gRole = message.guild.roles.find(`name`, role);
      if (!gRole) return message.reply("I couldn't find that role!");

      if (nMember.roles.has(gRole.id));
      await nMember.addRole(gRole.id);

      try {
        nMember.send(`You received ${gRole.name}`);
      } catch (e) {
        message.channel.send(
          `The user <@${rMember.id}>, received the role ${gRole.name}. We tried to dm him but he disabled them.`
        );
      }
    };
    module.exports.help = {
      name: 'addrole',
    };
  }
});

The first problem I found comes from these two lines:

if(nMember.roles.has(gRole.id));
    await(nMember.addRole(gRole.id));

First of all:

await is not a function, and thus you don't need parentheses. If you do put parentheses, you will get an error. Instead, just use:

await nMember.addRole(gRole.id)

Second of all:

GuildMember.roles.has is deprecated. discord.js v12+ uses Managers , so you will have to add the cache property. Write:

if (nMember.roles.cache.has(gRole.id))

This also applies to a line further up in the code:

let gRole=message.guild.roles.find(`name`, role);

Replace that with

let gRole = message.guild.roles.cache.find(r => r.name = role)

Third of all:

This issue is also seen in the second line of code I quoted:

await nMember.addRole(gRole.id)

addRole() is also deprecated, instead use:

await nMember.roles.cache.add(gRole.id)

Fourth of all, and I barely caught this:

MANAGE_MEMBERS is no longer a permission flag. Instead, use MANAGE_ROLES .


Overall the code could be cleaned up a bit, but I think that's all the errors I found.

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