Discord.py on_message事件函数未运行问题求助
问题排查:Discord机器人on_message事件无响应(Minecraft服务器控制场景)
核心问题分析与修复步骤
1. 阻塞式IO卡住asyncio事件循环
你的start_console函数中使用了同步阻塞的self.process.stdout.readline(),这会直接占用asyncio事件循环,导致其他异步任务(包括on_message事件)无法被调度执行。
修复方案:改用异步方式读取子进程输出,推荐使用asyncio.create_subprocess_exec替代同步的subprocess.Popen,全程异步操作:
async def start(self): if self.process: self.process.kill() await self.process.wait() self.process = None self.process = await asyncio.create_subprocess_exec( "java", "-jar", self.jar_file, "nogui", cwd=self.directory, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, stdin=asyncio.subprocess.PIPE, ) async def start_console(self, channel): while True: output = await self.process.stdout.readline() if not output: break output = output.decode().strip() await channel.send(output)
2. 变量名不一致导致异常
按钮回调中创建的任务被赋值给server.console,但on_message里调用的是server.console_task.cancel(),变量名不匹配会抛出AttributeError,未捕获的异常会导致事件循环异常,进而影响on_message执行。
修复方案:统一变量名,按钮回调中改为:
server.console_task = asyncio.create_task(server.start_console(channel))
3. 未正确启用消息意图(Intents)
若使用discord.py v2.x及以上版本,必须显式启用消息意图才能接收on_message事件。
修复方案:初始化机器人时开启消息意图:
intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix="!", intents=intents)
4. on_message逻辑优化
active_servers遍历效率低可能拖慢响应速度,建议用字典映射服务器名称到实例:
# 初始化时构建映射字典 active_servers_map = {server.name.lower(): server for server in active_servers} # on_message中直接查找 server = active_servers_map.get(server_name) if server: # 后续命令处理逻辑
内容的提问来源于stack exchange,提问作者JCBWLL
相关产品推荐
相关产品推荐

