【问题标题】:Command cooldown in discord.pydiscord.py 中的命令冷却时间
【发布时间】:2021-03-11 22:31:15
【问题描述】:

我希望我的 discord 机器人的命令有冷却时间。我尝试了其他方法,但它们似乎都不适用于我所拥有的。

@client.event
async def on_message(message):
  if message.content == 'shear sheep':
    await message.channel.send('you sheared your sheep, gaining 1 wool.')
    #cooldown?

【问题讨论】:

  • 如果你使用commands.Bot接口,并使用装饰器创建命令,你可以使用内置的冷却系统,否则你需要为冷却做某种形式的映射

标签: python discord bots discord.py


【解决方案1】:

最好使用@bot.command,而不是event。然后,你必须把@commands.cooldown(1, {seconds off cooldown}, commands.BucketType.user)放在@bot.command下面

例子:

@bot.command
@commands.cooldown(1, 15, commands.BucketType.user)
async def shearsheep(ctx):
    await ctx.send('you sheared your sheep, gaining 1 wool.')

然后,您可以创建一个错误处理程序,当您尝试使用命令时会发送一条消息,但它会处于冷却状态,例如:

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send('This command is on cooldown, you can use it in {round(error.retry_after, 2)}')

我认为这是最简单的方法。

【讨论】:

  • 是的,但我想使用我的方法,因为我还有其他事情要考虑,比如如果有人说“嗨”,就发送消息“你好”
  • 好的,那么您可以创建time.sleep((x seconds)),但您的机器人不会发送错误消息。但我不擅长 Discord.py,我认为你可以这样做。
【解决方案2】:

由于您正在与 on_message 交互以进行冷却,因此您需要使用 commands.CooldownMapping.from_cooldown() 创建自定义冷却映射(注意:这未包含在文档中,这是 RAPPTZ 提供的内容),请使用方法get_bucket(message) 并将您的消息对象传递给消息,然后在存储桶上使用update_rate_limit() 来检查您是否受到速率限制(返回一个布尔值)。但是,该系统根本不可靠,因为它也会触发普通消息的冷却时间。使用命令要容易得多,因为它有完整的文档,但缺点是不能在 on_message 中使用。

这两个系统都有缺点,但最终使用命令更有文档且更强大

【讨论】:

【解决方案3】:

我建议使用变量来跟踪使用该命令或冷却前的天气。

import time
cooldown = True

@client.event
async def on_message(message):
    global cooldown
    if message.content == 'shear sheep' and cooldown:
        cooldown = False
        await message.channel.send('you sheared your sheep, gaining 1 wool.')
        time.sleep(1)
        cooldown = True

这将为所有用户添加冷却时间,如果您想为每个用户添加冷却时间,请使用表格检查单个用户是否使用过该命令的天气。

import time
cooldown = []

@client.event
async def on_message(message):
    global cooldown
    if message.content == 'shear sheep' and cooldown.count(message.author.id) == 0:
        cooldown.append(message.author.id)
        await message.channel.send('you sheared your sheep, gaining 1 wool.')
        time.sleep(1)
        cooldown.remove(message.author.id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2021-04-25
    • 2021-03-30
    • 2021-05-15
    • 2019-02-17
    相关资源
    最近更新 更多