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

discord.py框架下指令冷却触发时提示消息不生效问题求助

问题修复方案

核心故障原因

你写的装饰器顺序错误,discord.py框架要求@client.command()命令注册装饰器必须放在最上层,冷却规则装饰器要放在命令装饰器下方,否则冷却触发的CommandOnCooldown错误无法被绑定到该命令的错误处理器捕获,自然就不会输出预设提示。

修正后代码

getconbalanceAliases = "gc, getconbal"
getconbalanceDesc = "赚取Con余额!该命令有30秒冷却时间。"
@client.command(aliases=["gc","getconbal"])
@commands.cooldown(1, 30, commands.BucketType.user)
async def getconbalance(ctx):
    await open_account(ctx.author)
    user = ctx.author

    users = await get_bank_data()

    earnings = random.randrange(101)

    await ctx.send(f'{ctx.author.mention} 获得了 {earnings} 枚硬币!!')

    users[str(user.id)]["conbalance"] += earnings

    with open("conbalance.json",'w') as f:
        json.dump(users,f)


@getconbalance.error
async def getconbalance_error(ctx, error):
  if isinstance(error, commands.CommandOnCooldown):
    embed = discord.Embed(title = f"慢一点兄弟",
    description = f"你频繁刷指令乞讨的样子像个小屁孩。", 
    color = 0xf461ff)
    now = datetime.now()
    current_time = now.strftime("%H:%M")

    embed.set_footer(text=f"由 {ctx.author} 于 {current_time} 请求")
    await ctx.reply(embed=embed,mention_author=False)

额外排查点

  • 确认代码顶部已导入datetime模块:错误处理器中用到了datetime.now(),如果没有写from datetime import datetime会触发静默报错,导致提示无法发出
  • 确认没有全局错误处理器拦截:如果项目中存在全局的on_command_error事件监听,需要在全局处理器中添加逻辑,当错误未被处理时才继续传递,否则单命令的错误处理器不会被触发

内容的提问来源于stack exchange,提问作者MenIndo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:36:03