Discord.js新手如何调用Rolimons API发送请求添加玩家至数据库
前置准备
- 环境要求:Node.js 18及以上版本可原生使用
fetch发起请求;低于该版本需执行npm i node-fetch安装依赖,调用前需导入:import fetch from 'node-fetch'(ESM项目)或const fetch = require('node-fetch')(CJS项目) - 注意:必须对传入的玩家名做URL编码处理,避免特殊字符导致参数解析错误;请求需添加自定义
User-Agent头,否则易被Rolimons反爬机制拦截
核心请求逻辑实现
单独调用接口的基础可复用函数:
async function addRolimonsPlayer(playerName) { // 对玩家名做URL编码,兼容空格、特殊符号等场景 const encodedName = encodeURIComponent(playerName); const requestUrl = `https://www.rolimons.com/playerapi/addplayer?playername=${encodedName}`; try { const response = await fetch(requestUrl, { method: 'GET', headers: { 'User-Agent': 'DiscordBot/1.0 (你的Bot名称)' } }); // 接口返回JSON格式结果,直接解析即可 const result = await response.json(); return result; } catch (err) { console.error('请求异常:', err); throw new Error('请求失败,请检查网络或玩家名'); } } // 测试调用,替换参数为实际玩家名即可 // addRolimonsPlayer('示例玩家名');
嵌入Discord.js v14 斜杠指令的完整实现
如果你要在Discord bot中通过指令触发请求,可参考以下完整逻辑(默认你已经完成Discord.js bot的基础初始化、令牌配置):
const { Client, GatewayIntentBits, ApplicationCommandOptionType } = require('discord.js'); const { REST } = require('@discordjs/rest'); const { Routes } = require('discord-api-types/v10'); // Bot基础配置 const client = new Client({ intents: [GatewayIntentBits.Guilds] }); const BOT_TOKEN = '你的Bot令牌'; const BOT_CLIENT_ID = '你的Bot客户端ID'; // 注册带玩家名参数的斜杠指令 const commandConfig = [{ name: 'add_rolimons_player', description: '将指定Roblox玩家添加到Rolimons数据库', options: [{ name: 'playername', description: '要添加的Roblox玩家名称', type: ApplicationCommandOptionType.String, required: true }] }]; // 初始化注册指令(仅需执行一次,调试完成后可注释) const rest = new REST({ version: '10' }).setToken(BOT_TOKEN); (async () => { try { await rest.put(Routes.applicationCommands(BOT_CLIENT_ID), { body: commandConfig }); console.log('斜杠指令注册完成'); } catch (err) { console.error('指令注册失败:', err); } })(); // 处理指令交互 client.on('interactionCreate', async interaction => { if (!interaction.isChatInputCommand() || interaction.commandName !== 'add_rolimons_player') return; // 先调用deferReply占位,规避Discord 3秒响应超时限制 await interaction.deferReply(); const inputPlayerName = interaction.options.getString('playername'); try { const requestResult = await addRolimonsPlayer(inputPlayerName); // 根据Rolimons返回的字段调整提示文案,示例为通用格式 await interaction.editReply(`添加请求已提交,结果:${requestResult.success ? '成功' : requestResult.message || '失败'}`); } catch (err) { await interaction.editReply('请求失败,请稍后重试或检查玩家名是否正确'); } }); // 启动Bot client.login(BOT_TOKEN);
关键注意事项
- 不要高频重复调用同一个玩家名的请求,Rolimons接口有频率限制,短时间多次触发会导致IP临时被拦截
- 一定要用
deferReply()处理Discord交互,异步请求耗时较长,不提前占位会被Discord判定为指令失效 - 部署Bot时需确认服务器出站规则允许访问Rolimons域名,否则会出现请求超时
内容的提问来源于stack exchange,提问作者0505Luke
相关产品推荐
相关产品推荐

