Search code examples
javathread-sleeprate-limiting

Rate-limit calls to an IRC bot


I am working on a IRC bot that has the command !Scouter and it will generate a random number.... I already have that done, what I wanted to make was a cool down system to keep from people spamming it over and over again.

here is my code.

public class Twitchbot extends PircBot {
    Random dice = new Random();
    int number;

    for(int counter=1; counter<=1;counter++) {
        number = 1+dice.nextInt(9001);
        System.out.println(number + " ");
    }

    public Twitchbot() {
        this.setName("Blah");
    }

    public void onMessage(String channel, String sender, String login, String hostname, String message) {
       if (message.equalsIgnoreCase("!Scouter")) {
           sendMessage(channel,": The time is now " + sender + number);
           for(int counter=1; counter<=1;counter++) {
              number = 1+dice.nextInt(9001);
              System.out.println(number + " ");
              try {
                 Thread.sleep(5000);
              } catch(InterruptedException ex) {
                Thread.currentThread().interrupt();
              }
           }
       }
    }
}

I tried using this code for a cool down

 try {
    Thread.sleep(5000);
 } catch(InterruptedException ex) {
     Thread.currentThread().interrupt();
 }

but all it did is do the code after 5 seconds of sleeping. I don't want the command !Scouter to register during that cool down. is there a better way of doing it?


Solution

  • You could save the current system-time on a successfull call using:

    lastCall = System.currentTimeMillis();
    

    and before, you check

    if(System.currentTimeMillis() - lastCall >= DELAY)
    

    where DELAY is a time in milliseconds (1 second equals 1000 milliseconds).

    if that statement is true, set lastCall to the current time:

    lastCall = System.currentTimeMillis();
    

    and call the normal code.


    It would look something like this:

    long lastCall = 0L; //Initializing 
    
    public void onMessage(String channel, String sender,
            String login, String hostname, String message) {
    
       if (message.equalsIgnoreCase("!Scouter")) {
           if(System.currentTimeMillis() - lastCall >= 5000)
           {
               lastCall = System.currentTimeMillis(); // Set lastCall again
               sendMessage(channel,": The time is now " + sender + number);
               for(int counter=1; counter<=1;counter++) {
                 number = 1+dice.nextInt(9001);
                 System.out.println(number + " ");
               }
           }
       }
    }