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

为什么Discord机器人调用GIPHY API时无论输入数量多少都只返回1条结果?

问题根因

你的代码已经正确将limit参数传给了GIPHY接口,接口也确实返回了你指定数量的结果,问题出在返回结果处理逻辑:你只提取了结果数组json.data的第1个元素(json.data[0])进行输出,所以不管limit设置多大,最终都只会返回1条结果。
不同count值返回的GIF/贴纸不同,是因为GIPHY会根据limit参数调整返回结果集的偏移和范围,你每次取出的都是对应结果集的第一条,所以会出现单条内容随count变化的现象。

修复方案

你需要遍历json.data数组,把所有返回的结果URL拼接后再一次性输出即可。参考修复后的代码如下:

const fetch = require('node-fetch')

module.exports = {
    name: 'gifsearch',
    description: 'Returns a gif based on your search term.',
  options: [{
    name: 'type',
    type: 'STRING',
    description: 'Whether to search for a GIF or sticker.',
    choices: [
      {
        name: 'GIF',
        value: 'gif'
      },
      {
        name: 'Sticker',
        value: 'sticker'
      }
    ],
    required: true,
  },
  {
    name: 'search_term',
    type: 'STRING',
    description: 'The search term to use when searching for gifs.',
    required: true,
  },
  {
    name: 'count',
    type: 'INTEGER',
    description: 'The number of results to be returned.',
    required: true,
  }],
    async execute(interaction) {
    let resultCount = interaction.options.getInteger('count')
    let searchType = interaction.options.getString('type')
    let searchTerm = interaction.options.getString('search_term')

    if (resultCount < 1) return interaction.reply('You have to search for at least 1 result.')
    // 可选:限制最大返回数量,避免超出Discord消息长度限制
    const MAX_COUNT = 10
    resultCount = Math.min(resultCount, MAX_COUNT)

    try {
      let apiUrl = searchType === 'gif' 
        ? `https://api.giphy.com/v1/gifs/search?q=${encodeURIComponent(searchTerm)}&api_key=${process.env.giphyAPIkey}&limit=${resultCount}&rating=g`
        : `https://api.giphy.com/v1/stickers/search?q=${encodeURIComponent(searchTerm)}&api_key=${process.env.giphyAPIkey}&limit=${resultCount}&rating=g`
      
      const res = await fetch(apiUrl)
      const json = await res.json()

      if (json.data.length <= 0) return interaction.reply({ content: `No results found!` })
      // 拼接所有结果URL,用换行分隔
      const content = json.data.map(item => item.url).join('\n')
      interaction.reply({ content })
    } catch (err) {
      console.error('GIPHY request failed:', err)
      interaction.reply({ content: 'Failed to fetch resources, please try again later.' })
    }
  }
};

额外优化说明

  • 新增了encodeURIComponent处理搜索词,避免搜索词含特殊字符时请求报错
  • 新增了最大返回数量限制,防止用户输入过大数值导致消息超出Discord长度限制
  • 改用async/await写法替换原来的链式then,代码可读性更高
  • 新增了异常捕获逻辑,避免接口请求失败时机器人无响应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:39:00