Discord.js v14 Hug斜杠命令无法正确对接some-random-api获取随机GIF
问题:Discord.js v14 Hug命令无法加载随机GIF的修复方案
问题详情
使用some-random-api实现Discord.js v14的Hug斜杠命令时,出现两个问题:
- 复制API返回的GIF链接写入代码,每次执行命令只会显示同一张GIF
- 直接将API端点URL设为图片地址,GIF无法正常显示
原代码如下:
const { EmbedBuilder, SlashCommandBuilder, AttachmentBuilder } = require("discord.js"); module.exports = { data: new SlashCommandBuilder() .setName("hug") .setDescription("Hug someone.") .addUserOption((option) => option.setName("user").setDescription("Select a user") .setRequired(true) ), async execute(client, interaction) { const { member, options, user } = interaction; let target = options.getUser("user") || user; let author = interaction.member; let canvas = `https://some-random-api.com/animu/hug`; let embed = new EmbedBuilder() .setImage(canvas) .setDescription(`${author} has hugged ${target}!`) .setColor('#2B2D31') .setTimestamp() .setFooter({ text: `Requested by ${member.user.tag}`, iconURL: member.displayAvatarURL() }); await interaction.reply({ embeds: [embed] }); }, };
修复方案
1. 明确API返回格式
https://some-random-api.com/animu/hug 端点返回的是JSON格式数据,而非直接的GIF文件。示例返回内容:
{ "link": "https://example.com/random-hug.gif", "id": "123" }
直接将端点URL设为图片地址,Discord无法识别JSON为图片,导致显示失败;硬编码复制的link值,只会固定使用该链接,失去随机性。
2. 修改代码实现动态请求
需要先发送HTTP请求获取API返回的JSON数据,提取其中的link字段作为图片地址。步骤如下:
- 安装HTTP请求库:执行
npm install node-fetch(Discord.js v14未内置请求工具) - 在代码中引入
node-fetch,并在execute函数中异步请求API
修改后的完整代码:
const { EmbedBuilder, SlashCommandBuilder } = require("discord.js"); const fetch = require('node-fetch'); // 引入请求库 module.exports = { data: new SlashCommandBuilder() .setName("hug") .setDescription("Hug someone.") .addUserOption((option) => option.setName("user").setDescription("Select a user") .setRequired(true) ), async execute(client, interaction) { const { member, options } = interaction; const target = options.getUser("user"); const author = interaction.member; try { // 请求API获取随机GIF链接 const response = await fetch('https://some-random-api.com/animu/hug'); const data = await response.json(); const hugGifUrl = data.link; const embed = new EmbedBuilder() .setImage(hugGifUrl) .setDescription(`${author} has hugged ${target}!`) .setColor('#2B2D31') .setTimestamp() .setFooter({ text: `Requested by ${member.user.tag}`, iconURL: member.displayAvatarURL() }); await interaction.reply({ embeds: [embed] }); } catch (error) { // 处理请求失败的情况 await interaction.reply({ content: 'Failed to get hug GIF, please try again later.', ephemeral: true }); console.error(error); } }, };
关键改动说明
- 添加了
node-fetch的引入和API请求逻辑,每次执行命令都会重新请求API获取新的随机GIF链接 - 增加了错误捕获,避免API请求失败导致命令报错
- 移除了无用的
AttachmentBuilder引入,原代码未使用该模块
内容的提问来源于stack exchange,提问作者Jonny
相关产品推荐
相关产品推荐

