Javascript 试图让我的Discord Bot在不循环消息的情况下重复生成答案,chooseanswer未定义

Javascript 试图让我的Discord Bot在不循环消息的情况下重复生成答案,chooseanswer未定义,javascript,discord,discord.js,Javascript,Discord,Discord.js,对于我的8ball命令,我试图让它不断地从数组中生成新的答案。 但是,我无法正确定义它,因为它位于函数内部。 如果我将send放在random()函数中,它将循环,这是我不想要的。 这是我的密码: const Discord = require("discord.js"); module.exports = { name: "8ball", description: "Ask something to the magic 8ba

对于我的8ball命令,我试图让它不断地从数组中生成新的答案。 但是,我无法正确定义它,因为它位于函数内部。 如果我将send放在
random()
函数中,它将循环,这是我不想要的。 这是我的密码:

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}".`);
       
    }
}

如我所见,您可以使用返回状态来捕获所选答案。它不会修改列表,并且总是返回不同的答案。 我已将该函数放在module.exports函数之外,并将所需答案放在文件顶部

const Discord=require(“Discord.js”);
const answersList=require(“../data/8ball.json”).answers;
module.exports={
名称:“8ball”,
描述:“向魔法8球询问一些事情。”,
执行(消息,参数){
让question=args.slice(1).join(“”);
如果(!问题){
msg.channel.send(“你需要问魔术师一些事情,伙计。”);
返回;
}       
msg.channel.send(“**你摇动你的8个球,努力思考,但很简单。**”;
msg.channel.send(“:8ball:您查看您的8ball并看到“+random(answersList)+”);
}
}
随机函数(答案){
const chooseanswer=answers[Math.floor(Math.random()*answers.length)];
返回选择答案;
}

此代码无效,因为chooseanswer是在random()中定义的,msg.channel.send不可用。也许您需要同步调用random()并返回值?但我不确定你所说的“不断生成新答案”是什么意思:你的意思是无限期地每3秒向频道发布一个新答案?我想你需要从你的random()函数内部发送消息。现在我明白了,我需要把它放到函数中,然后调用它。