frappzlul
frappzlul

Reputation: 21

My discord.js bot sends multiple gifs instead of one. How do I fix this?

I'm trying to make this command on my discord bot where it sends a random kirby gif using the giphy api. However, I only want it to send one, but it sends multiple. This is the code:

client.on('message', message => {
    if (message.content === 'k!gif')

    giphy.search('gifs', {"q": "kirby"})
    .then((response) => {
        var totalResponses = response.data.length
        var responseIndex = Math.floor((Math.random() * 10) + 1) % totalResponses;
        var responseFinal = response.data[responseIndex]

        message.channel.send("We stan kirby gifs", {
            files: [responseFinal.images.fixed_height.url]
        })
    }).catch(() => {
        message.channel.send('Kirby has run into a roadblock and was unable to complete his task.');
    })

})

Thanks for helping in advance!

Upvotes: -2

Views: 638

Answers (2)

Dorian349
Dorian349

Reputation: 1589

As @Giuiopime highlighted, you are not making any requirement for the command. So every time you send a message, the current code is executed and the gif is sent. Once this one is sent, a new message is caught by the bot and the process continues again and again...

Make sure to attach the current code inside the if and also verify that the player isn't a bot. This code may work. I didn't have tested it.

client.on('message', message => {
  if(message.author.bot) return;
  if (message.content === 'k!gif'){
    giphy.search('gifs', {"q": "kirby"}).then((response) => {
      
        var totalResponses = response.data.length
        var responseIndex = Math.floor((Math.random() * 10) + 1) % totalResponses;
        var responseFinal = response.data[responseIndex]

        message.channel.send("We stan kirby gifs", {
            files: [responseFinal.images.fixed_height.url]
        })
    }).catch(() => {
        message.channel.send('Kirby has run into a roadblock and was unable to complete his task.');
    })
  }
})

Upvotes: 1

Giuliopime
Giuliopime

Reputation: 1207

You used if (message.content === 'k!gif') without opening any curly braces, so what you need to do is to include all your code in that if.

Upvotes: 0

Related Questions