如何为我的不和谐服务器上提到的每个用户添加角色

时间:2021-02-03 17:58:42

标签: javascript node.js discord discord.js

我当前的代码是这样工作的。如果我输入 command @rolename @user,我的机器人会为提到的用户提供提到的角色。

但我想为每个提到的用户添加提到的角色:command @rolename @user1 @user2 @user3

这是我的代码,但它只将角色添加到第一个成员:

const { MessageEmbed } = require('discord.js')

module.exports = {
  name: "addrole",
  aliases: ["role", "P!role"],
  category: "moderation",
  description: "Add role to any user",
  run: async (client, message, args) => {
   if (!message.member.hasPermission("MANAGE_ROLES")) {
      return message.channel.send("sorry you need permission to mute someone");
    }
    if (!message.guild.me.hasPermission("MANAGE_ROLES")) {
      return message.channel.send("I do not have permission to mute");
    } 
    let target = message.mentions.members.first();
    
    if(!target) return message.reply(`<:no:677902165859237894>please mention user!`)
    
    let arole = message.mentions.roles.first();
    
    if(!arole) return message.reply(`<:no:677902165859237894>please mention role for add!`)
    
    let ticon = target.user.avatarURL({ dynamic: true, size: 2048 });
    let aicon = message.author.avatarURL({ dynamic: true, size: 2048 });
    
      const embed = new MessageEmbed()
      
      .setColor("RANDOM")
      .setDescription(`<a:ok_:731369076315652167>changed role for ${target.user.username} added ${arole}`)
      
      await message.channel.send(embed)
      
      target.roles.add(arole)
  }
}

1 个答案:

答案 0 :(得分:1)

message.mentions.members returns a collection 以便您可以使用 .each 方法为每个提到的成员添加角色:

if (!message.member.hasPermission('MANAGE_ROLES')) {
  return message.channel.send('sorry you need permission to mute someone');
}
if (!message.guild.me.hasPermission('MANAGE_ROLES')) {
  return message.channel.send('I do not have permission to mute');
}

const { members } = message.mentions;

if (!members.size) {
  return message.reply(`<:no:677902165859237894> please mention a user!`);
}

const role = message.mentions.roles.first();

if (!role) {
  return message.reply(
    `<:no:677902165859237894>please mention role for add!`,
  );
}

const embed = new MessageEmbed().setColor('RANDOM');

members.each((member) => {
  member.roles.add(role);
  embed.setDescription(
    `<a:ok_:731369076315652167> role changed for ${member.user}, added ${role}`,
  );
  message.channel.send(embed);
});