Skip to content
Advertisement

How to make a timed bool in discord.js

I want my bot to reply “Good morning” whenever someone says “good morning”, for example. I’ve got all that figured out, but now I wanted to put a timer onto it and it is getting a bit more complicated. I want the timer to be for absolutely everyone on the server. If anyone says good morning then let’s make the bot wait 3 seconds, for example. I’ve tried a couple different solutions but none work so I would see if I could get any help here.

let goodmorning = true;
client.on("message", (message) => {
if (!message.author.bot) {
     if (message.content == "good morning") {
            if (goodmorning == true) {
                message.channel.send("Good morning");
                setInterval(() =>
                goodmorning = false, 3000);
            } else {
                setTimeout(goodmorning = true, 3000);    
            }
     }
}
});

I have also tried this other solution that I found online. I got “Syntax error: Unexpected Identifier” for this one on line 3 even though line 5 is very similar:

client.on("message", (message) => {
if (!message.author.bot) {
long lastTrueTime;
boolean timedgm() {
        long now = System.currentTimeMillis();
     if (message.content == "good morning") {
            lastTrueTime = now;
            return true;
        }

        if (lastTrueTime+3000<now)
            return false;
        return true;
}
        message.channel.send("Good morning");
  }
});

Thank you for all the help in advance.

Advertisement

Answer

It seems like you are wanting a global cooldown for this command.

This can easily be done by setting the value to false immediately, then 3000ms later turn the value back to true

let goodmorning = true;
client.on("message", (message) => {
  if (!message.author.bot) {
    if (message.content == "good morning") {
      if (goodmorning == true) {
        message.channel.send("Good morning");
        goodmorning = false;
        setTimeout(() => goodmorning = true, 3000);
      }
    }
  }
});
Advertisement