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

Discord Bot嵌入消息(Embed)图片无法正常嵌入问题求助

Discord Bot Embed图片显示在外部的解决方法

问题描述

调用.set_image方法将本地图片放入Discord Bot的Embed消息中,但图片始终显示在Embed外部,而非嵌入其中。

问题根源

代码中存在Windows路径转义错误,导致本地图片无法被正确关联到Embed的图片字段,Discord只能将其作为普通附件显示。

修复步骤

1. 修复Windows路径的转义问题

原代码中的路径字符串使用了未转义的反斜杠,在Python的f-string中会被解析为转义字符(比如\U会触发Unicode转义),导致路径解析错误。将路径改为原始字符串即可解决:

# 原代码
case_folder_path = f"C:\Users\Admin\Desktop\bot\Itens\{case_name}"

# 修改后(使用原始字符串rf)
case_folder_path = rf"C:\Users\Admin\Desktop\bot\Itens\{case_name}"

2. 验证附件引用一致性

确保embed.set_image(url=f"attachment://{chosen_item}")中的chosen_item和discord.File的filename参数完全一致,避免文件名包含特殊字符(如空格、非ASCII字符)导致关联失败。

修改后的完整代码

@bot.command(name='abrir')
async def abrir_case(ctx, case_name: str):
    user_id = str(ctx.author.id)
    current_balance = get_balance(user_id)

    if current_balance < 10:
        embed = discord.Embed(title="Erro ao abrir o caso", description=":x: Você não possui saldo suficiente para abrir o caso.", color=0xff0000)
        await ctx.reply(embed=embed)
        return

    update_balance(user_id, current_balance - 10)

    # 修复路径转义问题
    case_folder_path = rf"C:\Users\Admin\Desktop\bot\Itens\{case_name}"
    
    if not os.path.exists(case_folder_path):
        embed = discord.Embed(title="Erro ao abrir o caso", description=":x: Este caso não existe.", color=0xff0000)
        await ctx.reply(embed=embed)
        return

    total_weight = sum(RARITY_CHANCES.values())

    chosen_rarity = random.choices(list(RARITY_CHANCES.keys()), weights=[RARITY_CHANCES[rarity] / total_weight for rarity in RARITY_CHANCES])[0]

    rarity_folder_path = os.path.join(case_folder_path, chosen_rarity)

    items = os.listdir(rarity_folder_path)

    chosen_item = random.choice(items)

    desguaste = random.uniform(0, 1)

    embed = discord.Embed(title="Caso Aberto", description=f"Você abriu o caso {case_name} e obteve:", color=0x00ff00)
    embed.add_field(name="Item", value=chosen_item[:-4], inline=False)
    embed.add_field(name="Raridade", value=chosen_rarity, inline=False)
    embed.add_field(name="DESGUASTE", value=desguaste, inline=False)

    item_image_path = os.path.join(rarity_folder_path, chosen_item)
    try:
        if os.path.exists(item_image_path) and os.path.isfile(item_image_path):
            file = discord.File(item_image_path, filename=chosen_item)
            embed.set_image(url=f"attachment://{chosen_item}")
            await ctx.reply(file=file, embed=embed)
        else:
            await ctx.reply(embed=embed)
    except discord.HTTPException as e:
        print(f"Error sending image: {e}")
        await ctx.reply(embed=embed)

额外检查

  • 确认RARITY_CHANCES变量已正确定义,且对应稀有度的文件夹存在
  • 检查图片文件格式是否为Discord支持的类型(如PNG、JPG等)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:00:29