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

discord.py 2.0.0版本消息检测失效问题求助

解决discord.py 2.0+自定义Client类下消息检测失效的问题

核心原因

discord.py 2.0版本开始,**消息内容意图(Message Content Intent)**不再默认开启,同时自定义Client类的事件注册需要配合正确的Intents配置才能生效。

解决步骤

1. 在Discord开发者后台开启消息内容权限

登录Discord开发者门户,进入你的Bot应用页面:

  • 切换到「Bot」标签页
  • 在「Privileged Gateway Intents」区域,开启「Message Content Intent」开关

2. 修正代码中的Intents配置

你的自定义Client类初始化时使用的discord.Intents.default()不包含消息内容权限,需要显式开启:

import discord
from discord import app_commands

class aclient(discord.Client):
    def __init__(self):
        # 初始化Intents,开启消息内容权限
        intents = discord.Intents.default()
        intents.message_content = True
        super().__init__(intents=intents)
        self.synced = False

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            await tree.sync(guild=discord.Object(id=748244591387607111))
            self.synced = True
        print('---------------------Bot is ready---------------------')

    # 把消息检测事件作为类方法实现(推荐方式)
    async def on_message(self, message):
        # 避免Bot检测自己的消息
        if message.author == self.user:
            return
        # 这里写你的消息处理逻辑
        if 'hello' in message.content.lower():
            await message.channel.send('Hi there!')

client = aclient()
tree = app_commands.CommandTree(client)

# 你的Slash命令代码保持不变

client.run('MYTOKEN')

可选:使用@client.event装饰器的写法

如果你习惯用装饰器注册事件,确保在实例化client后注册:

# ... 上面的类定义和client实例化代码不变 ...

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    # 处理逻辑
    if 'hello' in message.content.lower():
        await message.channel.send('Hi there!')

client.run('MYTOKEN')

关键注意点

  • 必须同时完成开发者后台的权限开启和代码中的Intents配置,缺一不可
  • 如果Bot需要检测DM消息,确保intents.messages = True(default()已包含该权限,无需额外配置)
  • 自定义Client类中,直接把事件作为类方法实现是更规范的写法,可避免装饰器注册顺序问题

内容的提问来源于stack exchange,提问作者Black'n'White

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:01:20