0

我正在编写一个可以在 Discord 中进行排队的 NodeJS 应用程序。我的 main 包含一个名为 queuedPlayers 的数组,并在以下代码中定义:

// 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); 

然后,我在单独的 JS 文件中创建一个命令,并尝试访问 Queued Players 数组,以便可以添加到它们:

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]);
    },
};

但是,它一直告诉我它是未定义的并且无法读取变量的属性。所以我假设它没有正确传递数组。我是否必须使用导出才能在不同的 Javascript 文件之间访问它?还是最好只使用 SQLite 本地实例来根据需要创建和操作队列?

4

1 回答 1

1

它是未定义的,因为您没有传递数组

改变

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

bot.commands.get(command).execute(message, args, queuedPlayers);
于 2020-08-22T20:53:21.403 回答