node.jsdiscorddiscord.jsgiphygiphy-api

Giphy API always gives the same gifs (discord.js)


This might be innapropriate, but I am making a discord bot, and in the process I wanted to make a "gif" command. I had chosen the Giphy api as it seemed to be the most simple one out there. But everytime I ask the bot to fetch a trending gif, it gives me the same gifs. (Example attached) Here you can see he bot sending the same gif 2 times

Here is the code needed for this command:

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

Any answers are appreciated.


Solution

  • I've never worked with the giphy API, but you are just trying to get a random index from an array and that is simply done by doing:

    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 is the length of the array, which we need to get a random number from. That is done in responseIndex. So now in responseIndex a random number from 0 to totalResponses is stored (and that is exactly what we wanted, because an array always starts at 0, so 0 could be a possible index). Then in responseFinal, we store the value of the array at the random index from responseIndex.