【问题标题】:discord.py bot command cooldown applies to everyone for work commanddiscord.py bot 命令冷却时间适用于每个人的工作命令
【发布时间】:2021-08-07 19:02:33
【问题描述】:

我的 discord.py 机器人有一个工作命令,冷却时间为一小时。所以如果我做>work 然后其他人做>work,它告诉他们必须等待一个小时。当>work 时,我怎样才能让冷却时间只适用于一个用户?谢谢

这是我用于冷却和命令的代码,

class Economy(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.last_work_time = None

    def on_work_waiting():
      time.sleep(3600)
      last_work_time = None

    def on_work_typed():
      if last_work_time is None:
        last_work_time = datetime.datetime.now()
        threading.Thread(target: on_work_waiting).start()
  
    else:
        time_left = datetime.datetime.now() - last_work_time
        minutes_left, _ = divmod(time_left.total_seconds(), 60)

        await ctx.send(f'{ctx.author.mention}, Wait {minutes_left} minutes until you can work again!')


    @commands.cooldown(1, 3600, commands.BucketType.user)

    @commands.command()
    async def work(self, ctx):
      database.load()
      randomjobtitle = ["Construction Worker", "Teacher", "Twitch Streamer", "911 Dispatcher", "Librarian", "Cookie Giver", "Fast Food Worker"]
      job = random.choice(randomjobtitle)
      author = ctx.author
      money = random.randint(10,50)
      balance = database[str(ctx.message.author.id)]
      total = database[str(ctx.message.author.id)] = balance + money
      embed=discord.Embed(title=f"{ctx.author.name} decided to work!", description="You're going to work!", color=0x00FFFF)
      embed.add_field(name="Amount Earned", value=f"**{money}** Ulti Coins", inline=True)
      embed.add_field(name="Job Title (random)", value=f"**{job}**", inline=True)
      embed.add_field(name="Balance Before Work", value=f"**{total}** Ulti Coins", inline=True)
      embed.set_thumbnail(url=author.avatar_url)
      embed.set_footer(text="Your total amount is saved across all servers that I'm in! >balance to see your balance")
      await ctx.send(embed=embed)
      try:
        balance = database[str(ctx.message.author.id)]
      except:
        balance = 0
      database[str(ctx.message.author.id)] = balance + money

【问题讨论】:

  • 您可以使用全局变量或类中的属性来执行此操作。每次有人键入work 时,检查此变量是否已设置(例如,将其初始化为 None 并检查它是否不是 None)。如果是,请告诉该人等待。如果不是,请将变量设置为某个值(可以是datetime.datetime.now()),创建一个新线程并在其中休眠一小时。当它唤醒时,再次将变量设置为无。如果需要,可以将 Thread 中的 sleep 替换为 something else。
  • @Enzo 感谢您的帮助,请问您是否可以使用新代码发布答案?
  • 好的,我会尽快发布的
  • @Enzo 谢谢。

标签: python discord discord.py


【解决方案1】:

你的命令冷却时间,@commands.cooldown(1, 3600, commands.BucketType.user),应该已经以这种方式工作了。您正在使用 user BucketType 其中 applies a cooldown on a per-user basis。根据您的机器人的使用方式,仍然有冷却时间的人可能正在另一台服务器上执行命令。在这种情况下,您可以使用member BucketType。

【讨论】:

  • 我试过了,还是不行。它仍在告诉其他人他们需要等待。
  • 您使用的是哪个版本的discord.py?你可以通过打印discord.__version__来检查你的版本。
猜你喜欢
  • 2019-02-17
  • 2021-04-06
  • 2017-11-21
  • 1970-01-01
  • 2021-03-11
  • 2021-02-16
  • 1970-01-01
  • 2021-05-13
  • 2017-06-13
相关资源
最近更新 更多