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

discord.py使用wait_for()时机器人误将自身消息作为响应输入的问题

问题根因

该问题由两个原因共同导致:

  1. 事件分发时序差:await channel.send()执行完成仅代表消息已经成功提交到Discord服务器,此时机器人自身发送的消息对应的网关事件还没有推送到本地程序,代码就已经执行到wait_for监听逻辑,后续网关推送的机器人自身发送的引导消息会被wait_for捕获。
  2. 检查函数未做过滤:on_message开头的机器人自身消息过滤规则仅作用于on_message回调本身,wait_for是独立的事件监听器,不会复用该过滤逻辑。你当前的check_instant_return仅判断消息是否有内容,只要收到非空消息就会判定为合法响应,因此机器人自身的消息会被直接识别为用户输入。
修复方案
  • 核心修改:调整检查函数,增加过滤规则,根据业务需求选择对应过滤逻辑:
    如果你需要仅响应触发指令的用户的消息(绝大多数场景的需求),检查函数增加作者和频道匹配:
    def check(m):
        # 仅匹配触发指令的同一用户、同一频道的消息,完全规避跨频道、其他用户的干扰
        return m.author == message.author and m.channel == message.channel
    
    如果你需要允许频道内所有非机器人用户响应,至少过滤掉机器人自身的消息:
    def check(m):
        return m.author != client.user and m.channel == message.channel
    
  • 优化建议:调用wait_for时增加超时配置,避免程序永久阻塞,完整修复代码如下:
import asyncio

@client.event
async def on_message(message):
    if message.author == client.user:
        return  

    if message.content.startswith('!example'):
        await message.channel.send("This is an example. Say 'y'")
        
        # 检查函数定义在on_message内部,可直接访问外层的message变量
        def check(m):
            return m.author == message.author and m.channel == message.channel
        
        try:
            # 超时时间可根据业务需求调整,单位为秒
            msg = await client.wait_for('message', check=check, timeout=30)
        except asyncio.TimeoutError:
            await message.channel.send("等待响应超时,指令已取消")
            return

        if msg.content.strip().lower() == "y":
            await message.channel.send("Alright")

内容的提问来源于stack exchange,提问作者someone

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:24:08