{"id":28411166,"url":"https://github.com/dutakey/whatsmulti","last_synced_at":"2025-08-19T02:34:47.661Z","repository":{"id":274594858,"uuid":"890322402","full_name":"DutaKey/WhatsMulti","owner":"DutaKey","description":"Whatsapp Client With Multi Session","archived":false,"fork":false,"pushed_at":"2025-08-05T06:46:43.000Z","size":102,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-08-08T15:47:41.569Z","etag":null,"topics":["multi-session","npm-package","npmjs","wa-gateway","whatsapp","whatsapp-api","whatsapp-web"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DutaKey.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-11-18T11:26:46.000Z","updated_at":"2025-08-05T06:46:46.000Z","dependencies_parsed_at":"2025-01-28T09:21:57.626Z","dependency_job_id":"664c4aeb-27ed-4bdf-8eee-7123bbd14b54","html_url":"https://github.com/DutaKey/WhatsMulti","commit_stats":null,"previous_names":["dutakey/whatsmulti"],"tags_count":11,"template":false,"template_full_name":null,"purl":"pkg:github/DutaKey/WhatsMulti","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DutaKey%2FWhatsMulti","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DutaKey%2FWhatsMulti/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DutaKey%2FWhatsMulti/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DutaKey%2FWhatsMulti/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DutaKey","download_url":"https://codeload.github.com/DutaKey/WhatsMulti/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DutaKey%2FWhatsMulti/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":271090487,"owners_count":24697613,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-19T02:00:09.176Z","response_time":63,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["multi-session","npm-package","npmjs","wa-gateway","whatsapp","whatsapp-api","whatsapp-web"],"created_at":"2025-06-02T14:11:25.446Z","updated_at":"2025-08-19T02:34:47.653Z","avatar_url":"https://github.com/DutaKey.png","language":"TypeScript","readme":"# @Dutakey/WhatsMulti\n\n![NPM Downloads](https://img.shields.io/npm/dw/%40dutakey%2Fwhatsmulti?label=npm\u0026color=%23CB3837)\n![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/dutakey/whatsmulti)\n\n## 📌 Overview\n\n@Dutakey/WhatsMulti is a powerful wrapper for [@whiskeysockets/baileys](https://github.com/WhiskeySockets/Baileys), designed to efficiently manage multiple WhatsApp Web sessions. It offers advanced session handling, flexible event listeners, and various storage options, making it ideal for developers integrating WhatsApp into their applications.\n\n## 🚀 Installation\n\nInstall via npm:\n\n```sh\nnpm install @dutakey/whatsmulti\n```\n\nOr using yarn:\n\n```sh\nyarn add @dutakey/whatsmulti\n```\n\n## ✨ Key Features\n\n- **Seamless Multi-Session Management**: Effortlessly create, manage, and maintain multiple WhatsApp sessions.\n- **Flexible Storage Options**: Store sessions locally, in memory, or integrate with databases like MongoDB.\n- **Robust Event Handling**: Easily handle events across multiple sessions for real-time monitoring.\n- **QR Code Generation**: Automatically generate QR codes for session authentication.\n- **Message Sending**: Send various types of messages (text, images, etc.) across sessions.\n- **Session Lifecycle Management**: Start, stop, restart, and delete sessions programmatically.\n\n## 📋 Table of Contents\n\n- [Quick Start](#-quick-start)\n- [Configuration](#-configuration)\n- [API Reference](#-api-reference)\n- [Session Management](#-session-management)\n- [Event Handling](#-event-handling)\n- [Message Operations](#-message-operations)\n- [Storage Options](#-storage-options)\n- [Examples](#-examples)\n- [TypeScript Support](#-typescript-support)\n- [Contributing](#-contributing)\n- [License](#-license)\n\n## 🚀 Quick Start\n\n```typescript\nimport WhatsMulti from '@dutakey/whatsmulti';\n\nconst client = new WhatsMulti({\n    mongoUri: 'mongodb://localhost:27017/whatsmulti-db', // Optional\n    defaultConnectionType: 'local', // 'local' | 'mongodb' | 'memory'\n});\n\n// Create and start a session\nawait client.createSession('my-session', 'local', {\n    printQR: true, // Print QR code to console\n});\n\nawait client.startSession('my-session');\n\n// Listen for events\nclient.on('open', (_, { sessionId }) =\u003e {\n    console.log(`Session ${sessionId} is connected!`);\n});\n\nclient.on('messages.upsert', async (data, { sessionId }) =\u003e {\n    const message = data.messages[0];\n    console.log('New message:', message);\n});\n```\n\n## ⚙️ Configuration\n\n### Constructor Options\n\n```typescript\ninterface ConfigType {\n    defaultConnectionType?: 'local' | 'mongodb' | 'memory';\n    localConnectionPath?: string;\n    LoggerLevel?: 'silent' | 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';\n    BaileysLoggerLevel?: 'silent' | 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';\n    mongoUri?: string;\n}\n```\n\n### Socket Configuration\n\n```typescript\ninterface SockConfig {\n    disableQRRetry?: boolean;\n    qrMaxWaitMs?: number;\n    printQR?: boolean;\n    // ... other Baileys SocketConfig options\n}\n```\n\n## 📚 API Reference\n\n### WhatsMulti Class\n\n#### Constructor\n\n```typescript\nnew WhatsMulti(config?: ConfigType)\n```\n\n#### Methods\n\n##### Session Management\n\n```typescript\n// Create a new session\nawait createSession(\n    id: string,\n    connectionType: 'local' | 'mongodb' | 'memory' = 'local',\n    socketConfig?: Partial\u003cSockConfig\u003e\n): Promise\u003cvoid\u003e\n\n// Start a session\nawait startSession(id: string): Promise\u003cvoid\u003e\n\n// Stop a session\nawait stopSession(id: string): Promise\u003cvoid\u003e\n\n// Restart a session\nawait restartSession(id: string): Promise\u003cvoid\u003e\n\n// Delete a session\nawait deleteSession(id: string): Promise\u003cvoid\u003e\n\n// Logout a session\nawait logoutSession(id: string): Promise\u003cvoid\u003e\n\n// Get session information\nawait getSession(id: string): Promise\u003cSessionInstance | undefined\u003e\n\n// Get all sessions\nawait getSessions(): Promise\u003cSessionInstance[]\u003e\n\n// Get QR code for a session\nawait getQr(id: string): Promise\u003c{ image: string; qr: string } | undefined\u003e\n\n// Load existing sessions\nawait loadSessions(): Promise\u003cvoid\u003e\n```\n\n##### Message Operations\n\n```typescript\n// Send a message\nawait sendMessage(\n    sessionId: string,\n    recipient: string | MessageType,\n    message: MessageContentType,\n    options?: MessageOptionsType\n): Promise\u003cvoid\u003e\n```\n\n## 🔧 Session Management\n\n### Creating Sessions\n\nSessions can be created with different storage types:\n\n```typescript\n// Local storage (files)\nawait client.createSession('session-1', 'local');\n\n// MongoDB storage\nawait client.createSession('session-2', 'mongodb');\n\n// Memory storage (temporary)\nawait client.createSession('session-3', 'memory');\n```\n\n### Session Lifecycle\n\n```typescript\n// Create and start\nawait client.createSession('my-session', 'local', {\n    printQR: true,\n    qrMaxWaitMs: 60000,\n});\nawait client.startSession('my-session');\n\n// Stop temporarily\nawait client.stopSession('my-session');\n\n// Restart\nawait client.restartSession('my-session');\n\n// Logout and clean up\nawait client.logoutSession('my-session');\n\n// Completely remove\nawait client.deleteSession('my-session');\n```\n\n### Loading Existing Sessions\n\n```typescript\n// Load all previously created sessions\nawait client.loadSessions();\n```\n\n## 📡 Event Handling\n\nWhatsMulti extends EventEmitter and provides all Baileys events plus custom events:\n\n### Built-in Events\n\n```typescript\n// Connection events\nclient.on('open', (data, { sessionId, socket }) =\u003e {\n    console.log(`Session ${sessionId} connected`);\n});\n\nclient.on('close', (data, { sessionId }) =\u003e {\n    console.log(`Session ${sessionId} disconnected`);\n});\n\nclient.on('connecting', (data, { sessionId }) =\u003e {\n    console.log(`Session ${sessionId} is connecting...`);\n});\n\n// QR Code event\nclient.on('qr', (data, { sessionId }) =\u003e {\n    console.log(`QR Code for ${sessionId}:`, data.qr);\n    // data.image contains base64 image data\n});\n\n// Message events\nclient.on('messages.upsert', (data, { sessionId, socket }) =\u003e {\n    data.messages.forEach(message =\u003e {\n        console.log(`New message in ${sessionId}:`, message);\n    });\n});\n\n// Contact events\nclient.on('contacts.update', (contacts, { sessionId }) =\u003e {\n    console.log(`Contacts updated in ${sessionId}:`, contacts);\n});\n\n// Group events\nclient.on('groups.update', (groups, { sessionId }) =\u003e {\n    console.log(`Groups updated in ${sessionId}:`, groups);\n});\n```\n\n### Event Processing\n\nYou can also use the `process` method to handle all events in one place:\n\n```typescript\nclient.process((events, { sessionId, socket }) =\u003e {\n    if (events['messages.upsert']) {\n        // Handle messages\n    }\n    if (events.qr) {\n        // Handle QR code\n    }\n    // Handle other events...\n});\n```\n\n## 💬 Message Operations\n\n### Sending Messages\n\n```typescript\n// Text message\nawait client.sendMessage('session-1', '1234567890@s.whatsapp.net', {\n    text: 'Hello, World!'\n});\n\n// Reply to a message\nawait client.sendMessage('session-1', originalMessage, {\n    text: 'This is a reply'\n}, {\n    quoted: originalMessage\n});\n\n// Image message\nawait client.sendMessage('session-1', '1234567890@s.whatsapp.net', {\n    image: { url: 'https://example.com/image.jpg' },\n    caption: 'Check out this image!'\n});\n\n// Document message\nawait client.sendMessage('session-1', '1234567890@s.whatsapp.net', {\n    document: { url: 'https://example.com/document.pdf' },\n    fileName: 'document.pdf',\n    mimetype: 'application/pdf'\n});\n```\n\n### Message Types\n\nWhatsMulti supports all Baileys message types:\n- Text messages\n- Image messages\n- Video messages\n- Audio messages\n- Document messages\n- Sticker messages\n- Location messages\n- Contact messages\n- And more...\n\n## 💾 Storage Options\n\n### Local Storage\n\nSessions are stored as files in the local filesystem:\n\n```typescript\nconst client = new WhatsMulti({\n    localConnectionPath: './sessions', // Default: './whatsmulti_sessions'\n});\n\nawait client.createSession('my-session', 'local');\n```\n\n### MongoDB Storage\n\nSessions are stored in a MongoDB database:\n\n```typescript\nconst client = new WhatsMulti({\n    mongoUri: 'mongodb://localhost:27017/whatsmulti-db'\n});\n\nawait client.createSession('my-session', 'mongodb');\n```\n\n### Memory Storage\n\nSessions are stored in memory (lost on restart):\n\n```typescript\nawait client.createSession('my-session', 'memory');\n```\n\n## 📂 Examples\n\n### Basic Multi-Session Bot\n\n```typescript\nimport WhatsMulti from '@dutakey/whatsmulti';\n\nconst client = new WhatsMulti({\n    mongoUri: 'mongodb://localhost:27017/whatsmulti-db',\n});\n\n// Create multiple sessions\nawait client.createSession('business', 'mongodb', { printQR: true });\nawait client.createSession('personal', 'local', { printQR: true });\n\n// Start all sessions\nawait client.startSession('business');\nawait client.startSession('personal');\n\n// Handle messages across all sessions\nclient.on('messages.upsert', async (data, { sessionId }) =\u003e {\n    const msg = data.messages[0];\n    if (msg.key.fromMe) return;\n    \n    const text = msg.message?.conversation || '';\n    \n    if (text === 'ping') {\n        await client.sendMessage(sessionId, msg, {\n            text: `Pong from session: ${sessionId}`\n        });\n    }\n});\n```\n\n### Dynamic Session Management\n\n```typescript\nimport WhatsMulti from '@dutakey/whatsmulti';\n\nconst client = new WhatsMulti();\n\n// Load existing sessions on startup\nawait client.loadSessions();\n\nclient.on('messages.upsert', async (data, { sessionId }) =\u003e {\n    const msg = data.messages[0];\n    if (msg.key.fromMe) return;\n    \n    const text = msg.message?.conversation || '';\n    const [command, ...args] = text.split(' ');\n    \n    switch (command) {\n        case '/create':\n            const newSessionId = args[0] || `session-${Date.now()}`;\n            await client.createSession(newSessionId, 'local');\n            await client.startSession(newSessionId);\n            \n            client.sendMessage(sessionId, msg, {\n                text: `Created session: ${newSessionId}`\n            });\n            break;\n            \n        case '/list':\n            const sessions = await client.getSessions();\n            const sessionList = sessions.map(s =\u003e \n                `${s.id}: ${s.status} (${s.connectionType})`\n            ).join('\\n');\n            \n            client.sendMessage(sessionId, msg, {\n                text: `Active sessions:\\n${sessionList}`\n            });\n            break;\n            \n        case '/qr':\n            const targetSession = args[0] || sessionId;\n            const qrData = await client.getQr(targetSession);\n            \n            if (qrData) {\n                const buffer = Buffer.from(qrData.image.replace(/^data:image\\/png;base64,/, ''), 'base64');\n                client.sendMessage(sessionId, msg, {\n                    image: buffer,\n                    caption: `QR Code for session: ${targetSession}`\n                });\n            }\n            break;\n    }\n});\n```\n\n### Event Logging and Monitoring\n\n```typescript\nimport WhatsMulti from '@dutakey/whatsmulti';\n\nconst client = new WhatsMulti({\n    LoggerLevel: 'info',\n    BaileysLoggerLevel: 'error'\n});\n\n// Monitor all session events\nclient.process((events, { sessionId }) =\u003e {\n    Object.entries(events).forEach(([event, data]) =\u003e {\n        console.log(`[${sessionId}] ${event}:`, data);\n    });\n});\n\n// Specific event handlers\nclient.on('open', (_, { sessionId }) =\u003e {\n    console.log(`✅ Session ${sessionId} connected successfully`);\n});\n\nclient.on('close', (_, { sessionId }) =\u003e {\n    console.log(`❌ Session ${sessionId} disconnected`);\n});\n\nclient.on('qr', (data, { sessionId }) =\u003e {\n    console.log(`📱 QR Code generated for ${sessionId}`);\n    // Save QR code or send to admin\n});\n```\n\n## 🔷 TypeScript Support\n\nWhatsMulti is built with TypeScript and provides full type definitions:\n\n```typescript\nimport WhatsMulti, { \n    ConfigType, \n    SessionInstance, \n    ConnectionType,\n    MessageContentType,\n    EventMap \n} from '@dutakey/whatsmulti';\n\nconst config: ConfigType = {\n    defaultConnectionType: 'local',\n    LoggerLevel: 'info'\n};\n\nconst client = new WhatsMulti(config);\n\n// Type-safe event handling\nclient.on('messages.upsert', (data: EventMap['messages.upsert'], meta) =\u003e {\n    // data is properly typed\n    data.messages.forEach(message =\u003e {\n        // message is typed as WAMessage\n    });\n});\n```\n\n## 🔧 Advanced Configuration\n\n### Custom Logger Configuration\n\n```typescript\nconst client = new WhatsMulti({\n    LoggerLevel: 'debug', // WhatsMulti logs\n    BaileysLoggerLevel: 'error', // Baileys logs\n});\n```\n\n### MongoDB Connection Options\n\n```typescript\nconst client = new WhatsMulti({\n    mongoUri: 'mongodb://username:password@localhost:27017/whatsmulti-db?authSource=admin'\n});\n```\n\n### Socket Configuration\n\n```typescript\nawait client.createSession('my-session', 'local', {\n    printQR: false,\n    qrMaxWaitMs: 30000,\n    disableQRRetry: false,\n    // Any other Baileys SocketConfig options\n    browser: ['WhatsMulti', 'Chrome', '1.0.0'],\n    connectTimeoutMs: 60000,\n});\n```\n\n## 🐛 Error Handling\n\n```typescript\ntry {\n    await client.createSession('my-session', 'local');\n    await client.startSession('my-session');\n} catch (error) {\n    if (error.message === 'Session exists') {\n        console.log('Session already exists');\n    } else if (error.message === 'Invalid session id') {\n        console.log('Invalid session ID format');\n    } else {\n        console.error('Unexpected error:', error);\n    }\n}\n\n// Handle connection errors\nclient.on('close', async (data, { sessionId }) =\u003e {\n    console.log(`Session ${sessionId} disconnected, attempting to reconnect...`);\n    try {\n        await client.restartSession(sessionId);\n    } catch (error) {\n        console.error(`Failed to restart session ${sessionId}:`, error);\n    }\n});\n```\n\n## 📋 Session ID Requirements\n\nSession IDs must follow these rules:\n- Only alphanumeric characters, hyphens, and underscores\n- No spaces or special characters\n- Validated by regex: `/^(?:[\\w-]+)$/`\n\n```typescript\n// Valid session IDs\nawait client.createSession('my-session', 'local');\nawait client.createSession('session_1', 'local');\nawait client.createSession('business-bot', 'local');\n\n// Invalid session IDs (will throw error)\nawait client.createSession('my session', 'local'); // spaces not allowed\nawait client.createSession('session@123', 'local'); // @ not allowed\n```\n\n## 🎯 Contributing\n\nContributions are welcome! If you find a bug, have feature suggestions, or want to improve the project, feel free to open an issue or submit a pull request.\n\n### Development Setup\n\n1. Clone the repository\n2. Install dependencies: `npm install`\n3. Build the project: `npm run build`\n4. Run linting: `npm run lint`\n5. Run the example: `npm run example`\n\n## 📄 License\n\nThis project is licensed under **MIT**, allowing free use, modification, and distribution.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdutakey%2Fwhatsmulti","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdutakey%2Fwhatsmulti","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdutakey%2Fwhatsmulti/lists"}