简体   繁体   中英

Adding role to all members who has another role?

I want to run a command on my discord bot and add a secondary role to all members which have the predefined role.

Its gonna be like this. All members have the X role are gonna be assigned to the Y role.

I tried to write to code but I failed so I am writing my code as pseudo-code below any help will be great.

const userID = "1234"; //this is my userid so only I will be able to use this command
let roleID1 = "xxxx";
let roleID2 = "yyyy";
client.on("message", function (message) {
  if (message.author.id === userID) {
    if (message.content === "!setrole") {

      // Code for taking the list of all members with role xxxx.
      // Code for assigning all those people to the role yyyy.

      message.channel.send("Roles assigned");
    }
  }
});

Try this:

// iterate a function through all members of the guild
message.guild.members.cache.forEach((member) => {
  if (member.roles.cache.has(roleID1) // if member has x role
     member.roles.add(roleID2); // give y role
});

You could also use Array.prototype.filter() ; although there's no difference in execution, it might be faster (but I really have no idea):

message.guild.members
  .filter((member) => member.roles.cache.has(roleID1))
  .forEach((member) => member.roles.add(roleID2))

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