Overview
Adding a new command to the WhatsApp Assistant Bot involves three main steps:- Create a command handler that implements the
CommandHandlerinterface - Register the command in the command registry
- (Optional) Create a service if the command requires database operations
Command Handler Interface
All commands must implement theCommandHandler interface defined in src/types/commands.ts:
Creating a Command Handler
// src/handlers/commands/GreetHandler.ts
import { CommandHandler, CommandContext } from '../../types/commands.js';
export const GreetHandler: CommandHandler = {
name: 'greet',
description: 'Send a personalized greeting',
usage: '!greet [name]',
examples: [
'!greet',
'!greet John',
'!greet Alice'
],
execute: async (context: CommandContext) => {
const { socket, chat, sender, args } = context;
const name = args.length > 0 ? args.join(' ') : 'there';
const greeting = `👋 Hello, ${name}! How can I help you today?`;
await socket.sendMessage(chat, { text: greeting });
}
};
import { GreetHandler } from './GreetHandler.js';
// Add to exports
export { GreetHandler } from './GreetHandler.js';
// Add to the commandHandlers Map
export const commandHandlers: Map<string, CommandHandler> = new Map([
['notify', NotifyHandler],
['todo', TodoHandler],
['note', NoteHandler],
['timer', TimerHandler],
['help', HelpHandler],
['sticker', StickerHandler],
['spotify', SpotifyHandler],
['greet', GreetHandler], // Add your command here
]);
Real-World Examples
Example 1: Simple Command (Note Handler)
The Note handler demonstrates subcommands and basic service integration:- Argument validation
- Subcommand routing with switch statement
- Service layer for database operations
- Error handling with user feedback
- Formatting output for readability
Example 2: Complex Command (Todo Handler)
The Todo handler shows more advanced patterns:- Batch operations (comma-separated input)
- Parallel database operations with
Promise.all - Conditional response formatting
- Input sanitization and validation
Example 3: Parsing and Validation (Notify Handler)
The Notify handler demonstrates custom parsing logic:- Custom argument parsing (last arg as time)
- Regular expression pattern matching
- Helper functions for complex logic
- Date/time manipulation with moment.js
Best Practices
1. Input Validation
Always validate user input before processing:2. Error Handling
Wrap command logic in try-catch blocks:3. User Feedback
Provide clear, helpful feedback:4. Use Services for Business Logic
Keep handlers focused on user interaction:5. Support Multiple Aliases
Register multiple names for the same handler:Common Patterns
Subcommand Router
Index-Based Selection
Formatting Lists
Testing Your Command
Next Steps
- Learn about the Service Layer for database operations
- Review the System Architecture for overall design
- Check existing handlers in
src/handlers/commands/for more examples