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

discord.js v12从数组取值实现动漫GIF返回指令开发问题

Discord anime指令调整方案

核心修改点

  • 修正参数获取逻辑:指令<anime 分类的第一个参数即为目标分类,原代码args.slice(1)会丢弃有效分类参数,改为直接取args[0]
  • 新增分类合法性校验:判断用户输入的分类是否在预设的animearray数组中,未传参/分类不存在时直接返回错误提示
  • 补全资源获取逻辑:新增GIF资源请求逻辑,补全原代码未定义的data变量
  • 优化返回Embed结构:将GIF直接嵌入Embed的图片字段,适配Discord展示逻辑

前置依赖

需要先安装http请求库,执行命令:
npm install axios

调整后完整代码

const axios = require('axios');
const Discord = require('discord.js');
const config = require('你的config文件路径'); // 替换为你实际的config引入路径

module.exports = {
  name: "anime",
  description: "返回对应分类的随机动漫GIF",
  async execute(message, args) {
    // 预设可用分类数组
    const animearray = [
      "angry",
      "anime",
      "bite",
      "bored",
      "bread",
      "chocolate",
      "cookie",
      "cuddle",
      "dance",
      "drunk",
      "happy",
      "kill",
      "kiss",
      "laugh",
      "lick",
      "lonely",
      "pat",
      "poke",
      "pregnant",
      "punch",
      "run",
      "satouselfies",
      "sleep",
      "spank",
      "steal",
      "tickle",
    ];

    // 错误提示Embed
    const errorEmbed = new Discord.MessageEmbed()
      .setDescription(`你选择的分类暂未支持,可使用 \`${config.PREFIX}list\` 查看当前所有可用分类`)
      .setColor('#E74C3C');

    // 校验是否传入分类参数
    const category = args[0]?.toLowerCase();
    if (!category) return message.reply({ embeds: [errorEmbed] });

    // 校验分类是否在可用数组中
    if (!animearray.includes(category)) return message.reply({ embeds: [errorEmbed] });

    try {
      // 请求对应分类的GIF资源
      const res = await axios.get(`https://nekos.life/api/v2/img/${category}`);
      const gifUrl = res.data.url;

      // 构造返回Embed
      const resultEmbed = new Discord.MessageEmbed()
        .setTitle(`${category} 分类随机动漫GIF`)
        .setImage(gifUrl)
        .setColor('#2ECC71');

      await message.channel.send({ embeds: [resultEmbed] });
    } catch (err) {
      // 请求失败提示
      const requestErrorEmbed = new Discord.MessageEmbed()
        .setDescription('资源获取失败,请稍后重试')
        .setColor('#E74C3C');
      await message.reply({ embeds: [requestErrorEmbed] });
    }
  },
};

功能验证

用户发送 <anime angry 时,机器人会自动校验angry属于可用分类,请求对应GIF后嵌入Embed发送到当前频道。如果用户输入不存在的分类、或者未传分类参数,都会返回错误提示Embed。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:30:05