迷宫求解Bot重复发送消息问题及嵌套on_message失效求助
迷宫破解Bot的消息重复与逻辑错误问题
我正在开发一个用于破解另一个Bot迷宫的Bot,需通过!wall、!step等指令进行移动,每条指令都会收到对应响应。目前该Bot可正常响应消息,但在转向操作时会同时发送两条消息,原因是仍在使用旧的响应消息,从而产生消息插入间隙。我尝试通过嵌套async def on_message(self, ctx)来更新消息,但并未生效。
当前使用的代码:
async def on_message(self, ctx): message_input = ctx.content message_content = " ".join(line.strip() for line in message_input.splitlines()) time.sleep(1) #MOVEMENT #keep right await ctx.channel.send("!turn right") await ctx.channel.send("!wall") async def on_message(self, ctx): message_input = ctx.content message_content = " ".join(line.strip() for line in message_input.splitlines()) #move if no wall in front if message_content == f"__**Wall**__ You can move forward.": return await ctx.channel.send("!step") #if wall is in front, turn forward again and check for walls if message_content == f"__**Wall**__ There is a wall in front of you.": await ctx.channel.send("!turn left") await ctx.channel.send("!wall") async def on_message(self, ctx): message_input = ctx.content message_content = " ".join(line.strip() for line in message_input.splitlines()) #if wall is still in front of me, turn around and go back if message_content == f"__**Wall**__ There is a wall in front of you.": await ctx.channel.send("!turn right") await ctx.channel.send("!turn right") await ctx.channel.send("!step") #if no wall is in front of me, keep going forward else: await ctx.channel.send("!step")
解决办法
1. 移除嵌套的on_message函数
嵌套定义事件处理函数完全无效,事件系统不会识别内部的on_message。你需要用状态机跟踪Bot的操作阶段,而不是嵌套监听。
2. 实现状态管理
给Bot添加状态变量,记录当前执行的操作阶段,根据状态处理对应响应:
import asyncio class MazeBot: def __init__(self): self.current_state = "idle" # 初始状态:空闲 # 提取响应文本为常量,避免硬编码 self.WALL_CAN_MOVE = "__**Wall**__ You can move forward." self.WALL_BLOCKED = "__**Wall**__ There is a wall in front of you." async def on_message(self, ctx): message_input = ctx.content message_content = " ".join(line.strip() for line in message_input.splitlines()) if self.current_state == "idle": # 初始操作:右转并检查墙体 await asyncio.sleep(1) # 替换同步sleep为异步延迟 await ctx.channel.send("!turn right") await ctx.channel.send("!wall") self.current_state = "waiting_first_wall" elif self.current_state == "waiting_first_wall": if message_content == self.WALL_CAN_MOVE: await ctx.channel.send("!step") self.current_state = "idle" elif message_content == self.WALL_BLOCKED: await ctx.channel.send("!turn left") await ctx.channel.send("!wall") self.current_state = "waiting_second_wall" elif self.current_state == "waiting_second_wall": if message_content == self.WALL_BLOCKED: await ctx.channel.send("!turn right") await ctx.channel.send("!turn right") await ctx.channel.send("!step") else: await ctx.channel.send("!step") self.current_state = "idle"
3. 替换同步阻塞的time.sleep
time.sleep(1)会阻塞整个事件循环,导致Bot无法及时处理其他消息。改用asyncio.sleep(1)实现异步延迟,不影响Bot的其他操作。
4. 优化响应文本判断
把迷宫Bot的响应文本提取为类属性常量,避免重复硬编码,后续修改响应格式时只需更新常量即可。
内容的提问来源于stack exchange,提问作者Sampler
相关产品推荐
相关产品推荐

