如何为多个 discord.py 命令添加共享冷却时间

How to add shared cooldown to multiple discord.py commands

我目前正在使用

@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))

遗憾的是没有关于它的文档所以我不能给你link,如果你有任何问题可以在评论中添加它们↓