【问题标题】:How to add shared cooldown to multiple discord.py commands如何为多个 discord.py 命令添加共享冷却时间
【发布时间】:2021-01-07 07:50:10
【问题描述】:

我目前正在使用

@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.py python-decorators


    【解决方案1】:

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

    遗憾的是没有关于它的文档,所以我不能给你链接,如果你有任何问题,你可以将它们添加到 cmets ↓

    【讨论】:

    • 幸运的是,我把它们放在了一个齿轮上,所以这应该很容易。你知道重置冷却是否也有效吗?如果 ctx.user 在白名单上,我有一个白名单检查,使用 after_invoke 重置冷却时间
    • 我不完全确定,你应该尝试一下
    猜你喜欢
    • 1970-01-01
    • 2021-04-21
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    相关资源
    最近更新 更多