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

Discord.py 触发指令时为已有Embed添加add_field字段的实现方法

解决方案

错误原因

你无法获取到有效discord.Message对象的核心问题是:不能直接通过discord.Message(消息ID)的方式手动构造消息对象,该构造方法是discord.py框架内部调用的,外部手动传入ID只会生成一个无实际数据的空对象,没有关联Discord服务器上的真实消息。

实现步骤

1. 确认前置要求

  • 已在Discord开发者后台的机器人设置页开启Message Content Intent权限
  • 机器人在Embed所在频道拥有「读取消息历史」、「管理消息」权限
  • 单个Embed的field总数不超过25条(Discord官方限制)

2. 方案一:固定编辑指定Embed消息

先运行一次mangaEmbed命令,获取生成的Embed消息ID、所在频道的ID,填入代码即可:

# 替换为你自己的实际ID
TARGET_EMBED_CHANNEL_ID = 123456789 # Embed消息所在的频道ID
TARGET_EMBED_MESSAGE_ID = 987654321 # 初始生成的Embed消息ID

@bot.command()
async def editembed(ctx, vols, *, title):
    # 先获取频道对象
    channel = bot.get_channel(TARGET_EMBED_CHANNEL_ID)
    if not channel:
        await ctx.send("目标频道不存在")
        return
    # 拉取真实的消息对象
    try:
        message = await channel.fetch_message(TARGET_EMBED_MESSAGE_ID)
    except discord.NotFound:
        await ctx.send("目标Embed消息已被删除")
        return
    except discord.Forbidden:
        await ctx.send("无权限读取目标消息")
        return
    # 校验Embed存在
    if not message.embeds:
        await ctx.send("目标消息没有Embed内容")
        return
    # 新增字段并更新
    embed = message.embeds[0]
    embed.add_field(name=title, value=vols, inline=False)
    try:
        await message.edit(embed=embed)
        await ctx.send("Embed更新成功")
    except discord.Forbidden:
        await ctx.send("无权限编辑目标消息")

3. 方案二:自动存储初始Embed消息ID(无需手动填ID)

修改mangaEmbed命令,发完初始Embed后自动存储消息ID,重启机器人后也可持久化存储到本地文件/数据库:

# 全局变量存储ID,重启后会失效,持久化可写入json文件或数据库
target_embed_msg_id = None
TARGET_EMBED_CHANNEL_ID = 123456789 # 你要发送Embed的频道ID

@bot.command()
async def mangaEmbed(ctx):
    global target_embed_msg_id
    embed = discord.Embed(
        title = "Completed Self Prints",
        color = discord.Color.blue()
    )
    embed.add_field(name="Kokou no Hito by NggKGG", value="Volumes 1-17", inline=False)
    embed.add_field(name="DrangonBall Z\nby NggKGG", value="Kokoue no 222o", inline=False)
    embed.add_field(name="Homoculus", value="Volumes 1-24\nManmangaboy", inline=False)
    # 发送Embed并存储消息ID
    msg = await ctx.send(embed=embed)
    target_embed_msg_id = msg.id
    await ctx.send(f"初始Embed创建完成,消息ID:{target_embed_msg_id}")

后续editembed命令直接调用存储的target_embed_msg_id变量即可,无需手动填ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:45:05