繁体   English   中英

discord.py 中的命令冷却

[英]Command cooldown in discord.py

我希望我的 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?

如果您使用@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)}')

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

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

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)

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM