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

discord.js如何将请求获取的JSON数据封装为Discord embed发送

Discord .data 命令推送VATSIM接口数据实现方案

实现逻辑说明

你当前已经完成了VATSIM公开数据接口的请求和日志打印,接下来只需对接Discord消息监听逻辑,将返回的JSON数据组装为Embed格式后回应用户即可。

前置依赖检查

  • 确保你的Discord.js版本为v14(示例代码基于v14编写,v13版本可将EmbedBuilder替换为MessageEmbed使用)
  • 已经在Discord开发者后台开启了Message Content Intent权限,否则机器人无法读取用户发送的文本命令

完整实现代码

const { Client, GatewayIntentBits, EmbedBuilder } = require('discord.js');
const request = require('request');

// 初始化机器人客户端
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent
  ]
});

// 机器人登录成功提示
client.on('ready', () => {
  console.log(`机器人已登录,账号:${client.user.tag}`);
});

// 监听消息事件
client.on('messageCreate', async message => {
  // 过滤机器人自己发送的消息,只响应用户发送的.data命令
  if (message.author.bot || message.content !== '.data') return;

  // 发起VATSIM接口请求
  request({
    url: "https://data.vatsim.net/v3/vatsim-data.json",
    json: true
  }, (err, response, body) => {
    // 请求异常处理
    if (err || !body || response.statusCode !== 200) {
      return message.reply('接口数据请求失败,请稍后重试');
    }

    // 取前15条飞行员数据展示,避免超过Embed长度限制
    const pilotList = body.pilots.slice(0, 15);
    
    // 构造Embed
    const dataEmbed = new EmbedBuilder()
      .setTitle('当前VATSIM在线飞行员数据')
      .setColor('#0099ff')
      .setTimestamp()
      .setFooter({ text: '数据来源:VATSIM公开接口' });

    // 遍历飞行员数据添加Embed字段
    pilotList.forEach(pilot => {
      dataEmbed.addFields({
        name: `呼号:${pilot.callsign}`,
        value: `CID:${pilot.cid}\n最后更新:${new Date(pilot.last_updated).toLocaleString('zh-CN')}`,
        inline: true
      });
    });

    // 发送Embed
    message.reply({ embeds: [dataEmbed] });
  })
});

// 填入你的机器人Token登录
client.login('你的Discord机器人Token');

可选优化点

  • 目前request库已经官方停止维护,你可以替换为axios或node-fetch等更流行的请求库,异步逻辑写法更简洁
  • 如果需要展示飞行计划相关信息,可以直接读取pilot.flight_plan对象下的字段,使用可选链操作符?.可以避免部分用户无飞行计划时抛出异常
  • 如果需要展示更多数据,可以拆分多条Embed发送,或者添加分页交互按钮

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:54:00