Discord机器人on_ready与on_message事件未触发,消息响应功能故障求助
嘿,我来帮你解决Discord.py rewrite版本里on_ready和on_message事件不触发的问题!这种情况我碰过好多次,大概率是几个常见的配置或代码结构问题,咱们一步步排查:
1. 先检查Message Content Intent权限(这是当前最常见的坑)
Discord在2022年之后更新了政策,机器人必须启用Message Content Intent才能读取普通用户发送的消息,否则on_message事件根本不会被触发。
解决步骤:
- 打开Discord开发者门户,找到你的应用,进入「Bot」页面,在「Privileged Gateway Intents」板块里开启「Message Content Intent」
- 在代码里初始化Bot/Client时,必须显式启用这个Intent:
import discord from discord.ext import commands # 初始化Intent intents = discord.Intents.default() intents.message_content = True # 关键:开启消息内容权限 class DiscordChat: def __init__(self): # 用带Intent的配置初始化Bot self.bot = commands.Bot(command_prefix="!", intents=intents) # 注册类内的事件方法 self.bot.event(self.on_ready) self.bot.event(self.on_message) async def on_ready(self): print(f"已登录为:{self.bot.user}") async def on_message(self, message): # 跳过机器人自己发的消息,避免循环回复 if message.author == self.bot.user: return await message.channel.send("hello") def start(self, token): self.bot.run(token) # 使用示例 chat_bot = DiscordChat() chat_bot.start("你的机器人Token")
2. 检查事件注册的方式是否正确
如果你的类是自定义结构(不是用Cog),不能直接在类方法上用@self.bot.event装饰器——因为类定义时self还不存在,装饰器无法正确绑定。正确的做法是在__init__方法里用self.bot.event()来注册事件方法,就像上面的示例那样。
如果是用Cog(Discord.py推荐的模块化方式),要改用@commands.Cog.listener()装饰器,然后把Cog加载到Bot中:
class DiscordChat(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): print("机器人已就绪!") @commands.Cog.listener() async def on_message(self, message): if message.author.bot: return await message.channel.send("hello") # 初始化Bot并加载Cog intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix="!", intents=intents) bot.add_cog(DiscordChat(bot)) bot.run("你的机器人Token")
3. 确认机器人已正确启动并拥有权限
- 检查
run()/start()方法是否被正确调用,有没有传入正确的机器人Token - 查看控制台输出,如果Token错误、网络连接失败会直接抛出异常
- 确认机器人已经邀请到目标服务器,并且拥有「读取消息」「发送消息」的权限(可以给机器人分配
@everyone的基础消息权限,或者创建专门的角色)
4. 避免全局事件覆盖
如果你的代码里还有其他全局的on_message事件(比如不在类中的独立事件),可能会导致类内的事件不触发。因为Discord.py的事件是按注册顺序执行的,如果全局事件中没有调用await bot.process_commands()或者没有让事件继续传播,就会阻断后续事件的执行。
先从Message Content Intent开始排查,这是现在90%以上这类问题的根源,然后再检查代码结构和权限问题,应该就能解决啦!
内容的提问来源于stack exchange,提问作者Helbo
相关产品推荐
相关产品推荐

