如何在Discord.py交互中发送多个带图片的Embed?
问题描述
实现Discord交互命令时,根据howmany参数指定次数发送带图片的Embed,但仅第一个Embed显示图片,后续Embed无法加载图片。当前交互命令代码如下:
@tree.command(name='embed', description='embed') async def embed(interaction: discord.Interaction, seeable: bool, howmany: typing.Optional[int]): embed = discord.Embed(title="Here is a title", color=0xff8c00) file = discord.File(f"[file path]", filename="image.png") embed.set_image(url="attachment://image.png") if seeable == True: await interaction.response.send_message(file=file, embed=embed) if howmany >= 2: for i in range(howmany-1): await interaction.followup.send(file=file, embed=embed) if seeable == False: await interaction.response.send_message(file=file, embed=embed, ephemeral=True) if howmany >= 2: for i in range(howmany-1): await interaction.followup.send(file=file, embed=embed, ephemeral=True)
旧前缀系统下功能正常(使用远程图片URL),代码示例:
if message.content.startswith('+image'): count = 0 args = message.content.split(' ') if len(args) < 2: count = 1 else: if args[1].isdigit(): count = int(args[1]) else: await message.channel.send("How many should it be?") for i in range(count): random = random.randint(1,68) embed = discord.Embed(title="Title", color=0xff8c00) embed.set_image(url=f"https://www.awebsite/pic{random}.png") # file = discord.File(f"C:a/file/path/pic{random}.png", filename="image.png") # embed.set_image(url="attachment://image.png") # await message.channel.send(file=file, embed=embed) await message.channel.send(embed=embed)
问题原因
discord.File对象只能被Discord API处理一次,复用同一个File实例发送后续消息时,Discord不会重新上传该文件,导致后续Embed中的attachment://image.png找不到对应的附件资源。旧前缀系统使用远程URL时,每个Embed直接指向独立的远程资源,因此没有这个问题。
修复方案
每次发送消息(包括初始响应和后续跟进消息)时,重新创建discord.File实例,确保每次请求都携带有效的文件附件。
修改后的代码示例:
@tree.command(name='embed', description='embed') async def embed(interaction: discord.Interaction, seeable: bool, howmany: typing.Optional[int]): # 处理howmany默认值,避免参数为None的情况 howmany = howmany or 1 def create_embed_with_file(): # 每次调用生成全新的File和Embed实例 file = discord.File(f"[file path]", filename="image.png") embed = discord.Embed(title="Here is a title", color=0xff8c00) embed.set_image(url="attachment://image.png") return file, embed if seeable: # 发送初始响应 file, embed = create_embed_with_file() await interaction.response.send_message(file=file, embed=embed) # 发送后续消息 for _ in range(howmany - 1): file, embed = create_embed_with_file() await interaction.followup.send(file=file, embed=embed) else: # 发送仅自己可见的初始响应 file, embed = create_embed_with_file() await interaction.response.send_message(file=file, embed=embed, ephemeral=True) # 发送仅自己可见的后续消息 for _ in range(howmany - 1): file, embed = create_embed_with_file() await interaction.followup.send(file=file, embed=embed, ephemeral=True)
补充说明
- 封装
create_embed_with_file函数是为了避免重复代码,确保每次发送都生成全新的File和Embed实例,保证附件有效性。 - 增加
howmany = howmany or 1处理参数为None的情况,确保至少发送1次消息。
内容的提问来源于stack exchange,提问作者lorenzfohl
相关产品推荐
相关产品推荐

