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

Python开发Discord机器人时embed内嵌图片显示异常问题求助

问题成因及解决方法

核心错误点

  • 附件文件名和embed引用的文件名不匹配:你创建discord.File对象时,给filename参数传入了固定值Star_Wars_Icon.png,但设置embed图片地址时用的是原图片文件名random_image,两者不一致导致Discord无法把附件匹配到embed的图片位置,只能单独展示附件。
  • 代码缩进不规范:装饰器下的函数定义、函数内部代码的缩进层级有误,可能会引发额外的运行异常。
  • 文件名切片操作存在风险:手动对路径做切片取文件名的方式,在存储路径变更时很容易出现取值错误,不需要额外做该操作。

修正后代码

import glob
import random
import discord
from discord.ext import commands

client = commands.Bot(command_prefix='!', intents=discord.Intents.all())

@client.command()
async def foto(ctx):
    channel = ctx.message.channel
    file_path_type = ["images/*.png"]
    # 直接获取随机图片的完整路径
    random_image_path = random.choice(glob.glob(random.choice(file_path_type)))
    # 统一附件文件名,要和embed里引用的文件名完全一致
    attachment_filename = "Star_Wars_Icon.png"
    embed = discord.Embed(
        title="Een star wars icon", 
        description="Zo eh! knap koppie.", 
        color=0x00ff00
    ) 
    file = discord.File(random_image_path, filename=attachment_filename)
    # 引用附件的url必须严格匹配上面设置的filename参数值
    embed.set_image(url=f"attachment://{attachment_filename}")
    await channel.send(file=file, embed=embed)

注意事项

  • 请确保你使用的discord.py为最新稳定版本,旧版本可能存在附件匹配的兼容性问题
  • 运行前需要开启机器人对应的消息、附件上传权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:27:03