0

我正在为我的 Discord 机器人创建一个命令,从这个 GIPHY API 端点获取 GIF 或贴纸:https ://developers.giphy.com/docs/api/endpoint#search

我提供的限制等于用户选择的数字,但是,无论我提供什么数字,它都只返回 1。

命令:

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.')

    if (searchType === 'gif') {
      const res = fetch(`https://api.giphy.com/v1/gifs/search?q=${searchTerm}&api_key=${process.env.giphyAPIkey}&limit=${resultCount}&rating=g`)
      .then((res) => res.json())
      .then((json) => {
        if (json.data.length <= 0) return interaction.reply({ content: `No gifs found!` })
      interaction.reply({content: `${json.data[0].url}`})
      })
    }
    else if (searchType === 'sticker') {
      const res = fetch(`https://api.giphy.com/v1/stickers/search?q=${searchTerm}&api_key=${process.env.giphyAPIkey}&limit=${resultCount}&rating=g`)
      .then((res) => res.json())
      .then((json) => {
      if (json.data.length <= 0) return interaction.reply({ content: `No gifs found!` })
      interaction.reply({content: `${json.data[0].url}`})
      })
    }
  
    },
};

正如我上面所说,用户可以使用该count选项来指定要返回的结果数量。但是,我的机器人在每种情况下都只返回一个结果。但是每个数字都会产生不同的 GIF 或贴纸。

我希望它返回用户提供的结果数。

4

1 回答 1

0

在您的代码中,您只发送json.data[0].url,无论count用户提供什么。

要发送所有图像,您可以执行以下操作:

interaction.reply({
  // assumes the limit === number chosen
  content: json.data.map(result => result.url).join("\n")
});
于 2021-08-25T04:11:31.163 回答