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

discord.py中如何将API返回的JSON转为格式化Embed嵌入式消息

代码调整方案

核心问题梳理

原有代码存在几个逻辑错误,先修正后再实现Embed排版:

  • 同时初始化Bot和Client两个实例会导致运行冲突,discord.ext.commands.Bot本身继承了Client的全部能力,无需重复定义
  • API请求写在全局仅会启动时执行一次,建议移到命令内部保证每次调用都拿最新数据
  • 错误将响应对象、字典当做文件路径读取,完全不符合正常调用逻辑
  • 使用了旧版discord.py废弃语法,适配v2.x以上版本需要调整写法

修正后完整代码

import discord
import requests
from discord.ext.commands import Bot

# 配置机器人权限和前缀
intents = discord.Intents.default()
intents.message_content = True
bot = Bot(command_prefix="!", intents=intents)

# API地址
url = "https://api-mainnet.magiceden.io/collections/angomon"

@bot.event
async def on_ready():
    print(f'已登录为 {bot.user}')

@bot.command(name='display')
async def display_collection(ctx):
    # 发起请求获取最新数据
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        data = response.json()
    except Exception as e:
        await ctx.send(f"请求API失败:{str(e)}")
        return

    # 构建Embed
    embed = discord.Embed(
        title = data['name'],
        description = data['description'],
        colour = discord.Color.blue(),
        timestamp = discord.utils.utcnow()
    )
    # 设置缩略图
    embed.set_thumbnail(url=data['image'])
    # 添加基础信息字段
    embed.add_field(name='符号', value=data['symbol'], inline=True)
    embed.add_field(name='创建时间', value=data['createdAt'].split('T')[0], inline=True)
    embed.add_field(name='启用属性筛选', value='是' if data['enabledAttributesFilters'] else '否', inline=True)
    # 处理糖果机ID列表
    candy_ids = '\n'.join([f'`{id_}`' for id_ in data['candyMachineIds']])
    embed.add_field(name='糖果机ID', value=candy_ids, inline=False)
    # 页脚
    embed.set_footer(text='数据来源:Magic Eden')

    # 发送消息
    await ctx.send(embed=embed)

# 启动机器人,替换为你自己的机器人令牌
bot.run("你的机器人Token")

效果说明

发送!display命令后,机器人会发送排版好的Embed消息,结构如下:

  • 标题为集合名称Angomon
  • 头部展示集合描述和官方缩略图
  • 同行展示符号、创建时间、是否启用筛选等基础属性
  • 单独区块展示全部糖果机ID,用代码格式包裹方便复制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:54:08