如何在discord.py中重新接收聊天输入?猜词机器人故障排查
问题分析与解决方法
你遇到的问题根源非常明显——你在获取用户新输入后,又把它覆盖成了初始的.play消息内容,导致机器人永远在和.play做比较,自然永远判断错误。
具体错误点
看这段代码:
user_input = await client.wait_for('message', timeout=60.0, check=None) user_input = message.content # 这里是罪魁祸首!
client.wait_for('message')已经返回了用户新发送的消息对象,但你紧接着把user_input赋值为message.content,而这个message是触发.play指令的那条原始消息,所以user_input永远是.play,根本没用到用户后来输入的内容。
修复方案 + 优化建议
我帮你修正了代码,同时补充了几个必要的细节:
import random # 把导入移到函数外,避免重复导入 import asyncio @client.event async def on_message(message): print(message.author.bot) content = message.content author = message.author print("{}: {}".format(author, content)) # 先判断是不是机器人消息,避免自己触发自己 if message.author.bot: return if message.content.startswith(".play"): words = [ "expert", "error", "fairies", "star", "example", "pencil", "friction", "attraction", "horse", "vegetable", "stove", "invention"] word = random.choice(words) guesses = 7 hint = "" i = 0 try: await message.channel.send("Guess the word!") while guesses > 0: # 1. 添加check,确保只有发起游戏的用户在当前频道的输入才会被接收 guess_msg = await client.wait_for( 'message', timeout=60.0, check=lambda m: m.author == message.author and m.channel == message.channel ) # 2. 用新消息的content作为用户输入 user_input = guess_msg.content.lower() # 转小写,让游戏不区分大小写 print(user_input) if user_input == word.lower(): # 同样转小写 await message.channel.send("You found the word!") break # 猜对后直接跳出循环,结束游戏 else: await message.channel.send("Guessed wrong!") # 处理hint逻辑,避免索引越界 if i < len(word): hint += word[i] i += 1 await message.channel.send(f"Here is hint: {hint}") guesses -= 1 await message.channel.send(f"{guesses} guesses left") if guesses == 0: await message.channel.send(f"Game over! The word was: {word}") except asyncio.TimeoutError: await message.channel.send("Time out! Game ended.")
关键修改说明
- 修复输入获取逻辑:用
guess_msg = await client.wait_for(...)接收用户新消息,再通过user_input = guess_msg.content获取真实输入,不再覆盖为初始指令。 - 添加输入校验(check):确保只有发起游戏的用户在当前频道发送的消息才会被处理,避免其他用户干扰游戏。
- 不区分大小写:把用户输入和目标单词都转成小写,提升游戏体验。
- 优化hint逻辑:增加
i < len(word)的判断,避免索引越界报错。 - 猜对后终止循环:添加
break,用户猜对后直接结束游戏,不用继续等待输入。 - 移除非必要的重复导入:把
import random移到函数外部,避免每次触发.play都重复导入模块。
内容的提问来源于stack exchange,提问作者user13692097
相关产品推荐
相关产品推荐

