1

I am trying to send a message every x amount of seconds in a discord.js bot. I know how to do this put the problem I am having is that it is spamming messages even when I have slowmode enabled. How can I fix this?

client.on('message', message => {
if (message.content === '$ww) {
      let count = 0;
      let ecount = 0;
      for(let x = 0; x < 9000; x++) {
        message.channel.send(`hy`)
          .then(m => {
            count++;
          })
          
        }
      }
});
Guilherme Lemmi
  • 3,271
  • 7
  • 30
  • 30

1 Answers1

2

You can use setInterval() to repeat your function every X milliseconds. For example:

setInterval(() => {
 message.channel.send(`hy`).then(() => count++);
}, 10000);

setInterval(() => console.log('hey'), 1000)

The code you've provided is spamming because it is not waiting 10 seconds; it is counting from 0 to 9000 and for every count, it sends the message 'hy', so it quickly spams 9000 'hy' messages.

Lioness100
  • 8,260
  • 6
  • 18
  • 49
trolloldem
  • 669
  • 4
  • 9
  • It's important to note here that setInterval timers are not accurate. 10 seconds is approximation of when the event will trigger. In reality (because of thread priority, etc.) it could be less or more than this time. – Liam Sep 11 '20 at 10:21
  • You're true, but in the question there are not indication on the precision needed for the particular application. Also we are talking about X seconds and not smaller time units. Using Date() and some other logic could be the solution to this timing problem. This [question](https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript) is more accurate in this argument. – trolloldem Sep 11 '20 at 10:26