You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:03:30