问题描述
我正在编写一个可以在discord中进行排队的NodeJS应用程序。我的主要对象包括一个名为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本地实例来根据需要创建和操作队列?
解决方法
它是未定义的,因为您没有传递数组
更改
bot.commands.get(command).execute(message,args);
到
bot.commands.get(command).execute(message,args,queuedPlayers);