I’m working on an 8ball feature for my Discord bot and running into a scope issue. I want the bot to pick different responses from an array each time someone uses the command, but I’m having trouble accessing the selected answer outside of my randomization function.
When I try to reference the chosen response in my message, it shows as undefined. I know this is because the variable is declared inside the function scope, but when I move the message sending into the randomization function, it creates a loop that spams the channel every few seconds.
Here’s what I have so far:
const Discord = require("discord.js");
module.exports = {
name: "fortune",
description: "Get a prediction from the mystical fortune teller.",
execute(message, arguments){
let userQuery = arguments.slice(1).join(" ");
if (!userQuery){
message.channel.send("Please ask the fortune teller a question first.");
return;
}
function getRandomResponse(){
const responses = require("../data/fortune.json").responses;
const selectedResponse = responses[Math.floor(Math.random() * responses.length)];
return true;
}
setInterval(getRandomResponse, 3000);
message.channel.send("**The crystal ball swirls with mysterious energy...**");
message.channel.send(`:crystal_ball: The fortune teller reveals: "${selectedResponse}".`);
}
}
How can I properly return the random selection from my function so I can use it in the message without creating an infinite loop?