I am currently developing a Discord bot with Discord.JS and have encountered an issue that seems to stem more from JavaScript itself rather than the library. I have created a file named commandManager.js that defines my command functions. This file is responsible for loading commands from the /commands/ directory and classifying them into an array based on their designated category specified in the command export.
const userCommands = {};
const modCommands = {};
const adminCommands = {};
const ownerCommands = {};
exports.initialize = function(bot) {
fs.readdir('./commands/', (err, files) => {
if (err) {
console.error(err);
}
files.forEach(file => {
const commandFile = require(`../commands/${file}`);
const commandKey = file.split('.')[0];
switch (commandFile.info.category) {
case 'User':
userCommands[commandKey] = commandFile;
break;
case 'Mod':
modCommands[commandKey] = commandFile;
break;
case 'Admin':
adminCommands[commandKey] = commandFile;
break;
case 'Owner':
ownerCommands[commandKey] = commandFile;
break;
default:
console.warn(`Could not categorize the command ${commandKey}.`);
}
});
console.info(`Loaded ${files.length} command(s)`);
});
};
After loading commands, I implemented command handling in the bot, which is executed as follows:
exports.execute = function(bot, message) {
const params = message.content.slice(config.prefix.length).trim().split(/ +/g);
const cmd = params.shift().toLowerCase();
if (message.author.bot) return;
if (!message.content.startsWith(config.prefix)) return;
if (Object.prototype.hasOwnProperty.call(userCommands, cmd)) {
message.reply('user');
} else if (Object.prototype.hasOwnProperty.call(modCommands, cmd)) {
// Mod command handling
} else if (Object.prototype.hasOwnProperty.call(adminCommands, cmd)) {
// Admin command handling
} else if (Object.prototype.hasOwnProperty.call(ownerCommands, cmd)) {
// Owner command handling
} else {
message.reply(`That command does not exist! Use ${config.prefix}help for a list of available commands.`);
}
};
For example, when I type “ping”, it should respond with message.reply('user'), but instead, it claims the command does not exist. I have defined has globally to check if the commands exist.
global.has = Object.prototype.hasOwnProperty;
Here’s how the Ping command is structured:
exports.info = {
name: 'Ping',
permission: 10,
category: 'User',
description: 'Responds with pong, indicating the bot is operational.'
};
exports.execute = function(message) {
message.channel.send('Pong!');
};
I welcome any suggestions, references, or examples that could assist me. Additionally, if you have recommendations for improving my approach, I’d appreciate it since I am still learning JavaScript.