Home > Mobile >  how to pick a random string from an array every time the bot answers
how to pick a random string from an array every time the bot answers

Time:05-29

I'm trying to develop a simple discord bot which's made for chatting. I've created a string array that's supposed to store all answers the bot can give and then let the program give a random response based on that array. Now the bot does give a random answer but he only picks one random one from the array and only changes it when he's restarted. I was wondering if there's a way to make the bot pick a different answer every time he says something. Here's the current code:

const stringarray = [
      'string1',
      'string2',
      'string3',
];

let randomNumber = Math.floor(Math.random()*stringarray.length);

client.on("message", msg => {
  if (msg.content === "string0") {
    msg.reply(stringarray[randomNumber]);
  }
})

CodePudding user response:

The problem is you are setting randomNumber in the main code and not in the .on('message') callback! Therefore, the code is executed when you launch the server (and thus only once). You need to move it inside the callback for it to compute a new random value for each call:

client.on("message", msg => {
  if (msg.content === "string0") {
    let randomNumber = Math.floor(Math.random()*stringarray.length);
    msg.reply(stringarray[randomNumber]);
  }
})
  • Related