discord.py机器人无响应:命令与事件无法触发问题排查求助
问题排查与解决
你的代码存在两个关键问题,导致机器人既不响应消息也不执行命令:
1. 自定义on_message事件阻塞了命令处理
当你自定义on_message事件时,discord.py默认的命令处理逻辑会被覆盖,必须手动调用await bot.process_commands(message),才能让!ping这类命令正常工作。
2. 消息匹配逻辑错误
原代码中if message.content == 'Hello'.lower()的写法是将固定字符串转小写后和用户原始消息比较,正确逻辑应该是把用户输入的消息转小写,再和目标字符串比对,否则只有用户输入完全小写的hello才会触发回复。
修正后的完整代码:
import discord from discord.ext import commands from discord import Embed bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) # 机器人上线提示 @bot.event async def on_ready(): print("PythonBot is online") # 回复Hello消息 @bot.event async def on_message(message): # 跳过机器人自身发送的消息,避免循环触发 if message.author.bot: return # 正确的消息匹配逻辑:将用户消息转小写后比对 if message.content.lower() == 'hello': await message.channel.send("Hey!") # 必须添加这一行,让命令处理逻辑正常运行 await bot.process_commands(message) # Ping命令 @bot.command() async def ping(ctx): await ctx.send("Pong!") bot.run("TOKEN_HERE")
额外说明:
- 添加
if message.author.bot: return可防止机器人响应自身发送的消息,避免无限循环。 - 确保Discord开发者后台已开启消息内容意图(Message Content Intent),即便代码中使用
Intents.all(),后台未开启该权限仍无法读取消息内容。
内容的提问来源于stack exchange,提问作者Cerulean
相关产品推荐
相关产品推荐

