Reputation: 247
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");
}
}
});
Upvotes: 0
Views: 991
Reputation: 8402
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))
Upvotes: 2