As your WhatsApp bot grows, adding features directly inside one file becomes messy. Commands start mixing with each other and maintaining the bot becomes difficult. This is where a proper command handler system helps you organize your bot like a professional developer.
A command system allows users to interact with your bot using specific keywords like !menu, !help, or !owner. Each command performs a separate function and keeps your code clean.
Create a folder named commands. Each command will have its own file.
// commands/menu.js
module.exports = {
name: "menu",
execute: async (sock, msg) => {
await sock.sendMessage(msg.key.remoteJid, { text: "This is menu command" });
}
}
const fs = require('fs');
const commands = new Map();
fs.readdirSync('./commands').forEach(file => {
const cmd = require(`./commands/${file}`);
commands.set(cmd.name, cmd);
});
sock.ev.on('messages.upsert', async ({ messages }) => {
const msg = messages[0];
const text = msg.message.conversation || '';
if(text.startsWith('!')){
const commandName = text.slice(1).split(' ')[0];
if(commands.has(commandName)){
commands.get(commandName).execute(sock, msg);
}
}
});
A proper command system transforms your WhatsApp bot from a simple script into a structured application. This method is used by advanced bot developers to manage large bots easily.