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

如何在Discord机器人第二个on_message事件执行后回到第一个事件?

问题分析与解决方案

你的核心问题是在第一个on_message事件内部注册了第二个on_message事件,这会导致:当第一次触发Hey Sloime后,第二个on_message会被永久注册到机器人的事件系统中。此后所有消息都会优先/仅由这个新的事件处理函数响应,再也不会回到原来的逻辑里。

正确实现思路

如果你的需求是触发Hey Sloime后,临时等待用户的后续指令(比如Can I have my Dis ID?),应该用wait_for方法实现临时对话流程,而不是注册多个事件。

修改后的代码

import os
import asyncio
import discord

# 必须开启message_content意图才能读取消息内容
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

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

    # 处理初始触发消息
    if message.content == 'Hey Sloime':
        # 根据用户ID发送不同回复
        if message.author.id == xxx:  # 替换为实际用户ID
            await message.channel.send('Yes master?')
        elif message.author.id == xxx:  # 替换为实际用户ID
            await message.channel.send('Tell me brother')
        else:
            await message.channel.send('TF u want?')
        
        # 定义检查规则:只接收当前用户在当前频道的消息
        def check(m):
            return m.author == message.author and m.channel == message.channel
        
        try:
            # 等待用户回复,超时时间10秒
            follow_msg = await client.wait_for('message', check=check, timeout=10.0)
        except asyncio.TimeoutError:
            await message.channel.send('You took too long to reply.')
            return
        
        # 处理后续回复
        if follow_msg.content == 'Can I have my Dis ID?':
            await message.channel.send(follow_msg.author.id)
        else:
            await message.channel.send('Do I look like I can answer that?')

client.run(os.environ['TOKEN'])

关键说明

  1. 避免嵌套注册事件:Discord.py的事件是全局注册的,一旦注册就会一直生效,不能用这种方式实现临时对话。
  2. 使用wait_for实现临时监听:这个方法会临时挂起,等待符合条件的消息触发,处理完成后自动回到原事件逻辑,不会影响后续的消息处理。
  3. 开启消息内容意图:Discord.py v2.0+必须显式开启message_content意图,否则机器人无法读取用户发送的消息内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:50:31