0

I'm making a command where a specific role gets added to all members. The problem is that, the .forEach loop is way too fast for the API.

I know that I'll probably have to solve this with a setIntervall somehow.

module.exports.run = async (bot, message, args, level) => {
    if (!args || args.length < 1) return message.reply("Must provide a role to give. Derp.");
    

    let role = message.guild.roles.find(r => r.name == args[0])

    if (!role) return message.channel.send(`**${message.author.username}**, role not found`)
        
        let msg = await message.channel.send("Ur lazy")
        
        message.guild.members.filter(m => !m.user.bot).forEach(member => member.addRole(role))
        

        message.channel.send(`**${message.author.username}**, role **${role.name}** was added to all members`)
        msg.delete();
        
}

Currently this just gives Timeout errors, which is highly unwanted, so I need to do the same thing but slower.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
VIINZ
  • 1
  • Possible duplicate of [Add a delay after executing each iteration with forEach loop](https://stackoverflow.com/questions/45498873/add-a-delay-after-executing-each-iteration-with-foreach-loop) – slothiful Jul 06 '19 at 20:02
  • My problem is, that I'm not iterating numbers, I'm giving a role to each member that gets called in the forEach loop. – VIINZ Jul 06 '19 at 20:17
  • The code in the answer provided to that question doesn't output numbers. `i` is simply a step variable to act as the index with each iteration. At least in my opinion, the same concept is applicable here, it may require just a few tweaks. – slothiful Jul 06 '19 at 20:25
  • I mean I might just be stupid, but could you show me how you mean to apply this to my case? Sorry if this bothers you. – VIINZ Jul 06 '19 at 20:27

1 Answers1

0

can you expalin? if you mean you need to wait until all members added you can use :


module.exports.run = async (bot, message, args, level) => {
    if (!args || args.length < 1) return message.reply("Must provide a role to give. Derp.");


    let role = message.guild.roles.find(r => r.name == args[0])

    if (!role) return message.channel.send(`**${message.author.username}**, role not found`)

        let msg = await message.channel.send("Ur lazy")

        const members = message.guild.members.filter(m => !m.user.bot);
     for(let i = 0; i < members.length; i++){
       await new Promise(resolve => setTimeout(() => {
           members[i].addRole(role)
           resolve();
         },1000))
     }



        message.channel.send(`**${message.author.username}**, role **${role.name}** was added to all members`)
        msg.delete();

}