首页 > 解决方案 > 为多个 discord.py 机器人命令设置相同的冷却时间?

问题描述

这是写在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使用,冷却时间将应用于两个!hiAND !bye

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

标签: pythondiscorddiscord.py

解决方案


这是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")

推荐阅读