How can I put a cooldown on commands/messages

Discussion in 'Plugin Development' started by flyingtacoz, Sep 2, 2012.

Thread Status:
Not open for further replies.
  1. Offline

    flyingtacoz

    Trying to reduce spam, how can I put something like a 1 second cool down in between saying commands and messages?
     
  2. Offline

    escortkeel

    You'll have to keep track of the time when the player last send a command, and then cancel it if it was too soon ago.
     
  3. Offline

    flyingtacoz

    How would I do this?
     
  4. Offline

    Tj3

    Create a HashMap of Strings (player names) and longs (timestamps). Each time a message is chatted, do the following:
    1. Check if the player is in the map: map.containsKey(player.getName())
    2. If they are, check if the number is more than X seconds before the last message time: ((System.currentTimeMillis()/1000) -map.get(player.getName())) < minimumTimeBetweenMessages
    3. If it was, then cancel the event: event.setCancelled(true)
    4. Then set the current time in the map so you know when their last message was: map.put(player.getName(), (long)(System.currentTimeMillis()/1000))
     
  5. Offline

    MrFigg

    Code:
    private HashMap<String, Date> cooldowns = new HashMap<String, Date>();
     
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
        if(cooldowns.containsKey(sender.getName())&&cooldowns.get(sender.getName()).getTime()>new Date().getTime()) {
            sender.sendMessage("You must wait a bit before using this command again.");
            return true;
        }
        if(!(sender instanceof Player)) {
            cooldowns.put(sender.getName(), new Date(new Date().getTime() + 60000))); // Replace 60000 with the cooldown time you want in miliseconds
        }
        // Do your command stuff here
    }
     
Thread Status:
Not open for further replies.

Share This Page