### Initialize and Start WhatsApp Bot (JavaScript) Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Initializes the WhatsApp Bot, starts the connection process displaying a QR code for authentication, and retrieves the bot's status. Requires the 'baileys' library. Handles graceful shutdown. ```javascript const WhatsAppBot = require('./src/index'); const bot = new WhatsAppBot(); // Start the bot - displays QR code for authentication await bot.start(); // Bot status includes connection state, config, and user info const status = bot.getStatus(); console.log(status); // Output: // { // isRunning: true, // whatsapp: { isConnected: true, isAuthenticated: true, user: { name: 'Bot', phone: '1234567890' } }, // config: { name: 'WhatsApp Bot', version: '1.0.0', database: './database/whatsapp-bot.db', server: '0.0.0.0:3000' } // } // Graceful shutdown await bot.stop(); ``` -------------------------------- ### Run Project Tests and Development Mode (Bash) Source: https://github.com/bamit99/whatsapp-bot/blob/master/README.md Provides commands for managing the project's development lifecycle. 'npm test' executes the test suite, while 'npm run dev' starts the application in development mode, typically with auto-restarting capabilities. ```bash # Run tests npm test # Development mode with auto-restart npm run dev ``` -------------------------------- ### Manage Bot with npm Commands (Bash) Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Provides essential npm commands for managing the WhatsApp Bot project. Includes initializing the database, starting the bot in production mode, and running in development mode with auto-restart. ```bash # Initialize the database first npm run init-db # Start the bot npm start # Development mode with auto-restart npm run dev ``` -------------------------------- ### GET /api/triggers Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Lists all active automated response triggers configured in the bot. Requires Basic Authentication. ```APIDOC ## GET /api/triggers ### Description Lists all active automated response triggers configured in the bot. Requires Basic Authentication. ### Method GET ### Endpoint /api/triggers ### Parameters #### Query Parameters None #### Headers - **Authorization** (string) - Required - Basic Auth token (e.g., `Basic base64EncodedCredentials`) ### Request Example ```bash curl -X GET http://localhost:3000/api/triggers \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" ``` ### Response #### Success Response (200) - Returns an array of trigger objects. - **id** (integer) - Unique identifier for the trigger. - **keyword** (string) - The keyword or pattern that activates the trigger. - **response** (string) - The automated response message. - **match_type** (string) - The type of matching used ('exact', 'contains', 'regex'). - **case_sensitive** (integer) - 0 for case-insensitive, 1 for case-sensitive. - **is_active** (integer) - 1 if the trigger is active, 0 otherwise. #### Response Example ```json [ { "id": 1, "keyword": "help", "response": "Available commands: help, info, stats", "match_type": "exact", "case_sensitive": 0, "is_active": 1 }, { "id": 2, "keyword": "support", "response": "Contact support@example.com", "match_type": "contains", "case_sensitive": 0, "is_active": 1 } ] ``` ``` -------------------------------- ### Get Users API Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Retrieves a list of users who have interacted with the bot. The list is sorted by the last seen timestamp. ```APIDOC ## GET /api/users ### Description Retrieves a list of users who have interacted with the bot, sorted by last seen timestamp. ### Method GET ### Endpoint /api/users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **id** (integer) - Unique identifier for the user. - **jid** (string) - WhatsApp ID of the user. - **name** (string) - Name of the user. - **phone** (string) - Phone number of the user. - **message_count** (integer) - Total number of messages exchanged with the user. - **last_seen** (string) - Timestamp of the last interaction with the user. #### Response Example ```json [ { "id": 1, "jid": "1234567890@s.whatsapp.net", "name": "John", "phone": "1234567890", "message_count": 45, "last_seen": "2024-01-15T10:30:00.000Z" }, { "id": 2, "jid": "0987654321@s.whatsapp.net", "name": "Jane", "phone": "0987654321", "message_count": 23, "last_seen": "2024-01-15T09:15:00.000Z" } ] ``` ``` -------------------------------- ### GET /api/status Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Retrieves the current bot status, including connection state, authentication status, and configuration details. Requires Basic Authentication. ```APIDOC ## GET /api/status ### Description Returns the current bot status including connection state, authentication status, and configuration details. Requires Basic Auth with admin credentials. ### Method GET ### Endpoint /api/status ### Parameters #### Query Parameters None #### Headers - **Authorization** (string) - Required - Basic Auth token (e.g., `Basic base64EncodedCredentials`) ### Request Example ```bash curl -X GET http://localhost:3000/api/status \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" ``` ### Response #### Success Response (200) - **isRunning** (boolean) - Indicates if the bot is currently running. - **whatsapp** (object) - WhatsApp connection and authentication status. - **isConnected** (boolean) - True if the WhatsApp connection is established. - **isAuthenticated** (boolean) - True if the user is authenticated with WhatsApp. - **user** (object) - Information about the authenticated user. - **name** (string) - The display name of the user. - **id** (string) - The WhatsApp JID of the user. - **phone** (string) - The phone number associated with the user. - **config** (object) - Bot configuration details. - **name** (string) - The name of the bot. - **version** (string) - The version of the bot. - **database** (string) - Path to the bot's database file. - **server** (string) - The server address and port the bot is running on. #### Response Example ```json { "isRunning": true, "whatsapp": { "isConnected": true, "isAuthenticated": true, "user": { "name": "Bot", "id": "1234567890@s.whatsapp.net", "phone": "1234567890" } }, "config": { "name": "WhatsApp Bot", "version": "1.0.0", "database": "./database/whatsapp-bot.db", "server": "0.0.0.0:3000" } } ``` ``` -------------------------------- ### Get Bot Statistics API (Bash) Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Shows how to fetch comprehensive statistics for the WhatsApp Bot using cURL. This includes total message counts, user and group numbers, active triggers, and daily analytics. Requires Basic Authentication. ```bash curl -X GET http://localhost:3000/api/stats \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" ``` -------------------------------- ### Initialize WebSocket and Fetch Status (JavaScript) Source: https://github.com/bamit99/whatsapp-bot/blob/master/public/index.html Initializes a WebSocket connection and defines functions to get and display the bot's status. It prompts for an admin password and uses it to authenticate API requests. The status is updated in real-time via WebSocket and also fetched initially via an API call. ```javascript const socket = io(); const adminPassword = prompt('Enter admin password:'); function getAuthHeader() { return 'Basic ' + btoa(`admin:${adminPassword}`); } socket.on('connect', () => { console.log('Connected to server'); }); socket.on('status', (status) => { const statusDiv = document.getElementById('status'); statusDiv.innerHTML = `
WhatsApp Connected: ${status.whatsapp.isConnected}
Bot Running: ${status.isRunning}
`; }); async function getStatus() { try { const response = await fetch('/api/status', { headers: { 'Authorization': getAuthHeader() } }); const status = await response.json(); const statusDiv = document.getElementById('status'); statusDiv.innerHTML = `WhatsApp Connected: ${status.whatsapp.isConnected}
Bot Running: ${status.isRunning}
`; } catch (error) { console.error('Error getting status:', error); const statusDiv = document.getElementById('status'); statusDiv.innerHTML = 'Error getting status. Check the console for details.'; } } if (adminPassword) { getStatus(); } ``` -------------------------------- ### Get Bot Status API (Bash) Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Demonstrates how to retrieve the current status of the WhatsApp Bot using a cURL command. This API endpoint requires Basic Authentication and returns details about the bot's connection, authentication, and configuration. ```bash curl -X GET http://localhost:3000/api/status \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" ``` -------------------------------- ### GET /api/stats Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Retrieves comprehensive bot statistics, including message counts, user and group data, and daily analytics. Requires Basic Authentication. ```APIDOC ## GET /api/stats ### Description Retrieves comprehensive bot statistics including total messages, users, groups, active triggers, and today's analytics data. Requires Basic Authentication. ### Method GET ### Endpoint /api/stats ### Parameters #### Query Parameters None #### Headers - **Authorization** (string) - Required - Basic Auth token (e.g., `Basic base64EncodedCredentials`) ### Request Example ```bash curl -X GET http://localhost:3000/api/stats \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" ``` ### Response #### Success Response (200) - **total** (object) - Overall statistics. - **messages** (integer) - Total number of messages processed. - **users** (integer) - Total number of unique users interacted with. - **groups** (integer) - Total number of groups the bot is part of. - **triggers** (integer) - Total number of active automated response triggers. - **today** (object) - Statistics for the current day. - **total_messages** (integer) - Number of messages processed today. - **total_users** (integer) - Number of unique users interacted with today. - **active_groups** (integer) - Number of active groups today. - **spam_detected** (integer) - Number of spam incidents detected today. - **status** (object) - Current bot status (similar to `/api/status`). #### Response Example ```json { "total": { "messages": 1542, "users": 87, "groups": 12, "triggers": 5 }, "today": { "total_messages": 234, "total_users": 23, "active_groups": 8, "spam_detected": 3 }, "status": { "isRunning": true, ... } } ``` ``` -------------------------------- ### Get Messages API Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Retrieves recent messages from the database. An optional limit parameter can be used to control the number of messages returned. ```APIDOC ## GET /api/messages ### Description Retrieves recent messages from the database with optional limit parameter. ### Method GET ### Endpoint /api/messages ### Parameters #### Path Parameters None #### Query Parameters - **limit** (integer) - Optional - The maximum number of messages to retrieve. #### Request Body None ### Response #### Success Response (200) - **id** (integer) - Unique identifier for the message record. - **message_id** (string) - The unique ID of the WhatsApp message. - **jid** (string) - The WhatsApp ID of the chat (user or group). - **sender_jid** (string) - The WhatsApp ID of the message sender. - **message_type** (string) - The type of the message (e.g., 'text', 'image'). - **content** (string) - The content of the message. - **timestamp** (string) - The timestamp when the message was sent. - **is_group** (integer) - Indicates if the message was sent in a group (1) or not (0). #### Response Example ```json [ { "id": 1, "message_id": "ABC123", "jid": "1234567890@s.whatsapp.net", "sender_jid": "1234567890@s.whatsapp.net", "message_type": "text", "content": "Hello", "timestamp": "2024-01-15T10:30:00.000Z", "is_group": 0 } ] ``` ``` -------------------------------- ### Retrieve Messages via API Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Get recent messages from the database via the /api/messages endpoint. An optional 'limit' parameter can be provided to control the number of messages returned. Each message object contains details like ID, sender, content, and timestamp. ```bash curl -X GET "http://localhost:3000/api/messages?limit=20" \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" ``` -------------------------------- ### Project Structure Overview (Bash) Source: https://github.com/bamit99/whatsapp-bot/blob/master/README.md Illustrates the directory and file structure of the WhatsApp bot project. This helps in understanding the organization of source code, configuration, database schema, scripts, and other project assets. ```bash whatsapp-bot/ ├── src/ │ ├── index.js # Main application entry │ ├── auth.js # WhatsApp authentication │ ├── whatsapp-handler.js # Connection management │ ├── message-handler.js # Message processing │ └── database.js # Database operations ├── config/ │ └── config.js # Configuration loader ├── database/ │ └── schema.sql # Database schema ├── scripts/ │ └── init-db.js # Database initialization ├── public/ # Web dashboard assets ├── logs/ # Log files ├── .env # Environment configuration └── package.json # Dependencies and scripts ``` -------------------------------- ### Connect and Listen to WebSocket Events (JavaScript) Source: https://github.com/bamit99/whatsapp-bot/blob/master/README.md Establishes a WebSocket connection to a local server and listens for incoming 'message' and 'stats' events. Logs received data to the console. Requires a WebSocket server running on 'http://localhost:3000'. ```javascript const socket = io('http://localhost:3000'); socket.on('message', (data) => { console.log('New message:', data); }); socket.on('stats', (data) => { console.log('Updated stats:', data); }); ``` -------------------------------- ### Accessing Configuration in JavaScript Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Loads and accesses configuration values defined in the .env file using the config module. Demonstrates how to retrieve settings for bot name, server port, database path, rate limit, spam threshold, and data collection. ```javascript const config = require('./config/config'); // Access configuration values console.log(config.bot.name); // 'My WhatsApp Bot' console.log(config.server.port); // 3000 console.log(config.database.path); // './database/whatsapp-bot.db' console.log(config.rateLimit.max); // 10 console.log(config.moderation.spamThreshold); // 5 console.log(config.dataCollection.collectUrls); // true ``` -------------------------------- ### Bot Configuration via .env File Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Defines bot settings using environment variables loaded from a .env file. Includes bot name, version, database path, server port, host, session directory, log level, log file, admin password, JWT secret, rate limiting parameters, and data collection flags. ```bash # .env file BOT_NAME=My WhatsApp Bot BOT_VERSION=1.0.0 DB_PATH=./database/whatsapp-bot.db PORT=3000 HOST=0.0.0.0 SESSION_DIR=./auth_info_baileys LOG_LEVEL=info LOG_FILE=./logs/bot.log ADMIN_PASSWORD=secure-password-here JWT_SECRET=your-jwt-secret RATE_LIMIT_WINDOW=60000 RATE_LIMIT_MAX=10 SPAM_THRESHOLD=5 SPAM_TIME_WINDOW=300000 COLLECT_PHONE_NUMBERS=true COLLECT_URLS=true COLLECT_MEDIA=true ``` -------------------------------- ### CLI Commands Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Manage and interact with the bot using various command-line interface commands. ```APIDOC ## CLI Commands ### Description The bot provides command-line interface for management operations without starting the full server. ### Available Commands - **help**: Shows all available commands. - **status**: Shows the current bot status. - **stats**: Shows the bot's statistics. - **add-trigger**: Adds a new message trigger. - `--match-type` (optional): Type of match ('contains', 'regex'). Defaults to 'exact'. - `--case-sensitive` (optional): Makes the trigger case-sensitive. - **remove-trigger**: Removes an existing trigger. - **send**: Sends a message directly to a user or group. ### Examples ```bash # Show help node src/index.js help # Show current bot status node src/index.js status # Show statistics node src/index.js stats # Add trigger with exact match (default) node src/index.js add-trigger "hello" "Hi there!" # Add trigger with contains match node src/index.js add-trigger "support" "Contact support@example.com" --match-type contains # Add trigger with regex match node src/index.js add-trigger "ticket.*" "Your ticket has been created" --match-type regex # Add case-sensitive trigger node src/index.js add-trigger "URGENT" "This is urgent!" --case-sensitive # Remove a trigger node src/index.js remove-trigger "hello" # Send a message directly node src/index.js send "1234567890@s.whatsapp.net" "Hello from CLI!" # Send message to group node src/index.js send "123456789-987654321@g.us" "Group announcement" ``` ``` -------------------------------- ### Create Bot Trigger API (Bash) Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Demonstrates creating new automated response triggers for the WhatsApp Bot via a POST request. Supports different match types (exact, contains, regex) and requires Basic Authentication and JSON content type. ```bash # Add exact match trigger curl -X POST http://localhost:3000/api/triggers \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" \ -H "Content-Type: application/json" \ -d '{ "keyword": "hello", "response": "Hi there! How can I help you?", "matchType": "exact", "caseSensitive": false }' # Add regex trigger curl -X POST http://localhost:3000/api/triggers \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" \ -H "Content-Type: application/json" \ -d '{ "keyword": "ticket.*", "response": "Your ticket has been created. Our team will respond shortly.", "matchType": "regex" }' ``` -------------------------------- ### CLI Commands for Bot Management Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Manage the WhatsApp bot using various command-line interface commands. Supports showing help, status, statistics, adding/removing triggers with different match types (exact, contains, regex, case-sensitive), and sending messages directly. ```bash # Show help node src/index.js help # Show current bot status node src/index.js status # Show statistics node src/index.js stats # Add trigger with exact match (default) node src/index.js add-trigger "hello" "Hi there!" # Add trigger with contains match node src/index.js add-trigger "support" "Contact support@example.com" --match-type contains # Add trigger with regex match node src/index.js add-trigger "ticket.*" "Your ticket has been created" --match-type regex # Add case-sensitive trigger node src/index.js add-trigger "URGENT" "This is urgent!" --case-sensitive # Remove a trigger node src/index.js remove-trigger "hello" # Send a message directly node src/index.js send "1234567890@s.whatsapp.net" "Hello from CLI!" # Send message to group node src/index.js send "123456789-987654321@g.us" "Group announcement" ``` -------------------------------- ### POST /api/triggers Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Creates a new automated response trigger. Supports exact match, contains, and regex match types. Requires Basic Authentication. ```APIDOC ## POST /api/triggers ### Description Creates a new automated response trigger. Supports exact match, contains, and regex match types. Requires Basic Authentication. ### Method POST ### Endpoint /api/triggers ### Parameters #### Query Parameters None #### Headers - **Authorization** (string) - Required - Basic Auth token (e.g., `Basic base64EncodedCredentials`) - **Content-Type** (string) - Required - `application/json` #### Request Body - **keyword** (string) - Required - The keyword or pattern for the trigger. - **response** (string) - Required - The automated response message. - **matchType** (string) - Optional - The type of matching ('exact', 'contains', 'regex'). Defaults to 'exact'. - **caseSensitive** (boolean) - Optional - True for case-sensitive matching, false otherwise. Defaults to false. ### Request Example ```bash # Add exact match trigger curl -X POST http://localhost:3000/api/triggers \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" \ -H "Content-Type: application/json" \ -d '{ "keyword": "hello", "response": "Hi there! How can I help you?", "matchType": "exact", "caseSensitive": false }' # Add regex trigger curl -X POST http://localhost:3000/api/triggers \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" \ -H "Content-Type: application/json" \ -d '{ "keyword": "ticket.*", "response": "Your ticket has been created. Our team will respond shortly.", "matchType": "regex" }' ``` ### Response #### Success Response (200 or 201) - **message** (string) - Confirmation message indicating successful trigger creation. #### Response Example ```json { "message": "Trigger added successfully" } ``` ``` -------------------------------- ### Real-time Events via WebSocket (Socket.IO) Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Connect to the bot's WebSocket server using Socket.IO for real-time updates. Handles bot status, statistics, and incoming messages. Includes event listeners for connection, status, stats, messages, errors, and disconnections. ```javascript const io = require('socket.io-client'); const socket = io('http://localhost:3000'); // Receive initial status on connection socket.on('status', (status) => { console.log('Bot status:', status); // { isRunning: true, whatsapp: { isConnected: true, ... }, config: { ... } } }); // Request and receive stats updates socket.emit('get-stats'); socket.on('stats', (stats) => { console.log('Statistics:', stats); // { total: { messages: 1542, users: 87, ... }, today: { ... } } }); // Handle incoming messages broadcast socket.on('message', (data) => { console.log('New message received:', data); // { message_id: 'ABC123', sender_jid: '1234567890@s.whatsapp.net', content: 'Hello', ... } }); // Handle errors socket.on('error', (error) => { console.error('Socket error:', error.message); }); socket.on('disconnect', () => { console.log('Disconnected from bot'); }); ``` -------------------------------- ### WhatsApp Bot API Endpoints Source: https://github.com/bamit99/whatsapp-bot/blob/master/README.md This section details the available REST API endpoints for managing and interacting with the WhatsApp Bot. ```APIDOC ## GET /api/status ### Description Retrieves the current status of the WhatsApp bot. ### Method GET ### Endpoint /api/status ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - The current status of the bot (e.g., 'running', 'stopped'). #### Response Example ```json { "status": "running" } ``` --- ## GET /api/stats ### Description Retrieves statistics about the WhatsApp bot's activity. ### Method GET ### Endpoint /api/stats ### Parameters None ### Request Example None ### Response #### Success Response (200) - **total_messages_received** (integer) - Total number of messages received. - **total_messages_sent** (integer) - Total number of messages sent. - **active_users** (integer) - Number of active users. - **spam_detected** (integer) - Number of detected spam messages. #### Response Example ```json { "total_messages_received": 1500, "total_messages_sent": 1200, "active_users": 50, "spam_detected": 5 } ``` --- ## GET /api/triggers ### Description Retrieves a list of all configured triggers for automated responses. ### Method GET ### Endpoint /api/triggers ### Parameters None ### Request Example None ### Response #### Success Response (200) - **triggers** (array) - An array of trigger objects. - **id** (string) - The unique identifier for the trigger. - **keyword** (string) - The keyword or pattern that triggers the response. - **response** (string) - The automated response message. - **match_type** (string) - The type of match (e.g., 'exact', 'contains', 'regex'). #### Response Example ```json { "triggers": [ { "id": "trigger_1", "keyword": "help", "response": "Available commands: help, info, stats", "match_type": "exact" }, { "id": "trigger_2", "keyword": "support", "response": "Contact support@example.com", "match_type": "contains" } ] } ``` --- ## POST /api/triggers ### Description Adds a new trigger for automated responses. ### Method POST ### Endpoint /api/triggers ### Parameters #### Request Body - **keyword** (string) - Required - The keyword or pattern to trigger the response. - **response** (string) - Required - The automated response message. - **match_type** (string) - Optional - The type of match (e.g., 'exact', 'contains', 'regex'). Defaults to 'exact'. ### Request Example ```json { "keyword": "hello", "response": "Hi there!", "match_type": "exact" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the trigger was added. - **trigger_id** (string) - The ID of the newly created trigger. #### Response Example ```json { "message": "Trigger added successfully.", "trigger_id": "trigger_3" } ``` --- ## DELETE /api/triggers/:id ### Description Removes a specific trigger by its ID. ### Method DELETE ### Endpoint /api/triggers/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the trigger to remove. ### Request Example None (uses path parameter) ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the trigger was removed. #### Response Example ```json { "message": "Trigger removed successfully." } ``` --- ## GET /api/users ### Description Retrieves a list of users interacting with the bot. ### Method GET ### Endpoint /api/users ### Parameters None ### Request Example None ### Response #### Success Response (200) - **users** (array) - An array of user objects. - **id** (string) - The unique identifier for the user (e.g., phone number). - **first_seen** (string) - Timestamp when the user was first seen. - **last_seen** (string) - Timestamp when the user was last seen. - **message_count** (integer) - Total number of messages exchanged with the user. #### Response Example ```json { "users": [ { "id": "1234567890@s.whatsapp.net", "first_seen": "2023-10-27T10:00:00Z", "last_seen": "2023-10-27T12:30:00Z", "message_count": 25 } ] } ``` --- ## GET /api/messages ### Description Retrieves a list of recent messages handled by the bot. ### Method GET ### Endpoint /api/messages ### Parameters None ### Request Example None ### Response #### Success Response (200) - **messages** (array) - An array of message objects. - **id** (string) - The unique identifier for the message. - **from** (string) - The sender's ID. - **to** (string) - The recipient's ID. - **timestamp** (string) - The time the message was sent. - **body** (string) - The content of the message. - **type** (string) - The type of message (e.g., 'text', 'image', 'video'). #### Response Example ```json { "messages": [ { "id": "message_1", "from": "1234567890@s.whatsapp.net", "to": "bot_number@s.whatsapp.net", "timestamp": "2023-10-27T12:30:00Z", "body": "Hello bot!", "type": "text" } ] } ``` --- ## POST /api/send ### Description Sends a message to a specified WhatsApp user or group. ### Method POST ### Endpoint /api/send ### Parameters #### Request Body - **to** (string) - Required - The recipient's WhatsApp ID (e.g., '1234567890@s.whatsapp.net' or 'group_id@g.us'). - **message** (string) - Required - The content of the message to send. ### Request Example ```json { "to": "1234567890@s.whatsapp.net", "message": "This is a message sent via the API." } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the message was sent successfully. #### Response Example ```json { "message": "Message sent successfully to 1234567890@s.whatsapp.net" } ``` ``` -------------------------------- ### DatabaseManager Operations in JavaScript Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Manages SQLite database operations for users, messages, groups, triggers, analytics, and logging. Initializes the database, performs CRUD operations, and handles rate limiting and spam logging. Requires './src/database'. ```javascript const DatabaseManager = require('./src/database'); const db = new DatabaseManager(); await db.initialize(); // User operations await db.createUser({ jid: '1234567890@s.whatsapp.net', name: 'John', phone: '1234567890' }); const user = await db.getUser('1234567890@s.whatsapp.net'); await db.updateUserActivity('1234567890@s.whatsapp.net'); // Message operations await db.saveMessage({ message_id: 'MSG123', jid: '1234567890@s.whatsapp.net', sender_jid: '1234567890@s.whatsapp.net', message_type: 'text', content: 'Hello', timestamp: new Date().toISOString(), is_group: false }); const messages = await db.getMessages('1234567890@s.whatsapp.net', 50); // Trigger operations await db.addTrigger('help', 'Available commands: help, info', 'exact', false); const triggers = await db.getActiveTriggers(); await db.removeTrigger('help'); // Spam logging await db.logSpam('1234567890@s.whatsapp.net', 'MSG123', 'High message frequency', 'medium', 'warned'); const spamLogs = await db.getSpamLogs('1234567890@s.whatsapp.net', 10); // Rate limiting const rateCheck = await db.checkRateLimit('1234567890@s.whatsapp.net', 'message', 60000, 10); // { allowed: true, remaining: 9 } // Collected data await db.saveCollectedData('url', 'https://example.com', '1234567890@s.whatsapp.net', 'MSG123'); const urls = await db.getCollectedData('url', 100); // Analytics await db.updateAnalytics('2024-01-15', { total_messages: 234, total_users: 23, active_groups: 8, spam_detected: 3 }); // Logging await db.log('info', 'Bot started', { version: '1.0.0' }); const logs = await db.getLogs('error', 50); db.close(); ``` -------------------------------- ### Retrieve Users via API Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Fetch a list of users who have interacted with the bot using the /api/users endpoint. The response is sorted by the last seen timestamp and includes user details like ID, JID, name, message count, and last seen time. ```bash curl -X GET http://localhost:3000/api/users \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" ``` -------------------------------- ### WhatsAppHandler Message Sending in JavaScript Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Handles sending messages and managing WhatsApp connections. Initializes the handler, sends text or rich messages, retrieves group metadata, registers message and group update handlers, checks connection status, and allows logout. Requires './src/whatsapp-handler'. ```javascript const WhatsAppHandler = require('./src/whatsapp-handler'); const whatsapp = new WhatsAppHandler(); await whatsapp.initialize(); // Send text message await whatsapp.sendText('1234567890@s.whatsapp.net', 'Hello!'); // Send message with content object (for media, buttons, etc.) await whatsapp.sendMessage('1234567890@s.whatsapp.net', { text: 'Hello with options' }); // Get group metadata const groupInfo = await whatsapp.getGroupMetadata('123456789-987654321@g.us'); // { id: '123456789-987654321@g.us', subject: 'My Group', participants: [...], owner: '...@s.whatsapp.net' } // Register custom message handler whatsapp.onMessage(async (message, sock) => { console.log('Received message:', message); // Custom processing logic }); // Register group update handler whatsapp.onGroupUpdate(async (update, sock) => { console.log('Group update:', update); // Handle member joins/leaves, etc. }); // Check connection status const status = whatsapp.getStatus(); // { isConnected: true, isAuthenticated: true, user: { name: 'Bot', id: '...', phone: '...' } } // Logout and cleanup await whatsapp.logout(); ``` -------------------------------- ### List Bot Triggers API (Bash) Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Retrieves a list of all currently active automated response triggers configured in the WhatsApp Bot. This API endpoint requires Basic Authentication and returns trigger details like keyword, response, and match type. ```bash curl -X GET http://localhost:3000/api/triggers \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" ``` -------------------------------- ### Send Message via API (Individual/Group) Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Send messages to individual users or groups using the /api/send endpoint. Requires authentication and specifies the recipient's JID and message content. Supports both direct user JIDs and group JIDs. ```bash curl -X POST http://localhost:3000/api/send \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" \ -H "Content-Type: application/json" \ -d '{ "jid": "1234567890@s.whatsapp.net", "message": "Hello from the bot!" }' ``` ```bash curl -X POST http://localhost:3000/api/send \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" \ -H "Content-Type: application/json" \ -d '{ "jid": "123456789-987654321@g.us", "message": "Announcement: Meeting at 3 PM today." }' ``` -------------------------------- ### MessageHandler Processing Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Details on how the MessageHandler class processes incoming messages, including trigger checking and spam detection. ```APIDOC ## MessageHandler Processing ### Description The MessageHandler class processes all incoming messages, extracts data, checks triggers, and handles spam detection. ### Usage Initialize the `MessageHandler` with a `WhatsAppHandler` instance and then call its methods. ```javascript const MessageHandler = require('./src/message-handler'); const WhatsAppHandler = require('./src/whatsapp-handler'); const whatsapp = new WhatsAppHandler(); const messageHandler = new MessageHandler(whatsapp); await messageHandler.initialize(); // Add custom trigger programmatically await messageHandler.addTrigger('pricing', 'Check our pricing at https://example.com/pricing', 'contains', false); // Remove trigger await messageHandler.removeTrigger('pricing'); // The handler automatically processes messages when registered with WhatsApp ``` ### Message Data Structure ```json { "message_id": "ABC123", "jid": "1234567890@s.whatsapp.net", "sender_jid": "1234567890@s.whatsapp.net", "message_type": "text", // text, image, video, audio, document, sticker "content": "Hello world", "media_url": null, "media_type": null, "timestamp": "2024-01-15T10:30:00.000Z", "is_group": false, "group_jid": null, "reply_to": null, "is_forwarded": false } ``` ``` -------------------------------- ### WebSocket Real-time Events Source: https://context7.com/bamit99/whatsapp-bot/llms.txt The bot integrates with Socket.IO to provide real-time updates on its status, statistics, and incoming messages. ```APIDOC ## WebSocket Real-time Events ### Description The web server provides Socket.IO integration for real-time updates on bot status and statistics. ### Events - **status**: Emitted on connection, provides the current status of the bot. - **stats**: Emitted after requesting stats, provides bot statistics. - **message**: Emitted for every new incoming message. - **error**: Emitted when a socket error occurs. - **disconnect**: Emitted when the connection to the bot is lost. ### Client Actions - **get-stats**: Emit this event to request statistics updates. ### Example Usage (Client-side JavaScript) ```javascript const io = require('socket.io-client'); const socket = io('http://localhost:3000'); // Receive initial status on connection socket.on('status', (status) => { console.log('Bot status:', status); // { isRunning: true, whatsapp: { isConnected: true, ... }, config: { ... } } }); // Request and receive stats updates socket.emit('get-stats'); socket.on('stats', (stats) => { console.log('Statistics:', stats); // { total: { messages: 1542, users: 87, ... }, today: { ... } } }); // Handle incoming messages broadcast socket.on('message', (data) => { console.log('New message received:', data); // { message_id: 'ABC123', sender_jid: '1234567890@s.whatsapp.net', content: 'Hello', ... } }); // Handle errors socket.on('error', (error) => { console.error('Socket error:', error.message); }); socket.on('disconnect', () => { console.log('Disconnected from bot'); }); ``` ``` -------------------------------- ### Send Message API Source: https://context7.com/bamit99/whatsapp-bot/llms.txt This endpoint allows sending messages to individual users or groups. It requires authentication and a JSON payload specifying the recipient's JID and the message content. ```APIDOC ## POST /api/send ### Description Sends a message to a specified WhatsApp user (jid) or group. ### Method POST ### Endpoint /api/send ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **jid** (string) - Required - The WhatsApp ID of the recipient (user or group). - **message** (string) - Required - The content of the message to send. ### Request Example ```json { "jid": "1234567890@s.whatsapp.net", "message": "Hello from the bot!" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates that the message was sent successfully. #### Response Example ```json { "message": "Message sent successfully" } ``` ``` -------------------------------- ### MessageHandler Class for Message Processing Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Programmatically manage message handling and triggers using the MessageHandler class. Initialize the handler, add or remove custom triggers, and understand the structure of incoming message data. The handler automatically processes messages when integrated with the WhatsApp handler. ```javascript const MessageHandler = require('./src/message-handler'); const WhatsAppHandler = require('./src/whatsapp-handler'); const whatsapp = new WhatsAppHandler(); const messageHandler = new MessageHandler(whatsapp); await messageHandler.initialize(); // Add custom trigger programmatically await messageHandler.addTrigger('pricing', 'Check our pricing at https://example.com/pricing', 'contains', false); // Remove trigger await messageHandler.removeTrigger('pricing'); // The handler automatically processes messages when registered with WhatsApp // Message data structure: // { // message_id: 'ABC123', // jid: '1234567890@s.whatsapp.net', // sender_jid: '1234567890@s.whatsapp.net', // message_type: 'text', // text, image, video, audio, document, sticker // content: 'Hello world', // media_url: null, // media_type: null, // timestamp: '2024-01-15T10:30:00.000Z', // is_group: false, // group_jid: null, // reply_to: null, // is_forwarded: false // } ``` -------------------------------- ### POST /api/send Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Sends a text message to a specified WhatsApp JID (user or group). ```APIDOC ## POST /api/send ### Description Sends a text message to a specified WhatsApp JID (user or group). ### Method POST ### Endpoint /api/send ### Parameters #### Query Parameters None #### Headers - **Content-Type** (string) - Required - `application/json` #### Request Body - **jid** (string) - Required - The WhatsApp JID of the recipient (e.g., `1234567890@s.whatsapp.net` for a user, or `1234567890-1234567890@g.us` for a group). - **message** (string) - Required - The text message content to send. ### Request Example ```bash curl -X POST http://localhost:3000/api/send \ -H "Content-Type: application/json" \ -d '{ "jid": "1234567890@s.whatsapp.net", "message": "Hello from the bot!" }' ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the message was sent successfully. #### Response Example ```json { "message": "Message sent successfully to 1234567890@s.whatsapp.net" } ``` ``` -------------------------------- ### DELETE /api/triggers/:keyword Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Removes an existing automated response trigger by its keyword. Requires Basic Authentication. ```APIDOC ## DELETE /api/triggers/:keyword ### Description Removes an existing trigger by its keyword. Requires Basic Authentication. ### Method DELETE ### Endpoint /api/triggers/:keyword ### Parameters #### Path Parameters - **keyword** (string) - Required - The keyword of the trigger to remove. #### Query Parameters None #### Headers - **Authorization** (string) - Required - Basic Auth token (e.g., `Basic base64EncodedCredentials`) ### Request Example ```bash curl -X DELETE http://localhost:3000/api/triggers/hello \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" ``` ### Response #### Success Response (200 or 204) - **message** (string) - Confirmation message indicating successful trigger removal. #### Response Example ```json { "message": "Trigger removed successfully" } ``` ``` -------------------------------- ### Delete Bot Trigger API (Bash) Source: https://context7.com/bamit99/whatsapp-bot/llms.txt Shows how to remove an existing automated response trigger from the WhatsApp Bot using its keyword. This DELETE request requires Basic Authentication. ```bash curl -X DELETE http://localhost:3000/api/triggers/hello \ -H "Authorization: Basic $(echo -n 'admin:admin123' | base64)" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.