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

如何在Discord嵌入消息中直接使用Pillow生成的图片(无需存盘)

解决Discord嵌入消息中直接使用Pillow生成的内存图片问题

Discord的Embed.set_image()方法只接受图片URL,没法直接传二进制数据,但可以通过Discord本地附件URL实现需求——不用存硬盘,还能让图片成为嵌入的一部分,不会破坏嵌入格式。

具体步骤和代码如下:

  1. 用Pillow生成图片后,存入BytesIO内存流
  2. 创建discord.File对象关联这个内存流
  3. 给嵌入的图片设置attachment://文件名格式的URL(这是Discord内部识别的上传附件地址)
  4. 发送时同时传入嵌入和文件,此时图片会显示在嵌入里,不会作为独立附件展示

示例代码:

import io
from PIL import Image
import discord

# 用Pillow生成示例图片(替换成你的生成逻辑)
img = Image.new('RGB', (300, 200), color='#2ECC71')

with io.BytesIO() as image_binary:
    img.save(image_binary, 'PNG')
    image_binary.seek(0)
    # 创建Discord文件对象,指定文件名
    img_file = discord.File(fp=image_binary, filename="embedded_img.png")
    # 创建嵌入消息
    embed = discord.Embed(title="内存生成图片嵌入", description="这张图是Pillow直接在内存生成的")
    # 用附件URL设置嵌入图片
    embed.set_image(url=f"attachment://{img_file.filename}")
    # 可选:添加页脚测试样式
    embed.set_footer(text="测试页脚样式,不会被破坏")
    # 发送消息
    await channel.send(embed=embed, file=img_file)

这种方式下,用户只会看到完整格式的嵌入消息,图片是嵌入的一部分,不会出现单独的文件附件,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:50:31