4
votes

I have looked at other posts in regards to how to make a cooldown command. One answer did exactly what I wanted, but that was only because I did exactly what they did. Now I want to officially implement the command into my Discord bot. I noticed that the cooldown command that I tested only worked under @client.command rather than @client.event (client is the object). I have all of my commands listed under the event thing, so I need help on how to add the cooldown command without having to rewrite a lot of things. This is what I have so far regarding the cooldown command.

from discord.ext.commands import Bot
from discord.ext import commands

client = Bot(command_prefix="?")

@client.event
@command.cooldown(5, 30, commands.BucketType.user)
async def on_message(message):
    if message.content.upper().startswith("?HELLO"):
        msg = 'Hello {0.author.mention} :banana:'.format(message)
        await client.send_message(message.channel, msg)

@on_message.error
async def on_message_error(self, error, ctx):
    if isinstance(error, commands.CommandOnCooldown):
    msg = ':exclamation: This command is on cooldown, please try again in {:.2f}s :exclamation:'.format(error.retry_after)
    await self.send_message(ctx.message.channel, msg)

I'm just using one command as an example to show what kind of format I have. I get the error with the @on_message.error (it was a trial an error thing, so I didn't expect it to work). I want to set a cooldown for 30 seconds after 5 consecutive attempts of the same command as well as an error message for the bot to say in response with the timer. I don't really want to have to rewrite the whole thing just for one command to work considering how far I've come to make this bot :/

1
If you want to use the commands features, you have to use commands. Also the cooldown decorator you have will allow a user to invoke the command no more that 5 times in any 30s period. - Patrick Haugh
I understand. I don't mind using a completely different cooldown command than I have right now. That was just a command that I tested from another post. - Jango
I would recommend refactoring your commands into commands.commands anyways. Otherwise, you'll have to have some global variable that stores the timestamps of the last x previous messages, and update that whenever you receive a message. You might want to refer to the way cooldowns are implemented for commands in the discord.py implementation. - Patrick Haugh

1 Answers

1
votes

You should add:

@commands.cooldown(1, 30, commands.BucketType.user)

This will add a ratelimit of 1 use per 30 seconds per user.

You can change the BucketType to default, channel or server to create a global, channel or server ratelimit instead, but you can only have 1 cooldown on a command.

This will also cause a CommandOnCooldown exception in on_command_error