0

So I have this command, that'll basically mute everyone in a voice channel, besides people with a certain role, and it works perfectly!

But what I also want it to do it take like a second or two inbetween mutes so I'm not API spamming, and get banned from using discord.js, so how would I do that?

Code:

message.delete({ timeout: 150 });
const vc = message.member.voice.channel;
if (!vc) return message.reply("You must be in a voice channel to run this!").then(msg => {
    msg.delete({ timeout: 5000 })
})
    let users = vc.members.filter(member => !member.roles.cache.has("753465550604075039")).map(fn => `<@${fn.id}> | ID: ${fn.id}`)
    let mutinguser = vc.members.filter(member => !member.roles.cache.has("753465550604075039"))
    if (mutinguser.size === 0) return message.channel.send("There's no one to mute!")
    if (mutinguser.size > 10) return message.channel.send(`I can only mute 10 people at a time! There's ${mutinguser.size} users in this voice channel!`)
    mutinguser.array().forEach(m => m.voice.setMute(true))
    let muting = new Discord.MessageEmbed()
        .setColor("GREEN")
        .setTitle(`Muting Users in [${vc.name}]`)
        .setDescription(users)
        .setFooter(` Users Muting: ${users.length} \n Total Users: ${vc.members.size}`)
    message.channel.send(muting)
anzepintar
  • 126
  • 1
  • 10
kasprg
  • 7
  • 2

1 Answers1

1

You can't exactly add delay in JS because the code runs in the context of the browser's UI thread, and a delay would cause a UI freeze.

What you can do, is schedule a function to run a number of milliseconds in the future.

For example:

let arr = [ "item 1", "item 2", "item 3" ];

function handleNext(idx) {
    if (idx == arr.length) {
        return;
    }

    console.log(arr[idx]);

    setTimeout(() => {
        // call handleNext() again for the next element
        handleNext(idx + 1);
    }, 500);
}

// kick it off
handleNext(0);

The above code should print "item 1" to the console immediately, and then 500ms later print "item 2", and after another 500ms - print "item 3".

Note that the code will not get "stuck" on the call to handleNext(0); it will invoke it and then continue past it. This means that the UI will remain responsive. It also means that other code can run during the 500ms delay, so you need to make sure it doesn't interfere with the variables handleNext() accesses in a hazardous way.

obe
  • 7,378
  • 5
  • 31
  • 40
  • Thanks, but how can I implement my muting feature into this code? How would I replace my console.log with mutinguser.array().forEach(m => m.voice.setMute(true)) – kasprg May 04 '21 at 20:40
  • You could store `mutinguser.array()` in a variable (e.g. `arr`) and then use the above technique to iterate through it, and call `arr[idx].voice.setMute(true)` in each iteration. – obe May 04 '21 at 20:42
  • omg that worked tysm – kasprg May 04 '21 at 20:46