SMD HOST SYSTEM CMD

How to Create a Command System in WhatsApp Bot

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.

What is a Command System?

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.

Step 1: Create Commands Folder

Create a folder named commands. Each command will have its own file.

Step 2: Example Command File

// commands/menu.js
module.exports = {
  name: "menu",
  execute: async (sock, msg) => {
    await sock.sendMessage(msg.key.remoteJid, { text: "This is menu command" });
  }
}

Step 3: Load Commands in index.js

const fs = require('fs');
const commands = new Map();

fs.readdirSync('./commands').forEach(file => {
  const cmd = require(`./commands/${file}`);
  commands.set(cmd.name, cmd);
});

Step 4: Listen for Commands

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);
    }
  }
});

Advantages of Command Handler

Conclusion

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.