【问题标题】:Giphy API always gives the same gifs (discord.js)Giphy API 总是提供相同的 gif (discord.js)
【发布时间】:2021-04-13 18:57:24
【问题描述】:

这可能是不恰当的,但我正在制作一个不和谐的机器人,并且在此过程中我想制作一个“gif”命令。我选择了 Giphy api,因为它似乎是最简单的。但每次我让机器人获取趋势 gif 时,它都会给我相同的 gif。 (附示例) Here you can see he bot sending the same gif 2 times

这是该命令所需的代码:

if (message.content.startsWith(`${prefix}gif`)) {
    giphy.trending('gifs', {limit:100})
        .then((response) => {
            var totalResponses = response.data.length;
            var responseIndex = Math.floor((Math.random() * 10) + 1) % totalResponses;
            var responseFinal = response.data[responseIndex];
               
            message.channel.send("Here is a gif for you!\n", {
                files: [responseFinal.images.fixed_height.url]
            }).catch(() => {
                message.channel.send('There was an API error, please try later.')
            })
        })
}

感谢任何答案。

【问题讨论】:

    标签: node.js discord discord.js giphy giphy-api


    【解决方案1】:

    我从未使用过 giphy API,但您只是想从数组中获取随机索引,而这很简单:

    var totalResponses = response.data.length;
    var responseIndex = Math.floor(Math.random() * totalResponses);
    var responseFinal = response.data[responseIndex];
    
    message.channel.send("Here is a gif for you!\n", {
                       files: [responseFinal.images.fixed_height.url]
                   }).catch(() => {
                       message.channel.send('There was an API error, please try later.')
                   })
    

    totalResponses 是数组的长度,我们需要从中获取一个随机数。这是在responseIndex 中完成的。所以现在在responseIndex 中存储了一个从 0 到totalResponses 的随机数(这正是我们想要的,因为数组总是从 0 开始,所以 0 可能是一个可能的索引)。然后在responseFinal中,我们将数组的值存储在responseIndex的随机索引处。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 2020-07-19
      • 2017-05-31
      • 2020-01-28
      • 2019-07-26
      • 2020-02-14
      • 1970-01-01
      相关资源
      最近更新 更多