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

Discord机器人on_message()致@bot.command失效问题求助

解决Discord机器人on_message事件导致@bot.command命令失效的问题

嘿,我来帮你搞定这个问题!你遇到的情况其实是几个Discord.py的常见使用误区导致的,咱们一步步拆解修复:

问题根源分析

  1. 事件错误使用命令装饰器:你给on_message事件加了@commands.has_role("Owner")装饰器,但这个装饰器是专门给@bot.command修饰的命令函数设计的,对on_message这类事件完全无效,不仅权限检查没生效,还可能干扰事件的正常运行。
  2. process_commands调用范围太窄:你只在消息以/lockdown开头时才调用await bot.process_commands(message),这意味着其他命令的消息根本不会触发命令处理逻辑,自然就失效了。

修复方案

方案1:修正on_message事件的写法

把权限检查逻辑移到事件内部,同时确保process_commands对所有消息都执行:

@bot.event
async def on_message(message):
    # 第一步:优先处理所有命令,保证@bot.command的命令能正常被识别
    await bot.process_commands(message)
    
    # 手动检查用户是否拥有"Owner"角色
    has_owner_role = any(role.name == "Owner" for role in message.author.roles)
    if not has_owner_role:
        return  # 没有权限就直接返回,不执行后续逻辑
    
    # 处理你的lockdown触发逻辑
    if message.content.startswith('/lockdown'):
        embed = discord.Embed(title=":warning: Do you want to activate Lock Down?", description="Type 'confirm' to activate Lock Down mode", color=0xFFFF00)
        await message.channel.send(embed=embed)

方案2:更规范的做法——把lockdown做成独立命令

其实Discord.py的设计更推荐用命令来实现这类交互,而不是在on_message里硬写逻辑,这样既不会干扰其他命令,也能正常使用权限装饰器:

@bot.command()
@commands.has_role("Owner")
async def lockdown(ctx):
    embed = discord.Embed(title=":warning: Do you want to activate Lock Down?", description="Type 'confirm' to activate Lock Down mode", color=0xFFFF00)
    await ctx.send(embed=embed)

这样你就不需要修改on_message事件,所有命令都能正常运行,权限控制也能通过@commands.has_role正常生效。

额外提醒

如果你的on_message事件还有其他逻辑,一定要把await bot.process_commands(message)放在事件的最开始位置(除非有特殊的拦截需求),这样才能保证所有消息都能被检查是否是命令。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:51:13