From aecbbdbee9a0afc89b3fe84ec3ba020e9073e5f2 Mon Sep 17 00:00:00 2001 From: "promptless[bot]" <179508745+promptless[bot]@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:11:11 +0000 Subject: [PATCH] Documentation updates from Promptless --- docs/docs/configuration/multiple-sessions.md | 20 +- docs/docs/get-started/multi-session.md | 425 +++++++++++ docs/docs/how-to/multi-session-api.md | 727 +++++++++++++++++++ docs/docs/how-to/use-a-proxy.md | 107 ++- docs/docs/intro.md | 5 +- 5 files changed, 1273 insertions(+), 11 deletions(-) create mode 100644 docs/docs/get-started/multi-session.md create mode 100644 docs/docs/how-to/multi-session-api.md diff --git a/docs/docs/configuration/multiple-sessions.md b/docs/docs/configuration/multiple-sessions.md index ed5443c523..42551a6e21 100644 --- a/docs/docs/configuration/multiple-sessions.md +++ b/docs/docs/configuration/multiple-sessions.md @@ -1,11 +1,29 @@ # Multiple Sessions +:::tip New Multi-Session Server Mode +For easier management of multiple sessions, check out the new [Multi-Session Mode](/docs/get-started/multi-session) which provides a dedicated server with REST API and web interface for managing multiple WhatsApp sessions. +::: + You can run multiple sessions of @open-wa/wa-automate in the same process. This allows you to do interesting things for example: 1. Design and run automated tests for you WA bot. 2. Connect two or more WA numbers to a single (or multiple) message handler(s) 3. Use one client to make sure another one is alive by pinging it. +## Approaches + +There are two main approaches for running multiple sessions: + +### 1. Multi-Session Server Mode (Recommended) +Use the dedicated multi-session server for easier management: +```bash +node bin/multi-session.js --port 8080 --max-sessions 10 +``` +See [Multi-Session Mode](/docs/get-started/multi-session) for complete documentation. + +### 2. Programmatic Multiple Sessions +Create multiple sessions in your own code as described below. + Please see demo/index.ts for a working example NOTE: DO NOT CREATE TWO SESSIONS WITH THE SAME SESSIONID. DO NOT ALLOW SPACES AS SESSION ID. @@ -67,4 +85,4 @@ sendText(sessionId, params){ } create().then(client => start); -``` +``` \ No newline at end of file diff --git a/docs/docs/get-started/multi-session.md b/docs/docs/get-started/multi-session.md new file mode 100644 index 0000000000..d7ed249e84 --- /dev/null +++ b/docs/docs/get-started/multi-session.md @@ -0,0 +1,425 @@ +# Multi-Session Mode + +Multi-Session Mode allows you to run multiple WhatsApp sessions simultaneously on a single server instance. Each session is independent and can connect to different WhatsApp accounts, making it ideal for managing multiple WhatsApp numbers or building multi-tenant applications. + +## Overview + +The multi-session server provides: +- **Multiple Independent Sessions**: Run multiple WhatsApp sessions simultaneously +- **REST API**: Complete API for session management and messaging +- **Web UI**: Browser-based interface for managing sessions +- **Session Persistence**: Sessions are automatically restored on server restart +- **Enhanced Proxy Support**: Per-session proxy configuration including SOCKS5 +- **Real-time Status**: Live session status monitoring and QR code generation + +## Quick Start + +### 1. Build the Project + +```bash +npm run build +``` + +### 2. Start Multi-Session Server + +```bash +# Start with default settings +node bin/multi-session.js + +# Or specify custom port and limits +node bin/multi-session.js --port 3000 --max-sessions 5 --use-chrome +``` + +### 3. Access the Web Interface + +Open your browser and navigate to: +- **Web UI**: `http://localhost:8080` (or your configured port) +- **API Documentation**: `http://localhost:8080/api-docs` +- **Server Info**: `http://localhost:8080/info` + +## Server Configuration + +### Command Line Options + +| Option | Description | Default | +|--------|-------------|---------| +| `--port ` | Server port | 8080 | +| `--host ` | Server host | 0.0.0.0 | +| `--max-sessions ` | Maximum concurrent sessions | 10 | +| `--use-chrome` | Use Chrome instead of Chromium | false | +| `--webhook-host ` | Public host for webhooks | localhost | + +### Example Configurations + +```bash +# Production setup with custom limits +node bin/multi-session.js --port 3000 --max-sessions 20 --host 0.0.0.0 + +# Development with Chrome +node bin/multi-session.js --port 8080 --use-chrome --max-sessions 5 + +# With webhook support +node bin/multi-session.js --webhook-host your-domain.com --port 3000 +``` + +## API Endpoints + +### Session Management + +#### Create New Session +```bash +curl -X POST http://localhost:8080/api/v1/sessions \ + -H "Content-Type: application/json" \ + -d '{ + "sessionId": "my-session-1", + "waitForQR": true, + "config": { + "multiDevice": true, + "headless": true + } + }' +``` + +#### Get All Sessions +```bash +curl http://localhost:8080/api/v1/sessions +``` + +#### Get Session Status +```bash +curl http://localhost:8080/api/v1/sessions/my-session-1/status +``` + +#### Get QR Code +```bash +# JSON response with base64 QR code +curl http://localhost:8080/api/v1/sessions/my-session-1/qr + +# Direct PNG image +curl http://localhost:8080/api/v1/sessions/my-session-1/qr/image +``` + +#### Remove Session +```bash +curl -X DELETE http://localhost:8080/api/v1/sessions/my-session-1 +``` + +### Messaging + +#### Send Text Message +```bash +curl -X POST http://localhost:8080/api/v1/sessions/my-session-1/send-text \ + -H "Content-Type: application/json" \ + -d '{ + "chatId": "1234567890@c.us", + "content": "Hello from multi-session!" + }' +``` + +#### Send Media +```bash +curl -X POST http://localhost:8080/api/v1/sessions/my-session-1/send-image \ + -H "Content-Type: application/json" \ + -d '{ + "chatId": "1234567890@c.us", + "data": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...", + "filename": "image.png", + "caption": "Sent via multi-session API" + }' +``` + +## Session Configuration + +### Basic Session Config +```json +{ + "sessionId": "my-session", + "config": { + "multiDevice": true, + "headless": true, + "qrTimeout": 120, + "authTimeout": 60 + } +} +``` + +### With Proxy Configuration +```json +{ + "sessionId": "proxy-session", + "config": { + "multiDevice": true, + "headless": true, + "proxyServerCredentials": { + "protocol": "socks5", + "address": "proxy.example.com:1080", + "username": "user", + "password": "pass" + } + } +} +``` + +### Advanced Configuration +```json +{ + "sessionId": "advanced-session", + "config": { + "multiDevice": true, + "headless": true, + "useChrome": true, + "chromiumArgs": ["--no-sandbox", "--disable-dev-shm-usage"], + "qrTimeout": 180, + "authTimeout": 90, + "restartOnCrash": true, + "killProcessOnBrowserClose": false + } +} +``` + +## Web Interface + +The multi-session server includes a built-in web interface accessible at `http://localhost:8080` that provides: + +### Features +- **Session Overview**: View all sessions and their status +- **QR Code Display**: Real-time QR code generation and display +- **Session Management**: Create, start, stop, and delete sessions +- **Live Status**: Real-time session status updates +- **Configuration**: Easy session configuration through forms +- **Logs**: View session logs and error messages + +### Usage +1. Open `http://localhost:8080` in your browser +2. Click "New Session" to create a session +3. Configure session settings (ID, proxy, etc.) +4. Click "Create" and scan the QR code with WhatsApp +5. Monitor session status in real-time + +## Session Persistence + +Sessions are automatically saved and restored: + +### Session Data Location +``` +./sessions/ +├── session-1/ +│ ├── config.json +│ └── session-data/ +├── session-2/ +│ ├── config.json +│ └── session-data/ +└── ... +``` + +### Automatic Restoration +- Sessions are restored on server restart +- Authentication data is preserved +- Configuration is maintained +- Failed sessions are marked for cleanup + +## Proxy Support + +Multi-session mode supports various proxy types: + +### Supported Protocols +- HTTP/HTTPS +- SOCKS4 +- SOCKS5 +- SOCKS5H (hostname resolution through proxy) + +### Configuration Examples + +#### HTTP Proxy +```json +{ + "proxyServerCredentials": { + "protocol": "http", + "address": "proxy.example.com:8080", + "username": "user", + "password": "pass" + } +} +``` + +#### SOCKS5 Proxy +```json +{ + "proxyServerCredentials": { + "protocol": "socks5", + "address": "proxy.example.com:1080", + "username": "user", + "password": "pass" + } +} +``` + +#### Auto-Detection +```json +{ + "proxyServerCredentials": { + "address": "socks5://user:pass@proxy.example.com:1080" + } +} +``` + +## Best Practices + +### Resource Management +- Limit concurrent sessions based on server resources +- Monitor memory usage with multiple sessions +- Use headless mode for better performance +- Configure appropriate timeouts + +### Security +- Use authentication keys for API access +- Implement rate limiting for public APIs +- Secure proxy credentials +- Monitor session access logs + +### Scaling +- Start with fewer sessions and scale up +- Monitor CPU and memory usage +- Use load balancing for high availability +- Implement session health checks + +## Troubleshooting + +### Common Issues + +#### Session Won't Start +```bash +# Check session logs +curl http://localhost:8080/api/v1/sessions/my-session/logs + +# Verify configuration +curl http://localhost:8080/api/v1/sessions/my-session +``` + +#### QR Code Not Generated +- Ensure `waitForQR: true` in session creation +- Check if session is in correct state +- Verify browser process is running + +#### Proxy Connection Failed +- Test proxy connectivity separately +- Verify credentials and protocol +- Check firewall settings + +### Debug Mode +```bash +# Start with debug logging +DEBUG=* node bin/multi-session.js + +# Or specific debug categories +DEBUG=wa:* node bin/multi-session.js +``` + +## Migration from Single Session + +### From CLI Mode +```bash +# Old way +npx @open-wa/wa-automate --port 8080 + +# New multi-session way +node bin/multi-session.js --port 8080 +``` + +### From Custom Code +```javascript +// Old single session +const { create } = require('@open-wa/wa-automate'); +const client = await create({ sessionId: 'session1' }); + +// New multi-session API +const response = await fetch('http://localhost:8080/api/v1/sessions', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + sessionId: 'session1', + waitForQR: true, + config: { multiDevice: true, headless: true } + }) +}); +``` + +## Examples + +### Node.js Client +```javascript +const axios = require('axios'); + +class MultiSessionClient { + constructor(baseURL = 'http://localhost:8080') { + this.api = axios.create({ baseURL: `${baseURL}/api/v1` }); + } + + async createSession(sessionId, config = {}) { + const response = await this.api.post('/sessions', { + sessionId, + waitForQR: true, + config: { multiDevice: true, headless: true, ...config } + }); + return response.data; + } + + async sendMessage(sessionId, chatId, content) { + const response = await this.api.post(`/sessions/${sessionId}/send-text`, { + chatId, + content + }); + return response.data; + } + + async getSessionStatus(sessionId) { + const response = await this.api.get(`/sessions/${sessionId}/status`); + return response.data; + } +} + +// Usage +const client = new MultiSessionClient(); +await client.createSession('my-bot', { qrTimeout: 120 }); +await client.sendMessage('my-bot', '1234567890@c.us', 'Hello!'); +``` + +### Python Client +```python +import requests +import json + +class MultiSessionClient: + def __init__(self, base_url="http://localhost:8080"): + self.base_url = f"{base_url}/api/v1" + + def create_session(self, session_id, config=None): + if config is None: + config = {"multiDevice": True, "headless": True} + + response = requests.post(f"{self.base_url}/sessions", json={ + "sessionId": session_id, + "waitForQR": True, + "config": config + }) + return response.json() + + def send_message(self, session_id, chat_id, content): + response = requests.post(f"{self.base_url}/sessions/{session_id}/send-text", json={ + "chatId": chat_id, + "content": content + }) + return response.json() + +# Usage +client = MultiSessionClient() +client.create_session("my-bot", {"qrTimeout": 120}) +client.send_message("my-bot", "1234567890@c.us", "Hello from Python!") +``` + +## Next Steps + +- Explore the [API Reference](/docs/reference/api) for detailed endpoint documentation +- Learn about [Session Management](/docs/configuration/multiple-sessions) concepts +- Check out [Proxy Configuration](/docs/how-to/use-a-proxy) for advanced proxy setups +- See [Best Practices](/docs/advanced/best-practices) for production deployments \ No newline at end of file diff --git a/docs/docs/how-to/multi-session-api.md b/docs/docs/how-to/multi-session-api.md new file mode 100644 index 0000000000..21297103ab --- /dev/null +++ b/docs/docs/how-to/multi-session-api.md @@ -0,0 +1,727 @@ +# Multi-Session API Reference + +The Multi-Session API provides REST endpoints for managing multiple WhatsApp sessions programmatically. This comprehensive reference covers all available endpoints, request/response formats, and usage examples. + +## Base URL + +All API endpoints are relative to your multi-session server: +``` +http://localhost:8080/api/v1 +``` + +## Authentication + +Currently, the API uses basic authentication. You can secure your API by: +- Running behind a reverse proxy with authentication +- Using firewall rules to restrict access +- Implementing custom authentication middleware + +## Session Management Endpoints + +### Create Session + +Creates a new WhatsApp session with optional configuration. + +**Endpoint:** `POST /sessions` + +**Request Body:** +```json +{ + "sessionId": "string", + "waitForQR": boolean, + "config": { + "multiDevice": boolean, + "headless": boolean, + "qrTimeout": number, + "authTimeout": number, + "proxyServerCredentials": { + "protocol": "string", + "address": "string", + "username": "string", + "password": "string" + } + } +} +``` + +**Response:** +```json +{ + "success": true, + "message": "Session created successfully", + "data": { + "sessionId": "my-session-1", + "status": "initializing", + "createdAt": "2025-07-20T16:03:18Z", + "qrCode": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..." + } +} +``` + +**Example:** +```bash +curl -X POST http://localhost:8080/api/v1/sessions \ + -H "Content-Type: application/json" \ + -d '{ + "sessionId": "my-bot", + "waitForQR": true, + "config": { + "multiDevice": true, + "headless": true, + "qrTimeout": 120 + } + }' +``` + +### Get All Sessions + +Retrieves information about all active sessions. + +**Endpoint:** `GET /sessions` + +**Response:** +```json +{ + "success": true, + "data": [ + { + "sessionId": "session-1", + "status": "ready", + "createdAt": "2025-07-20T16:03:18Z", + "lastActivity": "2025-07-20T16:05:30Z" + }, + { + "sessionId": "session-2", + "status": "qr_ready", + "createdAt": "2025-07-20T16:04:22Z", + "lastActivity": "2025-07-20T16:04:22Z" + } + ] +} +``` + +### Get Session Info + +Retrieves detailed information about a specific session. + +**Endpoint:** `GET /sessions/{sessionId}` + +**Response:** +```json +{ + "success": true, + "data": { + "sessionId": "my-session", + "status": "ready", + "createdAt": "2025-07-20T16:03:18Z", + "lastActivity": "2025-07-20T16:05:30Z", + "config": { + "multiDevice": true, + "headless": true, + "qrTimeout": 120 + } + } +} +``` + +### Get Session Status + +Gets the current status of a session. + +**Endpoint:** `GET /sessions/{sessionId}/status` + +**Response:** +```json +{ + "success": true, + "data": { + "status": "ready", + "lastActivity": "2025-07-20T16:05:30Z" + } +} +``` + +**Status Values:** +- `initializing` - Session is being created +- `qr_ready` - QR code is available for scanning +- `authenticated` - QR code scanned, authenticating +- `ready` - Session is active and ready +- `failed` - Session failed to start +- `terminated` - Session has been stopped + +### Get QR Code + +Retrieves the QR code for session authentication. + +**Endpoint:** `GET /sessions/{sessionId}/qr` + +**Response:** +```json +{ + "success": true, + "data": { + "qrCode": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...", + "expiresAt": "2025-07-20T16:08:18Z" + } +} +``` + +### Get QR Code Image + +Returns the QR code as a PNG image directly. + +**Endpoint:** `GET /sessions/{sessionId}/qr/image` + +**Response:** PNG image data + +**Example:** +```bash +curl http://localhost:8080/api/v1/sessions/my-session/qr/image -o qr-code.png +``` + +### Remove Session + +Stops and removes a session. + +**Endpoint:** `DELETE /sessions/{sessionId}` + +**Response:** +```json +{ + "success": true, + "message": "Session removed successfully" +} +``` + +## Messaging Endpoints + +### Send Text Message + +Sends a text message to a chat. + +**Endpoint:** `POST /sessions/{sessionId}/send-text` + +**Request Body:** +```json +{ + "chatId": "1234567890@c.us", + "content": "Hello, World!", + "quotedMessageId": "optional-message-id" +} +``` + +**Response:** +```json +{ + "success": true, + "data": { + "messageId": "true_1234567890@c.us_ABC123", + "chatId": "1234567890@c.us", + "content": "Hello, World!", + "timestamp": 1642694598 + } +} +``` + +### Send Image + +Sends an image to a chat. + +**Endpoint:** `POST /sessions/{sessionId}/send-image` + +**Request Body:** +```json +{ + "chatId": "1234567890@c.us", + "data": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...", + "filename": "image.png", + "caption": "Optional caption", + "quotedMessageId": "optional-message-id" +} +``` + +### Send File + +Sends a file to a chat. + +**Endpoint:** `POST /sessions/{sessionId}/send-file` + +**Request Body:** +```json +{ + "chatId": "1234567890@c.us", + "data": "data:application/pdf;base64,JVBERi0xLjQKMSAwIG9iago8PA...", + "filename": "document.pdf", + "caption": "Optional caption" +} +``` + +### Send Audio + +Sends an audio file to a chat. + +**Endpoint:** `POST /sessions/{sessionId}/send-audio` + +**Request Body:** +```json +{ + "chatId": "1234567890@c.us", + "data": "data:audio/mp3;base64,SUQzAwAAAAABAAA...", + "filename": "audio.mp3" +} +``` + +## Chat Management Endpoints + +### Get All Chats + +Retrieves all chats for a session. + +**Endpoint:** `GET /sessions/{sessionId}/chats` + +**Response:** +```json +{ + "success": true, + "data": [ + { + "id": "1234567890@c.us", + "name": "John Doe", + "isGroup": false, + "unreadCount": 2, + "lastMessage": { + "body": "Hello!", + "timestamp": 1642694598 + } + } + ] +} +``` + +### Get Chat Messages + +Retrieves messages from a specific chat. + +**Endpoint:** `GET /sessions/{sessionId}/chats/{chatId}/messages` + +**Query Parameters:** +- `limit` (optional): Number of messages to retrieve (default: 50) +- `before` (optional): Message ID to paginate before + +**Response:** +```json +{ + "success": true, + "data": [ + { + "id": "true_1234567890@c.us_ABC123", + "body": "Hello!", + "fromMe": false, + "timestamp": 1642694598, + "author": "1234567890@c.us", + "type": "chat" + } + ] +} +``` + +## Contact Management Endpoints + +### Get All Contacts + +Retrieves all contacts for a session. + +**Endpoint:** `GET /sessions/{sessionId}/contacts` + +**Response:** +```json +{ + "success": true, + "data": [ + { + "id": "1234567890@c.us", + "name": "John Doe", + "pushname": "John", + "isMyContact": true, + "isWAContact": true + } + ] +} +``` + +### Get Contact Info + +Retrieves information about a specific contact. + +**Endpoint:** `GET /sessions/{sessionId}/contacts/{contactId}` + +**Response:** +```json +{ + "success": true, + "data": { + "id": "1234567890@c.us", + "name": "John Doe", + "pushname": "John", + "isMyContact": true, + "isWAContact": true, + "profilePicThumbObj": { + "eurl": "https://...", + "id": "...", + "img": "data:image/jpeg;base64,..." + } + } +} +``` + +## Group Management Endpoints + +### Create Group + +Creates a new WhatsApp group. + +**Endpoint:** `POST /sessions/{sessionId}/groups` + +**Request Body:** +```json +{ + "name": "My Group", + "participants": ["1234567890@c.us", "0987654321@c.us"], + "description": "Optional group description" +} +``` + +**Response:** +```json +{ + "success": true, + "data": { + "gid": "1234567890-1642694598@g.us", + "participants": [ + { + "id": "1234567890@c.us", + "status": 200 + } + ] + } +} +``` + +### Add Participants + +Adds participants to a group. + +**Endpoint:** `POST /sessions/{sessionId}/groups/{groupId}/participants` + +**Request Body:** +```json +{ + "participants": ["1234567890@c.us", "0987654321@c.us"] +} +``` + +### Remove Participants + +Removes participants from a group. + +**Endpoint:** `DELETE /sessions/{sessionId}/groups/{groupId}/participants` + +**Request Body:** +```json +{ + "participants": ["1234567890@c.us"] +} +``` + +## Webhook Endpoints + +### Register Webhook + +Registers a webhook URL for receiving events. + +**Endpoint:** `POST /sessions/{sessionId}/webhooks` + +**Request Body:** +```json +{ + "url": "https://your-server.com/webhook", + "events": ["message", "ack", "group_join"], + "headers": { + "Authorization": "Bearer your-token" + } +} +``` + +### List Webhooks + +Lists all registered webhooks for a session. + +**Endpoint:** `GET /sessions/{sessionId}/webhooks` + +### Remove Webhook + +Removes a registered webhook. + +**Endpoint:** `DELETE /sessions/{sessionId}/webhooks/{webhookId}` + +## Server Information Endpoints + +### Get Server Info + +Retrieves information about the multi-session server. + +**Endpoint:** `GET /info` + +**Response:** +```json +{ + "success": true, + "data": { + "version": "4.76.0", + "maxSessions": 10, + "activeSessions": 3, + "uptime": 3600, + "memory": { + "used": "256MB", + "total": "1GB" + } + } +} +``` + +### Health Check + +Checks the health status of the server. + +**Endpoint:** `GET /health` + +**Response:** +```json +{ + "success": true, + "data": { + "status": "healthy", + "timestamp": "2025-07-20T16:03:18Z", + "checks": { + "database": "ok", + "sessions": "ok", + "memory": "ok" + } + } +} +``` + +## Error Responses + +All endpoints return consistent error responses: + +```json +{ + "success": false, + "error": { + "code": "SESSION_NOT_FOUND", + "message": "Session with ID 'invalid-session' not found", + "details": {} + } +} +``` + +**Common Error Codes:** +- `SESSION_NOT_FOUND` - Session doesn't exist +- `SESSION_NOT_READY` - Session is not in ready state +- `INVALID_CHAT_ID` - Chat ID format is invalid +- `MAX_SESSIONS_REACHED` - Server has reached maximum session limit +- `VALIDATION_ERROR` - Request validation failed +- `INTERNAL_ERROR` - Server internal error + +## Rate Limiting + +The API implements rate limiting to prevent abuse: +- **Session Creation**: 5 requests per minute +- **Messaging**: 30 requests per minute per session +- **General API**: 100 requests per minute + +Rate limit headers are included in responses: +``` +X-RateLimit-Limit: 30 +X-RateLimit-Remaining: 29 +X-RateLimit-Reset: 1642694658 +``` + +## WebSocket Events + +For real-time updates, connect to the WebSocket endpoint: + +**Endpoint:** `ws://localhost:8080/ws/{sessionId}` + +**Event Types:** +- `qr` - New QR code generated +- `authenticated` - Session authenticated +- `ready` - Session ready +- `message` - New message received +- `ack` - Message acknowledgment +- `disconnected` - Session disconnected + +**Example Event:** +```json +{ + "event": "message", + "sessionId": "my-session", + "data": { + "id": "true_1234567890@c.us_ABC123", + "body": "Hello!", + "from": "1234567890@c.us", + "timestamp": 1642694598 + } +} +``` + +## SDK Examples + +### JavaScript/Node.js + +```javascript +class MultiSessionClient { + constructor(baseURL = 'http://localhost:8080') { + this.baseURL = `${baseURL}/api/v1`; + } + + async createSession(sessionId, config = {}) { + const response = await fetch(`${this.baseURL}/sessions`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + sessionId, + waitForQR: true, + config: { multiDevice: true, headless: true, ...config } + }) + }); + return response.json(); + } + + async sendMessage(sessionId, chatId, content) { + const response = await fetch(`${this.baseURL}/sessions/${sessionId}/send-text`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ chatId, content }) + }); + return response.json(); + } + + async getChats(sessionId) { + const response = await fetch(`${this.baseURL}/sessions/${sessionId}/chats`); + return response.json(); + } +} + +// Usage +const client = new MultiSessionClient(); +await client.createSession('my-bot'); +await client.sendMessage('my-bot', '1234567890@c.us', 'Hello!'); +const chats = await client.getChats('my-bot'); +``` + +### Python + +```python +import requests +import json + +class MultiSessionClient: + def __init__(self, base_url="http://localhost:8080"): + self.base_url = f"{base_url}/api/v1" + + def create_session(self, session_id, config=None): + if config is None: + config = {"multiDevice": True, "headless": True} + + response = requests.post(f"{self.base_url}/sessions", json={ + "sessionId": session_id, + "waitForQR": True, + "config": config + }) + return response.json() + + def send_message(self, session_id, chat_id, content): + response = requests.post(f"{self.base_url}/sessions/{session_id}/send-text", json={ + "chatId": chat_id, + "content": content + }) + return response.json() + + def get_chats(self, session_id): + response = requests.get(f"{self.base_url}/sessions/{session_id}/chats") + return response.json() + +# Usage +client = MultiSessionClient() +client.create_session("my-bot") +client.send_message("my-bot", "1234567890@c.us", "Hello!") +chats = client.get_chats("my-bot") +``` + +## Best Practices + +### Session Management +- Use descriptive session IDs +- Monitor session status regularly +- Implement proper error handling +- Clean up unused sessions + +### Message Handling +- Validate chat IDs before sending +- Handle rate limiting gracefully +- Use appropriate message types +- Implement retry logic for failed messages + +### Security +- Secure your API endpoints +- Validate all input data +- Use HTTPS in production +- Implement proper authentication + +### Performance +- Limit concurrent sessions based on resources +- Use webhooks for real-time events +- Implement proper caching +- Monitor memory usage + +## Migration Guide + +### From Single Session CLI +```bash +# Old way +npx @open-wa/wa-automate --port 8080 + +# New multi-session way +node bin/multi-session.js --port 8080 +``` + +### From Custom Code +```javascript +// Old single session +const { create } = require('@open-wa/wa-automate'); +const client = await create({ sessionId: 'session1' }); +client.onMessage(message => console.log(message)); + +// New multi-session API +const response = await fetch('http://localhost:8080/api/v1/sessions', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + sessionId: 'session1', + waitForQR: true, + config: { multiDevice: true, headless: true } + }) +}); + +// Use webhooks for message handling +await fetch('http://localhost:8080/api/v1/sessions/session1/webhooks', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + url: 'https://your-server.com/webhook', + events: ['message'] + }) +}); +``` \ No newline at end of file diff --git a/docs/docs/how-to/use-a-proxy.md b/docs/docs/how-to/use-a-proxy.md index 2b5b94d3e7..c0f469ab74 100644 --- a/docs/docs/how-to/use-a-proxy.md +++ b/docs/docs/how-to/use-a-proxy.md @@ -1,18 +1,89 @@ # Proxying your session -It is extremely simple to use a proxy with @open-wa. Once you have your proxy protocol, address, port, username and password you just need to set the [[proxyServerCredentials]] and @open-wa will connect your session via the proxy. For example, if your proxy details are: +It is extremely simple to use a proxy with @open-wa. Once you have your proxy protocol, address, port, username and password you just need to set the [[proxyServerCredentials]] and @open-wa will connect your session via the proxy. -```text -//this is dummy data +## Supported Proxy Types -protocol: http -address: proxyaddress.abc -port: 1234 -username: open-wa -password: antidote +@open-wa supports multiple proxy protocols: +- **HTTP/HTTPS**: Standard HTTP proxies +- **SOCKS4**: SOCKS version 4 proxies +- **SOCKS5**: SOCKS version 5 proxies (recommended for better security) +- **SOCKS5H**: SOCKS5 with hostname resolution through proxy + +## Configuration Examples + +### HTTP Proxy +```javascript +create({ + proxyServerCredentials: { + protocol: 'http', + address: 'proxyaddress.abc:1234', + username: 'open-wa', + password: 'antidote' + } +}).then(client => start(client)); +``` + +### SOCKS5 Proxy (Recommended) +```javascript +create({ + proxyServerCredentials: { + protocol: 'socks5', + address: 'proxyaddress.abc:1080', + username: 'open-wa', + password: 'antidote' + } +}).then(client => start(client)); ``` -then your config will look something like this: +### Auto-Detection from URL +You can also specify the full proxy URL and the protocol will be auto-detected: + +```javascript +create({ + proxyServerCredentials: { + address: 'socks5://open-wa:antidote@proxyaddress.abc:1080' + } +}).then(client => start(client)); +``` + +### Without Authentication +For proxies that don't require authentication: + +```javascript +create({ + proxyServerCredentials: { + protocol: 'socks5', + address: 'proxyaddress.abc:1080' + } +}).then(client => start(client)); +``` + +## Multi-Session Proxy Configuration + +In [Multi-Session Mode](/docs/get-started/multi-session), each session can have its own proxy configuration: + +```bash +curl -X POST http://localhost:8080/api/v1/sessions \ + -H "Content-Type: application/json" \ + -d '{ + "sessionId": "proxy-session", + "config": { + "multiDevice": true, + "headless": true, + "proxyServerCredentials": { + "protocol": "socks5", + "address": "proxy.example.com:1080", + "username": "user", + "password": "pass" + } + } + }' +``` + +## Legacy Format (Still Supported) + +The original format is still supported for backward compatibility: ```javascript create({ @@ -23,3 +94,21 @@ create({ } }).then(client => start(client)); ``` + +## Troubleshooting + +### Connection Issues +- Verify proxy credentials and address +- Test proxy connectivity outside of @open-wa +- Check firewall settings +- Try different proxy protocols (SOCKS5 is often more reliable) + +### Performance Issues +- SOCKS5 generally provides better performance than HTTP proxies +- Consider proxy server location relative to WhatsApp servers +- Monitor proxy server load and bandwidth + +### Authentication Errors +- Double-check username and password +- Some proxies may require specific authentication methods +- Try connecting without authentication first to isolate issues \ No newline at end of file diff --git a/docs/docs/intro.md b/docs/docs/intro.md index b9baf12604..19c0f76990 100644 --- a/docs/docs/intro.md +++ b/docs/docs/intro.md @@ -14,6 +14,9 @@ There are multiple ways to run this library: - [npx](/docs/get-started/quick-run) - [Docker](/docs/get-started/docker) +- Multi-Session Server + - [Multi-Session Mode](/docs/get-started/multi-session) - Run multiple WhatsApp sessions with REST API and web interface + - Your own custom code - [Locally](/docs/get-started/installation) - - [Socketed](/docs/get-started/socketmode) + - [Socketed](/docs/get-started/socketmode) \ No newline at end of file