添加阻止用户使用命令的冷却时间

2024-06-16 10:23:04 发布

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

我正试图为我的机器人添加一种健康系统的冷却。因此,一旦成员的健康状况达到零,他们只有在达到0后一小时才能运行命令。我在研究可能的解决方案时看到过@commands.cooldown(1, 30, commands.BucketType.user),但我认为它在这里不会真正起作用,因为实际的命令本身没有冷却时间。这是我第一次尝试添加冷却时间(在清理之前尝试让它工作,对此非常抱歉)

def start_cooldown(ctx): # is called after the bot detects the user hits 0 hp or less
  stopTime=str(datetime.now().time()) # gets current time
  hours=stopTime[0:2]; minutes=stopTime[3:5] # separates hours from mins
  if hours[0] == '0': # removes the first zero (honestly not sure if I need this)
    hours[0]=''
  if hours=='00': # converts 00 to 24 (midnight to 24 hours)
    hours='24'
  global on_cooldown
  on_cooldown.update({ctx.author.id:f'{hours} {minutes}'}) # dictionary that contains members' ids and their cooldowns (if they have one)
  print(f'on_cooldown={on_cooldown}')

def check_cooldown(ctx): # called at the start of the command
  currentTime=str(datetime.now().time())
  hours=currentTime[0:2]; minutes=currentTime[3:5]
  print(hours,minutes)
  if hours[0] == '0':
    hours[0]=''
  if hours=='00':
    hours='24' # all the same as above
  print(hours,minutes)
  #cooldown ends at '24 50' 12:50am
  #current time is  '23 50' 11:50pm
  while True: # tries to get the member's cooldown, if a KeyError is raised (the member has no active cooldown), then the function ends and returns nothing (the command continues to run)
    try:
      cooldownEnd=on_cooldown[ctx.author.id] 
      break
    except KeyError:
      return

    print(f'[Line 71]\nhours={hours}\ncooldownEnd={cooldownEnd[0:2]}\nminutes={minutes}\ncooldownEnd[3:]={cooldownEnd[3:]}')

    if int(hours) > int(cooldownEnd[0:2]) and int(minutes) >= int(cooldownEnd[3:]):
      on_cooldown.pop(ctx.author.id) # checks if the current time is past the time the cooldown was started

    if on_cooldown[ctx.author.id] in on_cooldown:
      timeRemaining=int(cooldownEnd[3:]) - int(minutes)
      return(f'Sorry! You\'re still resting, try again in {timeRemaining} minutes.')

Tags: thetoidiftimeisonauthor