Trying to make my Discord Bot repeatedly generate answers without looping message, chooseanswer is undefined

Viewed 143

For my 8ball command, I am trying to make it constantly generate new answers from an array. However, I can not define it properly because it is inside a function. If I put the send inside the random() function, it will loop, which I do not want. Here is my code:

const Discord = require("discord.js");

module.exports = {
    name: "8ball",
    description: "Ask something to the magic 8ball.",
    execute(msg, args){
        let question = args.slice(1).join(" ");
        
        if (!question){
          msg.channel.send("You need to ask the magic 8ball something, dude.");
          return;
        }       

      function random(){
        const answers = require("../data/8ball.json").answers;
        const chooseanswer = answers[Math.floor(Math.random() * answers.length)];
        return true;
      }
      setInterval(random, 3000);
      
      msg.channel.send("**You shake your 8ball and think hard, yet simple.**");
      msg.channel.send(`:8ball: You look into your 8ball and see "${chooseanswer}".`);
       
    }
}
1 Answers

As I can see, you can use the return state to catch the selected answer. It will not modify the list and always return a different answer. I have put the function outside of the module.exports function and put the answers require at the top of the file.

const Discord = require("discord.js");
const answersList = require("../data/8ball.json").answers;

module.exports = {
    name: "8ball",
    description: "Ask something to the magic 8ball.",
    execute(msg, args){
        let question = args.slice(1).join(" ");
        
        if (!question){
          msg.channel.send("You need to ask the magic 8ball something, dude.");
          return;
        }       
      
      msg.channel.send("**You shake your 8ball and think hard, yet simple.**");
      msg.channel.send(":8ball: You look into your 8ball and see " + random(answersList) + ".");
       
    }
}

function random(answers){
  const chooseanswer = answers[Math.floor(Math.random() * answers.length)];
  return chooseanswer;
}
Related