首页 > 解决方案 > 如何为多个 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

标签: discord.pypython-decorators

解决方案


最简单的方法是将所有命令放在 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>


推荐阅读