【问题标题】:Make the same cooldown for multiple discord.py bot commands?为多个 discord.py 机器人命令设置相同的冷却时间?
【发布时间】:2019-12-29 13:26:46
【问题描述】:

这是写在discord.py

我有多个类似于以下的命令:

@bot.command(name ="hi")
async def hi(ctx):
    link = ["https://google.com", "https://youtube.com"]
    chosen = random.choice(link)
    url = chosen
    embed = discord.Embed(title="Your Link", description=f"[Click Here]({url})", color=0x00ff00)
    if ctx.message.guild == None:
        await ctx.author.send('You can not use this command in your DM!')
        pass
    else:
        await ctx.author.send(embed=embed)

如果有人使用其中一个命令,则应为所有命令设置冷却时间(例如,如果使用!hi,则!hi!bye 都将应用冷却时间。

我知道你可以使用@commands.cooldown(1, 600, commands.BucketType.user),但这只会对当前命令应用冷却时间。

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    cooldowns 装饰器在代码中是这样定义的:

    def cooldown(rate, per, type=BucketType.default):
        def decorator(func):
            if isinstance(func, Command):
                func._buckets = CooldownMapping(Cooldown(rate, per, type))
            else:
                func.__commands_cooldown__ = Cooldown(rate, per, type)
            return func
        return decorator
    

    我们可以修改它,以便我们只创建一个在命令之间共享的Cooldown 对象:

    def shared_cooldown(rate, per, type=BucketType.default):
        cooldown = Cooldown(rate, per, type=type)
        def decorator(func):
            if isinstance(func, Command):
                func._buckets = CooldownMapping(cooldown)
            else:
                func.__commands_cooldown__ = cooldown
            return func
        return decorator
    

    我们将通过调用它来获取装饰器,然后将其应用于命令:

    my_cooldown = shared_cooldown(1, 600, commands.BucketType.user)
    
    @bot.command()
    @my_cooldown
    async def hi(ctx):
        await ctx.send("Hi")
    
    
    @bot.command()
    @my_cooldown
    async def bye(ctx):
        await ctx.send("Bye")
    

    【讨论】:

      猜你喜欢
      • 2017-07-08
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 2021-04-25
      • 2021-04-06
      • 1970-01-01
      • 2021-10-15
      • 2021-08-07
      相关资源
      最近更新 更多