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

Discord.py中on_message事件导致机器人命令失效问题求助

解决Modmail机器人添加on_message后命令失效的问题

看起来你的问题出在几个容易忽略的细节上,我帮你逐一排查并给出修复方案:

1. 确认使用commands.Bot而非纯discord.Client

如果你的机器人是用discord.Client()初始化的,那么client.process_commands()方法根本不存在——这个方法是commands.Bot类独有的,命令装饰器@client.command()也只对Bot实例生效。

检查你的初始化代码,确保是这样的:

import discord
from discord.ext import commands

# 启用必要的intents(关键步骤!)
intents = discord.Intents.default()
intents.message_content = True  # Discord.py v2.x版本必须开启才能读取消息内容
intents.members = True  # 如果需要处理成员相关逻辑可添加

client = commands.Bot(command_prefix="你的命令前缀", intents=intents)

2. 修复on_message中的异常隐患

你的代码中如果log_channel获取失败(比如ID错误、机器人无频道访问权限),发送消息会抛出异常,导致await client.process_commands(message)无法执行。必须添加异常捕获和空值判断:

@client.event
async def on_message(message):
    # 处理DM日志逻辑
    if message.author != client.user and isinstance(message.channel, discord.DMChannel):
        log_channel = client.get_channel(你的真实日志频道ID)
        if log_channel:  # 先确认频道存在
            try:
                await log_channel.send(
                    f"ID: {message.author.id} - **{message.author.name}#{message.author.discriminator}:** ```{message.content}```"
                )
            except Exception as e:
                print(f"发送DM日志失败: {str(e)}")
    # 确保命令处理始终执行,哪怕日志发送出错
    await client.process_commands(message)

3. 开启Message Content Intent(Discord.py v2.x必做)

从Discord.py 2.0版本开始,默认不会授予机器人读取消息内容的权限,你需要:

  • 登录Discord开发者门户,找到你的机器人应用
  • 进入Privileged Gateway Intents页面,开启Message Content Intent
  • 在代码中像上面示例那样,显式启用intents.message_content = True

4. 检查命令装饰器的正确性

确保你的命令是用@client.command()正确装饰的,比如:

@client.command()
async def ping(ctx):
    await ctx.send("Pong!")

按照上面的步骤调整后,你的命令应该能正常触发,同时DM日志功能也能正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:08:40