向Discord(py)Bot命令添加大冷却时间

2024-10-04 01:30:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Discord Python API,并尝试执行bot命令。但是,我希望此命令可以在每个用户8小时内仅使用一次。 所以,我做了这样的事情:

@bot.command()
@commands.cooldown(1, 28800, commands.BucketType.user)
@commands.has_any_role('role1', 'role2')
async def treasureChest(context):
    chosenList = random.choices(
     population=[1, 100, 200, 300, 500, 700, 1000, 5000],
     weights=[0.24, 0.249, 0.2, 0.15, 0.1, 0.05, 0.01, 0.001],
     k=1)

  earnedCoins = chosenList[0]
  if earnedCoins == 1:
    message = #some specific message
  elif earnedCoins >= 100 and earnedCoins <= 700:
    message = #other message...
  (...)

  await context.send(message)

我试图将28800秒设置为冷却时间,但在使用该命令几分钟后,冷却计时器停止,用户可以再次使用它。我觉得冷却时间太大了。我能做些什么来实现这一点


Tags: 用户命令apimessagebotcontext时间事情
2条回答

下面是我要做的:

import datetime

bot.users_dict = {}
cooldown = 28800  # cooldown in seconds


@bot.command()
async def test(ctx):
    user_id = ctx.author.id
    if user_id in bot.users_dict:
        difference = (datetime.datetime.now() - bot.users_dict[user_id]).total_seconds()
        if difference < cooldown:
            await ctx.send(f"Cooldown! Wait {cooldown - difference} seconds")
            return
    bot.users_dict[user_id] = datetime.datetime.now()
    await ctx.send("Passed cooldown check")

这段代码的工作原理:我们定义了“全局”字典,它将保存用户上次调用命令的时间。如果current time - the last time小于冷却时间,则表示用户正在冷却。如果您有任何问题,请随时在评论中提问

显然,问题出在公布的代码之外。 在同一个bot中,我使用@client.event注释和on_message(message)方法来处理Discord服务器中的问候语消息。不知何故,这个过程使用@bot.command注释重置每个命令的冷却计数器。我刚刚删除了on_message()方法并停止使用客户端事件,现在它工作正常

相关问题 更多 >