首页 > 解决方案 > 只有在命令成功后才开始冷却 discord.py

问题描述

我一直在尝试找到只有在命令成功后才能发出冷却命令的方法。例如,在下面的代码中,它适用于冷却命令装饰器,只有在“now_amt”与“max_amt”达到相同之前,它才会发送“amount is too full”,但这是不成功的,如果用户使用另一个命令来降低“now_amt”,即使该命令没有执行任何操作,用户仍然需要等待全部时间。

我如何在代码中进行检查以确保命令已完成,然后它会开始冷却,直到您可以再次使用该命令?如果 now_amt 是最大值,那么它就不会开始新的冷却时间。

@client.command()
@commands.cooldown(1, 3600, commands.BucketType.user)
async def new(ctx):
    global now_amt
    now_amt += 1

    if now_amt >= max_amt:
        await ctx.send("Amount too full!")
        return
    await ctx.send(f'{now_amt}/{max_amt}')

now_amt = 0
max_amt = 5

标签: pythonvariablesdiscorddiscord.py

解决方案


根据文档,命令对象具有重置冷却时间的方法。你可以做的是从你的命令中引发一个错误,然后有一个错误处理程序来检测并重置。这是一个可能看起来像的示例。

import traceback # If you still want error traces for other errors
@client.command()
@commands.cooldown(1, 3600, commands.BucketType.user)
async def new(ctx):
    global now_amt
    now_amt += 1

    if now_amt >= max_amt:
        raise ValueError('Amount too full!')
    await ctx.send(f'{now_amt}/{max_amt}')

@new.error
async def new_error(ctx, error):
    # We must first check if its a command invoke error so
    # we dont get an AttrbiuteError, not all errors have a .original attribute
    if isinstance(error, commands.CommandInvokeError) and isinstance(error.original, ValueError):
        ctx.command.reset_cooldown(ctx)
    else:
        # If you want to have tracebacks printed for other errors, add this
        traceback.print_exception(type(error), error, error.__traceback__)

推荐阅读