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

通过on_reaction_add事件获取embed标题失败如何解决

问题原因与解决方案

你遇到的问题本质上是Discord API的缓存机制、权限配置和边界值判断缺失导致的,按以下步骤排查即可解决:

1. 开启必要的Intents权限

Discord 2022年后新增了强制Intent校验,未开启对应权限的机器人无法获取消息、反应相关数据:

  • 进入Discord开发者后台的对应Bot管理页,在「Privileged Gateway Intents」板块开启Presence Intent、Server Members Intent、Message Content Intent三个权限
  • 代码初始化Bot时声明对应权限,示例:
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.reactions = True
intents.message_content = True
# 测试阶段可以直接用 intents = discord.Intents.all() 覆盖所有权限
bot = commands.Bot(command_prefix="!", intents=intents)

2. 替换为不依赖缓存的事件监听

on_reaction_add事件仅对机器人启动后接收到、已存入本地缓存的消息触发,一旦消息是机器人启动前发送的、或缓存被清理,reaction.message的属性会缺失,甚至embeds列表为空,直接取[0].title会抛出异常,也无法正常发送。
推荐使用on_raw_reaction_add事件,该事件基于网关原始数据触发,不依赖本地缓存,可拿到所有消息的完整数据,示例代码:

@bot.event
async def on_raw_reaction_add(payload):
    # 过滤机器人自身的反应避免重复触发
    if payload.user_id == bot.user.id:
        return
    # 拉取完整的频道、消息对象
    channel = await bot.fetch_channel(payload.channel_id)
    message = await channel.fetch_message(payload.message_id)
    
    # 先判断消息是否存在Embed
    if not message.embeds:
        await channel.send("当前消息没有Embed内容")
        return
    
    # 读取Embed标题,空值做兜底处理
    embed_title = message.embeds[0].title or "该Embed未设置标题"
    # 正常发送即可
    await channel.send(f"提取到的Embed标题:{embed_title}")

3. 补充异常捕获

如果部分Embed本身就不存在标题,直接发送空内容会触发Discord的400错误,除了上面的兜底赋值,也可以加异常捕获避免程序崩溃:

try:
    embed_title = message.embeds[0].title
    await channel.send(embed_title if embed_title else "无标题")
except IndexError:
    await channel.send("无可用Embed内容")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:54:04