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

Discord.py V2命令无法识别,被误判为消息事件

问题排查与修复方案

核心问题1:消息内容意图未开启

Discord.py v2.x 开始,必须显式开启 message_content 意图才能读取消息内容,否则机器人无法识别命令前缀。你的代码里用了 discord.Intents.default(),但这个默认配置不包含 message_content,导致命令前缀检测失效,命令被当作普通消息处理。

修复代码:

intents = discord.Intents.default()
intents.message_content = True  # 新增该行开启消息内容读取权限

bot = commands.Bot(command_prefix='>', intents=intents)

核心问题2:Menu 类与命令调用存在语法错误

  • Menu 类的 __init__ 方法定义了多余的 args 参数,且未设置默认值,无参实例化会触发参数错误
  • helloworld 命令里 view=view() 是错误写法,应该直接传入 view 对象,不需要加括号调用

修复 Menu 类和命令:

class Menu(discord.ui.View):
    # 移除多余的args参数,给guild_id设置默认值避免无参报错
    def __init__(self, *kwargs):
        self.guild_id = kwargs.pop('guild_id', None)
        super().__init__(timeout=None)
        self.value = None

    @discord.ui.button(label="Yes", custom_id="yes", style=discord.ButtonStyle.green)
    async def button_yes(self, button: discord.ui.Button, interaction: discord.Interaction):
        print(True)


@bot.command()
async def helloworld(ctx):
    view = Menu()  # 现在无参实例化不会报错
    await ctx.channel.send('test', view=view)  # 直接传入view对象,而非调用view()

额外优化:过滤机器人自身消息

在 on_message 事件开头添加判断,避免机器人处理自己发送的消息,防止潜在循环问题:

@bot.event
async def on_message(message):
    if message.author.bot:
        return  # 跳过机器人发送的消息
    print(message)
    # do stuff here
    await bot.process_commands(message)

修复以上问题后,>helloworld 命令即可正常触发,不会仅触发 on_message 事件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:57:16