discord.py - 如何为多个 discord.py 命令添加共享冷却时间
问题描述
我目前正在使用
@commands.cooldown(1, 60, bucket)
Discord.py 命令的装饰器,这部分工作。假设我有两个单独的功能:func_a()
和func_b()
. 我需要它,因此当用户调用其中一个func_a()
或 func_b()
将冷却时间应用于两者时。
示例:用户调用func_a()
,用户等待 10 秒,但冷却时间为 60 秒。用户调用func_b()
,机器人回复“请等待 50 秒以使用此命令”
编辑: 使用下面的解决方案,对于那些想要黑名单(或白名单)功能的人,将代码更改为以下内容:
async def cog_check(self, ctx):
bucket = self._cd.get_bucket(ctx.message)
retry_after = bucket.update_rate_limit()
if ctx.author.id not in self.blacklist:
return True
else:
if retry_after:
# You're rate limited, send message here
await ctx.send(f"Please wait {round(retry_after)} seconds to use this command.")
return False
return True
解决方案
最简单的方法是将所有命令放在 Cog 中,然后使用commands.CooldownMapping.from_cooldown
class SomeCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._cd = commands.CooldownMapping.from_cooldown(1, 60, commands.BucketType.user) # Change it accordingly
async def cog_check(self, ctx):
bucket = self._cd.get_bucket(ctx.message)
retry_after = bucket.update_rate_limit()
if retry_after:
# You're rate limited, send message here
await ctx.send(f"Please wait {round(retry_after, 2)} seconds to use this command.")
return False
return True
@commands.command()
async def foo(self, ctx):
await ctx.send("Foo")
@commands.command()
async def bar(self, ctx):
await ctx.send("Bar")
@foo.error
@bar.error
async def cog_error_handler(self, ctx, error):
if isinstance(error, commands.CheckFailure):
pass # Empty error handler so we don't get the error from the `cog_check` func in the terminal
bot.add_cog(SomeCog(bot))
遗憾的是没有关于它的文档,所以我不能给你链接,如果你有任何问题,你可以在评论中添加它们↓</p>
推荐阅读
- java - 如何在 Eclipse IDE 中的内部类上使用 @UtilityClass lombok 注释
- selenium-chromedriver - 如何在空手道中使用 chromedriver 获得隐身模型
- javascript - 相关下拉列表 - 面积计算单位
- laravel - crontab 并没有真正开始计划
- android - 通过房间向数据库插入数据时崩溃:原因:android.database.sqlite.SQLiteConstraintException:UNIQUE 约束失败
- c# - 使用 C# 的 Windows 窗体应用程序中的折线图问题
- docker - 创建依赖于两个项目的 docker 镜像
- spring-boot-test - 当我运行 @SpringBootTest 我得到空结果
- json - 在反应中获取详细的json
- python - 烧瓶导入错误