Perseverance
Perseverance

Reputation: 11

My Discord Bot keeps sending the same image upon trigger

I'm working on my first Discord bot using NodeJS, the purpose of the bot is to respond to a message in Discord with a random image taken from the Imgur API whenever a user uses a trigger word in Discord. I have the following code:

request(options, function (error, response) {
  if (error) throw new Error(error);
  
  const randomNumber = Math.floor(Math.random() * 73) + 1; 

  arr = JSON.parse(response.body);
  var randomImage = arr.data[randomNumber].link;
  console.log(randomImage)
  bot.on("message", (msg) => {  
    if (msg.content === trigger){
      msg.channel.startTyping();
      msg.channel.send(randomImage);
  
    } 
    
  });
});

bot.login(TOKEN);

bot.on("ready", () => {
  console.info(`Logged in as ${bot.user.tag}!`);
});

Getting a random image from Imgur works, and using a trigger word in Discord to get to this image also works, however the problem is for example when I spam the trigger word in Discord 3 times, the bot will return the same image 3 times. The desired functionality is that on each trigger word, a different image gets sent. Whenever I restart the server a new image gets fetched from the Imgur API.

However the problem persists, when I use the trigger word x times in Discord the same image will be shown x times. Hope someone can put me in the right direction in how to solve this.

Upvotes: 1

Views: 472

Answers (1)

cagri
cagri

Reputation: 828

I believe request is called only once. So, you generate a random image only once and using it on all future messages. To generate a random image when a new message is received, try putting the random image generation inside the event handler like this:

request(options, function (error, response) {
  if (error) throw new Error(error);
  
  arr = JSON.parse(response.body);
  bot.on("message", (msg) => {  
    if (msg.content === trigger){
      const randomNumber = Math.floor(Math.random() * 73) + 1; 
      var randomImage = arr.data[randomNumber].link;
      console.log(randomImage)
      msg.channel.startTyping();
      msg.channel.send(randomImage);
    }
  });
});

Upvotes: 1

Related Questions