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))

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

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

然而,如果您想让bot等待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

请注意,如果在这段时间之间重新启动bot, bot将不会执行之后的代码60*60*24*7秒。所以你必须保持bot在线而不重新启动它。

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

最新更新