Discord.py 冷却时间

时间:2021-02-12 01:48:58

标签: discord.py

我制作了一个不和谐的经济机器人。我想包含一个贷款功能,用户可以在其中申请贷款。会有一个命令冷却时间。但是,如果他们在命令冷却结束后不付款,则机器人应自动收取这笔钱。

@bot.command()
@commands.cooldown(1, 60*60*24*7, commands.BucketType.user)
async def loan(ctx, amount : int):

    loan_available = int(client.get_user_bal(Devada, testbot)['cash'])

    if int(amount) <= loan_available:

      time.sleep(1)

      await ctx.channel.send('You have been given ' + ''.join(str(amount) + ". You will have to pay " + str((int(amount)+int(amount)*0.1)) +" baguttes within 2 weeks."))

      client.change_user_bal(str(ctx.guild.id), str(ctx.author.id), cash=0, bank=amount, reason='loan')
      client.change_user_bal(str(ctx.guild.id), testbot, cash=-amount, bank=0, reason='loan')

      must_pay.update({ctx.author.name:str(amount)})

    else:

        time.sleep(2)

        await ctx.channel.send("You Can only request a loan within "+str(loan_available))

有没有办法检测冷却时间何时结束?

2 个答案:

答案 0 :(得分:0)

检查命令的冷却时间是否已完成的正确方法是检查 Command.is_on_cooldown 是否为假,甚至使用 Command.get_cooldown_retry_after 检查命令的剩余时间。您需要每隔一定时间检查一次,因此您可以创建一个 Task 来调用这些函数中的任何一个,然后评估结果以执行您想要的任何操作。

答案 1 :(得分:0)

@commands.cooldown 属性用于为命令添加冷却时间,因此用户无法发送相同命令的垃圾邮件。相反,他们需要等待一段时间(在本例中为 60*60*24*7 秒)才能重新使用该命令。

但是,如果您希望机器人等待 604800 秒然后取回钱,您应该使用 asyncio 模块等待该时间,而不会干扰或停止其他命令的程序。以下是重新调整代码的方法:

import asyncio

@bot.command()
@commands.cooldown(1, 60*60*24*7, commands.BucketType.user)
async def loan(ctx, amount : int):

    loan_available = int(client.get_user_bal(Devada, testbot)['cash'])

    if int(amount) <= loan_available:

      time.sleep(1)

      await ctx.channel.send('You have been given ' + ''.join(str(amount) + ". You will have to pay " + str((int(amount)+int(amount)*0.1)) +" baguttes within 2 weeks."))

      client.change_user_bal(str(ctx.guild.id), str(ctx.author.id), cash=0, bank=amount, reason='loan')
      client.change_user_bal(str(ctx.guild.id), testbot, cash=-amount, bank=0, reason='loan')

      must_pay.update({ctx.author.name:str(amount)})

    else:

        time.sleep(2)

        await ctx.channel.send("You Can only request a loan within "+str(loan_available))

    # New asyncio code
    
    await asyncio.sleep(60*60*24*7) # Wait for 60*60*24*7 seconds

    # Here, just add the code to take the money away after 60*60*24*7 seconds

请注意,如果您在这期间重启机器人,机器人将不会在之后执行代码 60*60*24*7 秒。因此,您必须让机器人保持在线状态,而不要重新启动它。