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

discord.py编辑Embed消息报错:File类型无法JSON序列化

问题解决:Discord.py编辑带图片Embed时的JSON序列化错误

错误原因

调用day_msg.edit(file=file, embed=embed)时触发TypeError: Object of type File is not JSON serializable,核心原因是:
Discord的消息编辑API(PATCH请求)不支持通过上传新附件的方式更新消息,discord.File对象仅能用于创建消息(POST请求),将其传入edit()方法会导致库尝试把File对象序列化为JSON,进而触发类型错误。

你怀疑的函数外day_msg变量问题不成立——首次发送后它已经被正确赋值为Message对象,错误和这个变量无关。

解决方案

根据需求分两种情况处理:

情况1:仅更新Embed内容,图片保持不变

直接复用原消息的附件URL,编辑时无需传递file参数:

# 函数外定义全局变量
day_msg = None
issent_day = 0

async def day_vipe():
    global day_msg, issent_day
    chat = client.get_channel(1007301750895677491)
    embed = discord.Embed(color=discord.Color.green())
    
    if issent_day == 0:
        # 首次发送:上传图片并发送Embed
        file = discord.File("result.png", filename="image.png")
        embed.set_image(url="attachment://image.png")
        day_msg = await chat.send(file=file, embed=embed)
        issent_day = 1
    else:
        # 编辑时:复用原消息的图片URL,仅更新Embed
        embed.set_image(url=day_msg.attachments[0].url)
        # 这里可添加其他Embed内容的更新逻辑(如标题、描述)
        await day_msg.edit(embed=embed)

情况2:需要更换Embed中的图片

由于编辑消息无法直接上传新附件,需先将新图片上传到Discord获取临时URL(或第三方图床),再用该URL更新Embed:

# 函数外定义全局变量
day_msg = None
issent_day = 0

async def day_vipe():
    global day_msg, issent_day
    chat = client.get_channel(1007301750895677491)
    embed = discord.Embed(color=discord.Color.green())
    
    if issent_day == 0:
        # 首次发送:上传图片并发送Embed
        file = discord.File("result.png", filename="image.png")
        embed.set_image(url="attachment://image.png")
        day_msg = await chat.send(file=file, embed=embed)
        issent_day = 1
    else:
        # 1. 临时上传新图片获取URL
        temp_msg = await chat.send(file=discord.File("result.png", filename="new_image.png"))
        new_image_url = temp_msg.attachments[0].url
        await temp_msg.delete()  # 删除临时消息
        
        # 2. 更新Embed的图片URL并编辑消息
        embed.set_image(url=new_image_url)
        # 可添加其他Embed内容更新逻辑
        await day_msg.edit(embed=embed)

注意事项

  • 确保issent_day和day_msg是全局变量(或通过其他方式持久化状态),否则重启机器人后会重置为初始状态。
  • Discord的临时附件URL有效期为1小时,若需长期有效,建议使用第三方图床存储图片。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:18:18