Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
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]);
  }
})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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]);
  }
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!