【问题标题】:Cooldowns in discord.py with on_message带有 on_message 的 discord.py 中的冷却时间
【发布时间】:2021-11-16 04:54:59
【问题描述】:

所以,我基本上搞砸了。这是我第一次尝试不和谐的机器人,我已经在 on_message 中完成了我的所有代码,它检查了消息的内容以查看它是否与命令名称匹配(下面的示例)。我添加了一些命令,它们很长,我真的不想重写它。有什么办法可以解决这个问题还是我必须重写它?

  if message.content.lower().startswith("!test"):  
    await message.channel.send(db[str(message.author.id)])

我正在做的简单示例,只是一个测试命令。

我尝试过查看其他问题,但我要么:不想这样做,要么不明白人们在说什么。

任何帮助将不胜感激,因为我是 discord.py 的新手;我可能需要用更简单的术语解释一下。

【问题讨论】:

  • 我建议您亲自重写,您可以移植到正确的设置,而与您已有的设置几乎没有偏差。核心代码将完全相同,只是设置不同。推迟了你会后悔的。
  • 你应该从 Discord.py 升级到 Pycord。 Pycord 是 Discord.py 的维护版本。

标签: python discord discord.py


【解决方案1】:

你可以这样做:

import asyncio
users_on_cooldown = [] # Consider renaming this if you are going to have multiple commands with cooldowns.
def on_message(msg):
    if msg.content.lower().startswith("!test") and not msg.author.id in users_on_cooldown:  
        await msg.channel.send(db[str(msg.author.id)])
        users_on_cooldown.append(msg.author.id)
        await asyncio.sleep(20) # time in seconds
        users_on_cooldown.remove(msg.author.id)

既然您说您是初学者,请注意,如果您执行另一个带有单独冷却时间的命令,请使用另一个变量 users_on_cooldown,可能类似于 ban_cmd_cooldowntest_cmd_cooldown

工作原理 使用该命令时,会将用户添加到列表中,并在一定秒数后将其删除。运行命令时,会检查用户是否在列表中。

注意:当机器人被重置时,冷却时间也会被重置。

如果您对此有任何疑问,请随时在下面的 cmets 中提问。

【讨论】:

  • 这听起来很愚蠢,但asyncio.sleep(20) 怎么会出现无法识别的情况——我需要添加任何导入吗?还有,这和 time.sleep 一样吗?如果是这样,那不是停止所有代码,意味着不能使用其他命令吗?
  • 抱歉,忘记说明您需要导入 asyncio。我忘了等待它。它不会阻塞(停止代码)。请参阅我编辑的答案。 @没人
【解决方案2】:

这里如何使用

@client.command()
@commands.cooldown(1, 60, commands.BucketType.user)
async def test(ctx):
    await ctx.send(db[str(message.author.id)])

(1, 60, commands.BucketType.user) 表示每 60 秒 1 条消息或 60 秒冷却时间。

我建议你重写你的机器人。这可能需要一些时间,但值得。

【讨论】:

  • discord.ext.commands 不再使用client。考虑使用bot.commandbot = commands.Bot()
  • 也许可以澄清commands.BucketType.user 的含义。
  • 感谢您的帮助,我知道 commands.BucketType.user 是什么意思,但我真的不明白两件事:ctx 是什么以及当用户输入命令时如何调用它?很抱歉,这听起来很愚蠢;我只是有点习惯没有任何库的普通 python。
  • ctx 是上下文
猜你喜欢
  • 2021-05-02
  • 2022-01-16
  • 2021-03-25
  • 2018-10-21
  • 2021-05-15
  • 1970-01-01
  • 2020-10-14
  • 2021-03-11
相关资源
最近更新 更多