J
J
joposraka22021-01-23 00:07:55
Python
joposraka2, 2021-01-23 00:07:55

How do I make a command in discord.py usable once per hour/day/year?

Here is the command

@client.command()
async def beg(ctx):
    denga = random.randint(0,100)
    user = ctx.author
    hour=None
    mbalance=collection.find_one({"_id":user.id})["balance"]
    if hour==None:
        collection.update_one({"_id":user.id},
        {"$set": {"balance":mbalance+denga }})
        await ctx.send(embed=discord.Embed(
        description=f'**Копошась на полу вы нашли {denga} монет**'))
    else:
        await ctx.send("Вы можете использовать эту команду лишь раз в час!")

how to make it so that when re-used in less than an hour, the bot sends a message that you need to wait?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Nevzorov, 2021-01-23
@joposraka2

Use a decorator

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

@client.command()
@commands.cooldown(1, 60, commands.BucketType.user)  # Один раз в 60 секунд на пользователя (глобально)
async def cmd(ctx, ...):
    ...

To send a message when a command is called in cooldown, you need to handle the commands.CommandOnCooldown exception :
@client.listen("on_command_error")
async def cooldown_message(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send(f"{ctx.command.qualified_name} можно использовать только {error.cooldown.rate} раз в {error.cooldown.per} секунд. Попробуйте через {error.retry_after} секунд.")

If you need to store cooldowns between restarts - in this case, you will most likely have to create your own implementation. The simplest option is to store the current time as an integer and compare it with the current time on the next execution

A
Alexander, 2021-01-23
@Alexandre888

use python-crontab to implement time actions.
and to see if the command is repeated / not used - connect the .json file / database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question