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
相关产品推荐
相关产品推荐

