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

如何在单个discord.Embed的description字段中展示多组JSON键值对

问题原因

你当前的问题核心是把Embed实例的创建、发送逻辑放在了proof字典的遍历循环内部,每处理一个键值对就会发送一条独立的Embed消息。同时你代码里的JSON路径占位符存在命名错误:你定义的占位符是idproof,但格式化时传入的参数是idpersonaje,会导致路径匹配错误找不到对应文件。

修正后的完整代码
@commands.command(aliases=["pj"])
async def personaje(self, ctx, personaje=None, member: discord.Member=None):
    if personaje is None:
        await ctx.send(":x: Debes proporcionar la id del personaje")
        return
    if member is None:
        member = ctx.author
    # 修复路径占位符命名错误,简化为f-string写法更易读
    file_path = f"json/Roleplay/Personajes/{member.id}/{personaje}.json"
    if os.path.exists(file_path): 
        with open(file_path, 'r') as f:
            data = json.load(f)
            Name = data["Name"]
            color = int(data["Color"], 16) # 颜色转换只需要执行一次
            proof = data["proof"]
        
        # 先拼接所有proof的键值对内容
        proof_content = ""
        for key, value in proof.items():
            proof_content += f"\n**{key}:** {value}"
        
        # 循环外只创建、发送一次Embed
        timestamp = datetime.datetime.now()
        embed=discord.Embed(
            description=f"**Name:** {Name}{proof_content}",
            color=color
        )
        embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
        embed.timestamp = timestamp
        await ctx.send(embed=embed)
    else:
        await ctx.send(":x: Este personaje no existe")
        return
实现逻辑说明
  • 提前遍历proof字典,把所有键值对拼接成完整的字符串后再统一放到Embed的description字段中
  • 把Embed的创建、发送逻辑移到循环外部,全程只会发送一条Embed消息
  • 修复了路径占位符的命名错误,避免出现找不到文件的问题
  • 将颜色转换逻辑移出循环,避免重复执行无意义的转换操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 10:03:02