Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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]);
  }
})

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]);
  }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading