我正在尝试为我的 discord.py 机器人添加冷却时间,以便用户无法发送垃圾命令,在我的情况下它工作正常。我使用以下装饰器和这个 bot.event
并且我能够让机器人发送一条消息,说冷却时间已经到位。
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"wait for {round(error.retry_after, 2)} seconds before trying again")
我通过在我的命令中使用这个装饰来做到这一点。
@bot.command(name="dice", help="bet a certain amount of money in dice")
@commands.cooldown(1, 1200, commands.BucketType.user)
然而,问题是我有几个不同的冷却命令,我想为这些不同的命令中的每一个发送一条自定义消息,例如对于 dice
命令,机器人可能会说“赌博太多不好,你不觉得吗?”对于 mine
命令,机器人可以说“硬币不会从天而降!”等等等等。
我已经尝试使用一个变量来存储命令的名称并每次在 async def 函数中更改它,但是这不起作用,因为该变量在函数内部被更改,此外,我还尝试查看是否可以使用以下内容循环遍历 bot.commands
:
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
for command in bot.commands():
await ctx.send(f"@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
for command in bot.commands():
await ctx.send(f"There is no one on the street where you are begging, wait for {round(error.retry_after, 2)} seconds (a.k.a cooldown)")")
但这会产生一个错误说
<块引用>bot.commands 不可调用
TL;DR 如何为每个命令制作个性化的冷却信息?
答案 0 :(得分:0)
所以问题是检查调用了什么命令,我们可以使用提供的上下文来做到这一点:
if isinstance(error, commands.CommandOnCooldown):
if ctx.command.name == 'mine':
await ctx.send("Coins dont rain from the sky")
elif ctx.command.name == 'beg':
await ctx.send("there is no one in the street to beg to")
else:
await ctx.send('command is on cooldown')
注意:command.name
是默认的函数名称,您可以通过在 name=bar
装饰器中传递 bot.command
来更改它。