python - 只有在命令成功后才开始冷却 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
解决方案
根据文档,命令对象具有重置冷却时间的方法。你可以做的是从你的命令中引发一个错误,然后有一个错误处理程序来检测并重置。这是一个可能看起来像的示例。
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__)
推荐阅读
- typescript - “对象属于‘未知’类型。” 在 RxJS 动作中
- php - Laravel 8 组件 @props 指令不起作用
- mysql - MySQL InnoDB Gap Lock on Update 与 PK 的 where 子句?
- javascript - Javascript:解析 xml 以在节点内获取匹配的标记值
- android - 在 Android 上运行分屏视图
- javascript - 如何从 JavaScript 中奇偶索引中的字符串替换特定部分?
- c++ - 调用堆栈和堆栈有什么区别?
- spring-batch - 如何使用 Spring Batch Integration 在 IntegrationFlow 中添加自定义标头?
- postgresql - 如何平均单个 PostGIS 栅格表中的所有波段?
- angular - 从服务返回的地理位置值未定义