Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda