How to set cooldown to all commands in a Cog discord.py

Viewed 156

I have a discord bot with a Cog and I want to add a cooldown to all commands on this Cog.

I know I can add the cooldown by adding a decorator in the command function

@commands.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def ping(self, ctx):
    await ctx.send('Pong!')

but I don't want to add this decorator to all my functions manually because I have too many functions.

is there any way to add a cooldown to all these functions at once? maybe using something like the cog_before_invoke function?

I've even tried to create my own decorator for this, but I didn't manage to add it to the cog_before_invoke function or any other way to do this to multiple commands without add the code manually to each command

def my_cooldown(rate, per, type=commands.BucketType.default):
        def decorator(func):
            if isinstance(func, commands.Command):
                func._buckets = commands.CooldownMapping(commands.Cooldown(rate, per, type))
            else:
                func.__commands_cooldown__ = commands.Cooldown(rate, per, type)
            return func
        return decorator
1 Answers

You can use the sleep() method of the built-in time module.

import time

# The regular stuff

@commands.command()
async def your_func(self, ctx):
    # The code
    time.sleep(5)

This will pause the execution of your code completely so no other command can be called either.

Related