Skip to content Skip to sidebar Skip to footer

Starting Discord.py Command Cooldown Only If Condition Is Met

I want the cooldown of one of my commands to start only if a condition in the function is met, like so: @bot.command async def move(ctx, destination): destinations=['d1', 'd2',

Solution 1:

There could be a lots of ways to craft your own cooldowns, here is a simple one that can do the trick. The idea behind it is for the bot to "remember" the last time someone used this specific command and to check this time before allowing the player to move.

from datetime import datetime, timedelta    

on_cooldown = {} # Dictionary with user IDs as keys and datetime as values
destinations=["d1", "d2", "d3"] # List of valid arguments for the command
move_cooldown = 5# cooldown of the move command in seconds@bot.command()asyncdefmove(ctx, destination):

    if destination in destinations:
        author = ctx.author.idtry:
            # calculate the amount of time since the last (successful) use of the command
            last_move = datetime.now() - on_cooldown[author] 
        except KeyError:
            # the key doesn't exist, the player used the command for the first time# or the bot has been shut down since
            last_move = None
            on_cooldown[author] = datetime.now()

        if last_move isNoneor last_move.seconds > move_cooldown:
            # move(...)
            on_cooldown[author] = datetime.now() # the player successfully moved so we start his cooldown againawait ctx.send("You moved!")
        else:
            await ctx.send("You're still on cooldown.")    

    else:
        await ctx.send("This is not a valid destination")

Note : you may or may not need to remove the parentheses after the @bot.command decorator.

Solution 2:

Idk if this is what you're looking for, but there's a way to make the cooldown only activate after the code parses properly with this bit of code:

@bot.command(cooldown_after_parsing=True)
@commands.cooldown(rate, per, type=<BucketType.default: 0>)

you can find the document for commands.cooldown here

and the doc for cooldown_after_parsing here

Post a Comment for "Starting Discord.py Command Cooldown Only If Condition Is Met"