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

如何在JavaScript中从Rolimons API取值并赋值给变量(Discord机器人开发)

实现Discord机器人从Rolimons API获取物品Value值

以下是基于Discord.js的实现方案,直接适配你的需求:

核心逻辑步骤

  • 发起请求获取Rolimons物品API的完整数据
  • 根据用户提供的物品ID,定位到对应的数据数组
  • 提取数组中索引为3的元素(即你需要的value值),赋值给Value变量

代码示例(Discord.js v14+)

import { Client, GatewayIntentBits } from 'discord.js';
import fetch from 'node-fetch'; // Node.js 18+可改用内置fetch

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent
  ]
});

// 监听用户消息,假设用!value 物品ID触发查询
client.on('messageCreate', async (message) => {
  if (!message.content.startsWith('!value')) return;

  const itemId = message.content.split(' ')[1];
  if (!itemId) return message.reply('请提供要查询的物品ID');

  try {
    // 获取API数据
    const res = await fetch('https://www.rolimons.com/itemapi/itemdetails');
    const apiData = await res.json();

    // 校验物品ID是否存在
    if (!apiData.items[itemId]) {
      return message.reply(`未找到ID为${itemId}的物品`);
    }

    // 提取value值并赋值给变量
    const Value = apiData.items[itemId][3];
    message.reply(`物品ID ${itemId} 的Value值:${Value}`);

    // 这里的Value变量可用于后续业务逻辑
  } catch (err) {
    console.error('查询出错:', err);
    message.reply('查询失败,请稍后重试');
  }
});

client.login('你的Discord机器人Token');

关键说明

  • API返回的apiData.items是一个对象,键为物品ID,值为你描述的数组结构
  • 数组索引从0开始,[3]对应数组中第4个元素,也就是需求里的value值
  • 加入了基础错误处理,覆盖API请求失败、物品ID不存在的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:30:55