0

I'm writing a NodeJS application that can do some queueing in Discord. My main includes an array called queuedPlayers and is defined in the following code:

// Define our required packages and our bot configuration 
const fs = require('fs');
const config = require('./config.json');
const Discord = require('discord.js');

// Define our constant variables 
const bot = new Discord.Client();
const token = config.Discord.Token; 
const prefix = config.Discord.Prefix;
let queuedPlayers = []; 

// This allows for us to do dynamic command creation
bot.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); 

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    bot.commands.set(command.name, command)
}

// Event Handler for when the Bot is ready and sees a message
bot.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(' ');
    const command = args.shift().toLowerCase();
    
    if (!bot.commands.has(command)) return;

    try {
        bot.commands.get(command).execute(message, args);
    } catch (error) {
        console.error(error);
        message.reply('There was an error trying to execute that command!');
    }

});

// Start Bot Activities 
bot.login(token); 

I then create a command in a seperate JS file and I am trying to access the Queued Players array so that way I can add to them:

module.exports = {
    name: "add",
    description: "Adds a villager to the queue.",
    execute(message, args, queuedPlayers) {
        if (!args.length) {
            return message.channel.send('No villager specified!');
        }

        queuedPlayers.push(args[0]);
    },
};

However, it keeps telling me that it is undefined and can't read the attributes of the variable. So I'm assuming it isn't passing the array over properly. Do I have to use an exports in order to able to access it between different Javascript files? Or would it be best just to use a SQLite local instance to create and manipulate the queue as needed?

1
  • Yes, if you need to access it from a different file you've to export it in the original file and require it in the new file. Commented Aug 22, 2020 at 18:42

1 Answer 1

1

It's undefined because you aren't passing the array

Change

bot.commands.get(command).execute(message, args);

to

bot.commands.get(command).execute(message, args, queuedPlayers);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.