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

时间:2021-06-23 20:13:42

标签: python discord discord.py

我正在使用 Discord Python API,并且正在尝试执行机器人命令。但是,我希望每个用户只能在 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 秒设置为冷却时间,但在使用该命令几分钟后,冷却时间计时器停止,用户可以再次使用它。我认为冷却时间太大了。有什么解决方法可以做到这一点吗?

2 个答案:

答案 0 :(得分:0)

这是我会做的:

select t.*
from (select t.*, lead(date) over (order by date) as lead_date
      from t
     ) t
where t <= lead_date + interval '3 hour'
order by t.date
limit 1;

这段代码的工作原理:我们定义了“全局”字典,它将保存用户最后一次调用命令的时间。如果 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") 小于冷却时间,则表示用户处于冷却状态。如果您有任何问题,请随时在评论中提问。

答案 1 :(得分:0)

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