Skip to content
Advertisement

Updating variables with Discord.JS

I’m trying to work out how to update variables that are declared at runtime.

In my code it’s a simple random number generator. It works but doesn’t update, i.e. if the slash command /rng is used, alpha never updates past the initial number it picked, so it just repeats the same number at each use of /rng and I understand why. At the initial run, alpha is updated to a random number but it’s never updated again unless the script is ran again which isn’t possible in it’s current configuration unless I restart the bot.

I’m not even looking for someone to fix the code, more so a concept I can go look up or read into so I can learn.

const { SlashCommandBuilder } = require('discord.js');

const alpha = Math.floor(Math.random() * 11);
console.log(alpha);

module.exports = {
    data: new SlashCommandBuilder()
        .setName('rng')
        .setDescription('Number between 1 & 10'),
    async execute(interaction) {
        await interaction.reply(`${alpha}`);
    },
};

Advertisement

Answer

Everytime you run the script with slash command, it is running the code inside module.exports. In other words, variable outside module.exports are constants, which will be only declared once when the bot started up.

To get a different variable each of the time using the command, simply put const alpha ... inside module.exports, within the execute function.

module.exports = {
    data: new SlashCommandBuilder()
        .setName('rng')
        .setDescription('Number between 1 & 10'),
    async execute(interaction) {
        const alpha = Math.floor(Math.random() * 11);
        console.log(alpha);
        await interaction.reply(`${alpha}`);
    },
};
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement