I am new to JS and programming in general, so please explain with that in mind. I know that this question is not formulated very well, but I couldn't think of how to formulate it better so feel free to edit it. I am making a discord bot with discord.js. I have made a command called 'test'. My code is as follows (in a file named test.js):
module.exports = {
name: 'test',
description: 'Test command. Sends back "Test successful."',
prefixType: 'devPrefix',
execute(msg, args) {
if (!args.length){
msg.channel.send('Test successful.');
} else {
msg.channel.send('Test successful. You entered ' + args.length + ' argument(s).')
}
},
};
How do i get the value prefixType and use it in my main index.js file? However the solution needs to work for any file in a folder (called 'commands'), not just with test.js.
If this helps, I am including the code in my main index.js file that deals with handling and executing commands:
const Discord = require('discord.js');
const fs = require('fs'); //For commands (fs = file system)
const botClient = new Discord.Client;
const CONFIG = require('./config.json');
//Get the commands
botClient.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
botClient.commands.set(command.name, command);
}
botClient.once('ready', () => {
console.log('Bot online and ready.');
});
botClient.on('message', msg => {
if ((!msg.content.startsWith(CONFIG.prefix) && !msg.content.startsWith(CONFIG.devPrefix))
|| msg.author.bot) return;
const args = msg.content.slice(CONFIG.prefix.length).split(' ');
const commandName = args.shift().toLowerCase();
//If the command doesn't exist
if (!botClient.commands.has(commandName)){
msg.reply("That command does not exist. Do a.commands for a list of all commands");
return;
}
const command = botClient.commands.get(commandName);
try {
command.execute(msg, args);
} catch (error) {
console.error(error);
console.log('Error when trying to get and execute a command.');
msg.reply('There was an error trying to execute that command.');
}
});
Thanks
require('test.js').prefixType?const { prefixType } = require('test')require(`./commands/${file}`);const { prefixType } = require(filePath)will work.