Home > other >  How can I remove a specific role from everyone that has it in Discord.js v13
How can I remove a specific role from everyone that has it in Discord.js v13

Time:05-26

I want my bot to remove a specific role from everyone that has it when a message is sent in a channel

client.on('messageCreate', async message => {

        if(message.channel.id === '954375143965216869'){ //counting
            message.guild.roles.get('944674567811645472').members.map(m=>m.member.id).delete();

            
        }
})

I'm using discord.js v13 and node.js v16.4.2

CodePudding user response:

This should work, it'll fetch all the members in the guild and for each member it will remove the role specified. Also note that you'll need the proper gateway intents to run this and depending on the guild size, it may take multiple minutes. I wouldn't recommend running it every time a message is sent as it'll get you rate limited extremely fast.

message.guild.members.fetch().then(m => {
    m.forEach(member => {
        let role = message.guild.roles.cache.get("roleid");
        member.roles.remove(role)
    })
})

Also, if your guild is way too large that it gets too slow because of rate limits, try the code below so each change has a delay.

message.guild.members.fetch().then(m => {
    m.forEach(member => {
        let role = message.guild.roles.cache.get("roleid");
        setTimeout(() => {
            member.roles.remove(role)
        }, 1000);
    })
})

CodePudding user response:

As SP73 said, putting this on your messageCreate event will get you ratelimited fast. Try putting this on your ready event instead. This will get every member of the provided server on the cache (I'm sure you don't have a verified bot so discord.js would most likely save it on the cache for you) and only select those who have the role, then for each one, at a delay of 1500 millisecondes (1 and half second), remove the role from them.

client.on('ready',() =>{
  let n = 0;
  let { members } = client.guilds.cache.get("GUILD_ID");
  members.filter(m => m.roles.cache.has("ROLE_ID")).forEach(member => {
    setTimeout(() => member.roles.remove("ROLE_ID"), (  n) * 1500);
  })
})
  • Related