I’m relatively new to JavaScript and in the process of creating my first Discord bot. Initially, everything functioned well with all my code in one file. However, I encountered issues after splitting it up using a command handler.
The challenge I’m facing is that I need certain commands to work without requiring a prefix. For instance, when users type “how are you doing,” I’d like the bot to respond with “doing great” without needing a “!” in front. This worked fine when everything was in my main file using straightforward if statements, but now that I moved commands into separate files, this functionality has stopped working.
Commands that use the prefix system still work correctly, but those meant to function without a prefix are not activating from their respective files.
Here’s what my setup looks like:
main.js
const Discord = require('discord.js');
const fs = require('fs');
const bot = new Discord.Client({ disableMentions: 'everyone' });
bot.config = require('./config/settings');
bot.commands = new Discord.Collection();
fs.readdirSync('./handlers').forEach(folder => {
const commandFiles = fs.readdirSync(`./handlers/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const cmd = require(`./handlers/${folder}/${file}`);
console.log(`Loaded command: ${file}`);
bot.commands.set(cmd.name.toLowerCase(), cmd);
};
});
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
console.log(`Loading event: ${file}`);
const eventHandler = require(`./events/${file}`);
bot.on(file.split(".")[0], eventHandler.bind(null, bot));
};
bot.login(bot.config.discord.token);
Working command (image.js):
module.exports = {
name: 'image',
category: 'media',
run(bot, message, args) {
var totalImages = 25;
var randomImg = Math.floor(Math.random() * (totalImages - 1 + 1) + 1);
message.channel.send({files: ["./images/" + randomImg + ".jpg"]});
}
};
Non-working command (status.js):
module.exports = {
name: 'status',
category: 'basic',
run(bot, message, args) {
if(message.content.startsWith('how are you doing')){
message.channel.send('doing great!');
}
}
};
Is there a way to set up some commands to bypass the need for a prefix while maintaining a structured file organization?