Discord机器人无法响应Yes/No输入:问题原因及修复方案
问题原因
- 你的代码逻辑存在错误:当用户发送
ask me a question时,on_message事件触发,此时message.content的值是ask me a question,后续判断message.content == 'yes'或'no'时,对比的还是这条指令消息的内容,永远不可能匹配,所以不会触发回复。 - 另外,
on_message事件是每条新消息触发一次,用户发送yes/no是一条新消息,原代码没有针对这条新消息做任何对应处理。
修复方案
使用Discord.py提供的wait_for方法,专门等待用户的后续回复,修复后的代码如下:
import asyncio from discord.ext import commands # 假设你已完成bot初始化,示例: # bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) @bot.event async def on_message(message): # 跳过机器人自身消息,避免循环触发 if message.author == bot.user: return if message.content == 'ask me a question': await message.channel.send('Yes or No') # 等待指令发起者在同一频道的回复,超时30秒 try: response = await bot.wait_for( 'message', check=lambda m: m.author == message.author and m.channel == message.channel, timeout=30.0 ) except asyncio.TimeoutError: await message.channel.send('你超时了!') return # 忽略大小写判断回复内容 if response.content.lower() == 'yes': await message.channel.send('correct!') elif response.content.lower() == 'no': await message.channel.send('wrong') # 保留此行以确保其他前缀命令正常执行 await bot.process_commands(message)
关键说明
- 增加
message.author == bot.user判断,防止机器人自身消息触发事件,避免无限循环。 wait_for方法会暂停当前协程,直到监听的message事件满足check条件,确保只有发起指令的用户在同一频道的回复才会被处理。- 加入超时处理,避免机器人一直等待用户回复。
- 使用
lower()统一转换为小写,让回复不区分大小写(比如用户发Yes或YES也能匹配)。 - 最后调用
await bot.process_commands(message),保证机器人的其他前缀命令(如果有的话)能正常工作。
内容的提问来源于stack exchange,提问作者chester
相关产品推荐
相关产品推荐

