You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为discord.py命令设置冷却?需实现30秒用户级冷却

Discord.py 命令30秒冷却时间的正确实现

你的代码存在几个关键问题,导致冷却功能无法正常工作,以下是修正后的完整实现:

问题分析

  • 命令未定义为async def函数:discord.py的命令必须是异步函数形式,你直接写了if语句,缺少函数结构
  • 错误处理装饰器与命令不匹配:@work.error对应名为work的命令,但你的目标命令是狩猎相关,应该使用对应命令的.error装饰器
  • 冗余的触发判断:使用@client.command()后,无需再用message.content.startswith,框架会自动识别命令触发词

正确代码示例

@client.command(name="hunt")  # 命令名,用户输入!hunt触发
@commands.cooldown(1, 30, commands.BucketType.user)  # 1次/30秒,按用户维度冷却
async def hunt(ctx):
    await ctx.send('You hunted a...')

# 对应hunt命令的错误处理
@hunt.error
async def hunt_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send(f'This command is on cooldown, you can use it in {round(error.retry_after, 2)} seconds')

关键说明

  • BucketType.user表示每个用户独立计算冷却时间,符合你的需求
  • 冷却装饰器必须放在@client.command()的下方,顺序不能颠倒
  • 命令函数的参数必须包含ctx(上下文对象),用于发送消息等操作
  • 错误处理函数需要接收ctx和error两个参数,通过判断错误类型来处理冷却提示

内容的提问来源于stack exchange,提问作者Weidong Zhu Robot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 22:05:22