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

Discord.py发送Embed时图片未加载及本地图片嵌入问题求助

Discord.py Embed图片问题解决方案

一、解决外部URL缩略图加载延迟问题

Discord通过外部URL加载Embed缩略图时,由Discord服务器主动拉取图片,会出现消息先发送、图片后加载的情况。解决思路是先异步下载图片,将其作为消息附件一起发送,再用附件的本地引用路径设置缩略图,实现图片与消息同步加载。

正确代码示例

import discord
import aiohttp

client = discord.Client(intents=discord.Intents.default())
planet_api_url = "https://app.pixelencounter.com/api/basic/planets?frame=1000&disableBackground=true&disableStars=true"

@client.event
async def on_message(message):
    if message.author == client.user:  # 避免机器人响应自身消息
        return
    
    # 异步下载图片
    async with aiohttp.ClientSession() as session:
        async with session.get(planet_api_url) as resp:
            if resp.status == 200:
                image_data = await resp.read()
                # 将二进制图片转为Discord附件对象
                file = discord.File(fp=image_data, filename="planet.png")
                
                # 创建Embed并绑定附件路径作为缩略图
                embed = discord.Embed(title="随机星球")
                embed.set_thumbnail(url="attachment://planet.png")
                
                # 同步发送Embed和附件
                await message.channel.send(embed=embed, file=file)

client.run("你的机器人TOKEN")

关键注意点

  • 必须用aiohttp替代requests:requests是同步库,会阻塞Discord.py的事件循环,导致机器人响应卡顿。
  • 附件引用格式:attachment://文件名是Discord内部专属路径,仅当文件作为当前消息附件发送时生效。

二、本地图片嵌入Embed的方法

若已将图片保存到本地,只需读取本地文件为discord.File对象,用attachment://文件名设置Embed的图片字段,再与Embed一同发送即可。

代码示例

import discord

client = discord.Client(intents=discord.Intents.default())

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    
    # 读取本地图片文件(替换为你的实际路径)
    file = discord.File("./saved_planet.png", filename="local_planet.png")
    
    embed = discord.Embed(title="本地星球图片")
    embed.set_thumbnail(url="attachment://local_planet.png")
    
    # 发送Embed与本地附件
    await message.channel.send(embed=embed, file=file)

client.run("你的机器人TOKEN")

关键注意点

  • 确保机器人对本地图片路径有读取权限,路径填写准确。
  • filename参数可自定义,Embed中的引用路径必须与该参数完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:18:34