Discord Bot运行play命令时为何仅循环4次而非预期100次?
循环次数异常排查与修复
核心问题成因
- 你当前的循环逻辑写为
for x in 'play':,Python对字符串做遍历时会逐个取内部字符作为循环变量,字符串'play'仅包含p、l、a、y共4个字符,因此固定执行4次循环,完全不符合100次循环的预期。 - 代码里提前赋值的
x = '100'没有进入任何循环判断逻辑,属于完全无效的冗余代码,对循环次数没有任何影响。
其他可触发功能异常的隐患
- 使用
time.sleep()会阻塞Discord Bot的异步事件循环,在模拟按键等待的几秒内,Bot会完全失去响应,无法处理其他频道的指令。 keyboard.press('shift + w')不符合keyboard库的API规则,无法实现同时按住Shift和W的疾跑效果,该分支的操作逻辑会完全失效。client.wait_for('message')没有设置消息过滤规则,频道内任意用户发的任意内容都会被识别为游戏操作指令,甚至Bot自身发送的引导消息也可能被误触发。- 存在重复导入问题:keyboard、mouse相关模块被重复导入多次,部分导入的Controller类因为重名被后续导入覆盖,容易出现无明确报错的隐藏故障。
修复参考代码
import discord from discord.ext import commands import asyncio from pynput.mouse import Controller as MouseController, Button from pynput.keyboard import Controller as KeyboardController, Key # 替换为自己的Bot Token TOKEN = 'mytoken...' keyboard_ctrl = KeyboardController() mouse_ctrl = MouseController() client = commands.Bot(command_prefix = '.') @client.command(name='play') async def play(ctx): await ctx.channel.send("Hello! welcome to a game where you play my game through discord messages! How yo play: if you want to go write - 'go', left - 'left', right - 'right', back - 'back', sprint 'lgo', click - 'click', jump - 'jump'") # 按要求循环100次 for _ in range(100): # 消息过滤:仅接收命令发起用户在当前频道发送的非Bot消息 def check(message): return message.author == ctx.author and message.channel == ctx.channel and not message.author.bot # 等待用户指令,10秒无操作自动退出避免无限阻塞 try: msg = await client.wait_for('message', check=check, timeout=10) except asyncio.TimeoutError: await ctx.send("等待操作超时,退出游戏控制") break response = msg.content.lower() print(response) if response == "go": keyboard_ctrl.press('w') await asyncio.sleep(2) keyboard_ctrl.release('w') elif response == "left": keyboard_ctrl.press('a') await asyncio.sleep(2) keyboard_ctrl.release('a') elif response == "right": keyboard_ctrl.press('d') await asyncio.sleep(2) keyboard_ctrl.release('d') elif response == "back": keyboard_ctrl.press('s') await asyncio.sleep(2) keyboard_ctrl.release('s') elif response == "jump": keyboard_ctrl.press('b') keyboard_ctrl.release('b') elif response == "click": mouse_ctrl.click(Button.left) elif response == "lgo": keyboard_ctrl.press(Key.shift) keyboard_ctrl.press('w') await asyncio.sleep(5) keyboard_ctrl.release('w') keyboard_ctrl.release(Key.shift) client.run(TOKEN)
内容的提问来源于stack exchange,提问作者Lagis
相关产品推荐
相关产品推荐

