Skip to content

Self-improving AI Employees for everyone

feat: Add WhatsApp newsletter channel support across all 3 WhatsApp nodes

trohitg2913a47d8689
diff --git a/CLAUDE.md b/CLAUDE.md
index 6a12e91f..5132f4f4 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -369,7 +369,7 @@ class CacheEntry(SQLModel, table=True):
## Codebase Summary
- **Hybrid architecture**: Node.js + Python + React TypeScript
- **89 implemented workflow nodes** with clean service separation (6 AI models + 3 AI agents/memory + 13 specialized agents + 1 skill + 4 dedicated tools + 3 search + 16 Android + 3 WhatsApp + 4 Twitter + 2 Telegram + 2 Social + 3 Location + 3 Code + 6 Utility + 6 Document + 2 Chat + 2 Scheduler + 2 Workflow + 7 Google Workspace + 1 Apify)
-- **WebSocket-First Architecture**: WebSocket as primary frontend-backend communication (119 message handlers)
+- **WebSocket-First Architecture**: WebSocket as primary frontend-backend communication (120 message handlers)
- **Recent optimizations**: REST APIs replaced with WebSocket, AI endpoints migrated to Python, Android automation integrated
## Architecture Refactoring
@@ -522,7 +522,7 @@ React Flow edges use dynamic Dracula colors via `getEdgeStyles(theme.dracula)`:
### WebSocket-First Architecture
The project uses WebSocket as the primary communication method between frontend and backend, replacing most REST API calls:
- `src/contexts/WebSocketContext.tsx` - Central WebSocket context with request/response pattern
-- `server/routers/websocket.py` - WebSocket endpoint with 119 message handlers
+- `server/routers/websocket.py` - WebSocket endpoint with 120 message handlers
- `server/services/status_broadcaster.py` - Connection management and broadcasting
## Implemented Node Types
@@ -825,8 +825,8 @@ service_id_map = {
#### Dual-Purpose Tool Nodes (workflow node + AI tool)
Nodes that work BOTH as standalone workflow nodes AND as AI Agent tools. When connected to `input-tools`, the LLM fills the node's parameter schema.
-- **whatsappSend**: Send WhatsApp messages (text, media, location, contact). Full schema for all message types.
-- **whatsappDb**: Query WhatsApp database - chat history, contacts, groups with filtering and pagination.
+- **whatsappSend**: Send WhatsApp messages (text, media, location, contact) to contacts, groups, or newsletter channels. Full schema for all message types.
+- **whatsappDb**: Query WhatsApp database - chat history, contacts, groups, and newsletter channels with filtering and pagination.
- **pythonExecutor**: Execute Python code for calculations, data processing, and automation. Tool name: `python_code`. Available: math, json, datetime, Counter, defaultdict, random.
- **javascriptExecutor**: Execute JavaScript code via persistent Node.js server for calculations, data processing, and JSON manipulation. Tool name: `javascript_code`.
- **typescriptExecutor**: Execute TypeScript code via persistent Node.js server with type safety. Tool name: `typescript_code`.
@@ -892,15 +892,22 @@ Android device connection is configured via the Credentials Modal (Android panel
- **mediaControl**: Media playback control - volume control, playback control, play media files
### WhatsApp Nodes (3 nodes)
-- **whatsappSend**: **Dual-purpose node** - Send WhatsApp messages (text, image, video, audio, document, sticker, location, contact). Works as workflow node OR AI Agent tool. Group: `['whatsapp', 'tool']`. Recipient types: Self (connected phone), Phone Number, Group. Full parameter schema for message type, media URL, location coordinates, contact vCard.
-- **whatsappDb**: **Dual-purpose node** - Comprehensive WhatsApp database query node with 6 operations. Works as workflow node OR AI Agent tool. Group: `['whatsapp', 'tool']`. Operations:
+- **whatsappSend**: **Dual-purpose node** - Send WhatsApp messages (text, image, video, audio, document, sticker, location, contact) to contacts, groups, or newsletter channels. Works as workflow node OR AI Agent tool. Group: `['whatsapp', 'tool']`. Recipient types: Self (connected phone), Phone Number, Group, Channel (newsletter). Channel messages only support text, image, video, audio, document (NOT sticker, location, contact). Full parameter schema for message type, media URL, location coordinates, contact vCard, channel JID.
+- **whatsappDb**: **Dual-purpose node** - Comprehensive WhatsApp database query node with 13 operations. Works as workflow node OR AI Agent tool. Group: `['whatsapp', 'tool']`. Operations:
- `chat_history`: Retrieve messages from individual or group chats with filtering and pagination
- `search_groups`: Search groups by name
- `get_group_info`: Get group details with participant names and phone numbers
- `get_contact_info`: Get full contact info (name, phone, profile picture) for sending/replying
- `list_contacts`: List all contacts with saved names
- `check_contacts`: Check WhatsApp registration status for phone numbers
-- **whatsappReceive**: Event-driven trigger that waits for incoming WhatsApp messages with filters (message type, sender, group, keywords, forwarded status). Marked with `['whatsapp', 'trigger']` group for n8n-style trigger identification. Stores group/sender names alongside JID/phone for display persistence. The Go RPC resolves LIDs to phone numbers before sending events - `sender_phone` field is already resolved. Filter options: All Messages, From Self (notes to self chat only), From Any Contact (Non-Group), From Specific Contact, From Specific Group, Contains Keywords
+ - `list_channels`: List subscribed newsletter channels with optional server refresh
+ - `get_channel_info`: Get channel details (name, description, subscribers)
+ - `channel_messages`: Get channel message history with pagination
+ - `channel_stats`: Get channel subscriber/view statistics
+ - `channel_follow`: Follow/subscribe to a newsletter channel
+ - `channel_unfollow`: Unfollow/unsubscribe from a newsletter channel
+ - `channel_create`: Create a new newsletter channel
+- **whatsappReceive**: Event-driven trigger that waits for incoming WhatsApp messages with filters (message type, sender, group, channel, keywords, forwarded status). Marked with `['whatsapp', 'trigger']` group for n8n-style trigger identification. Stores group/sender names alongside JID/phone for display persistence. The Go RPC resolves LIDs to phone numbers before sending events - `sender_phone` field is already resolved. Filter options: All Messages, From Self (notes to self chat only), From Any Contact (Non-Group), From Specific Contact, From Specific Group, From Channel (Newsletter), Contains Keywords
### Social Nodes (2 nodes)
Unified social messaging nodes for multi-platform communication. Supports WhatsApp, Telegram, Discord, Slack, Signal, SMS, Webchat, Email, Matrix, Teams.
@@ -1341,7 +1348,7 @@ See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.
## Current Status
✅ **INodeProperties System**: Fully implemented with 89 functional node components
-✅ **WebSocket-First Architecture**: 119 message handlers replacing REST APIs
+✅ **WebSocket-First Architecture**: 120 message handlers replacing REST APIs
✅ **Code Editor**: Python, JavaScript, and TypeScript executors with syntax-highlighted editor (react-simple-code-editor + prismjs) and console output
✅ **Node.js Executor**: Persistent Node.js server (Express + tsx) for fast JS/TS execution, replacing subprocess spawning
✅ **Component Palette**: Emoji icons with distinct dracula-themed category colors, localStorage persistence for collapsed sections
@@ -1353,7 +1360,7 @@ See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.
✅ **Location Services**: Interactive map picker with coordinate handling, Google Maps API key fetched from backend credentials
✅ **Code Cleanup**: Dead code removed, unused files deleted
✅ **Process Management**: Robust stop scripts with duplicate process detection
-✅ **WhatsApp Integration**: Square node design with QR code viewer, group/sender name persistence, and proper error handling
+✅ **WhatsApp Integration**: Square node design with QR code viewer, group/sender name persistence, newsletter channel support (send, query, follow/unfollow, create), and proper error handling
✅ **Backend Stability**: Fixed dependency injection and error handling preventing crashes
✅ **Development Server**: Running at **http://localhost:3001** (frontend) and **http://localhost:3010** (backend)
✅ **WebSocket Integration**: Persistent WebSocket connections for remote Android devices with background tasks and message queue
@@ -4082,7 +4089,7 @@ export interface AndroidStatus {
## WhatsApp Integration
### Overview
-WhatsApp nodes use square design with integrated QR code viewing and proper error handling. The integration proxies all requests through the Python backend to the WhatsApp RPC service (default port 9400, configurable via `WHATSAPP_RPC_PORT` env var or `--port` CLI flag).
+WhatsApp nodes use square design with integrated QR code viewing and proper error handling. The integration proxies all requests through the Python backend to the WhatsApp RPC service (default port 9400, configurable via `WHATSAPP_RPC_PORT` env var or `--port` CLI flag). Supports individual chats, groups, and newsletter channels (sending, querying, follow/unfollow, create).
### Architecture
```
@@ -4401,6 +4408,10 @@ const sampleSchemas = {
sender_jid: 'string',
sender_phone: 'string', // Resolved phone number (Go RPC resolves LIDs)
sender_name: 'string'
+ },
+ newsletter_meta: {
+ edit_ts: 'number',
+ original_ts: 'number'
}
}
};
@@ -4710,7 +4721,7 @@ Updated `client_left` and presence handlers use `has_real_android_devices()` ins
| **Android** | `get_android_devices`, `execute_android_action`, `android_relay_connect`, `android_relay_disconnect`, `android_relay_reconnect` |
| **Maps** | `validate_maps_key` |
| **Apify** | `validate_apify_key` |
-| **WhatsApp** | `whatsapp_status`, `whatsapp_connected_phone`, `whatsapp_qr`, `whatsapp_send`, `whatsapp_start`, `whatsapp_restart`, `whatsapp_groups`, `whatsapp_group_info`, `whatsapp_chat_history`, `whatsapp_rate_limit_get`, `whatsapp_rate_limit_set`, `whatsapp_rate_limit_stats`, `whatsapp_rate_limit_unpause` |
+| **WhatsApp** | `whatsapp_status`, `whatsapp_connected_phone`, `whatsapp_qr`, `whatsapp_send`, `whatsapp_start`, `whatsapp_restart`, `whatsapp_groups`, `whatsapp_group_info`, `whatsapp_chat_history`, `whatsapp_newsletters`, `whatsapp_rate_limit_get`, `whatsapp_rate_limit_set`, `whatsapp_rate_limit_stats`, `whatsapp_rate_limit_unpause` |
| **Telegram** | `telegram_connect`, `telegram_disconnect`, `telegram_status`, `telegram_send`, `telegram_reconnect`, `telegram_get_me`, `telegram_get_chat` |
| **Workflow Storage** | `save_workflow`, `get_workflow`, `get_all_workflows`, `delete_workflow` |
| **Chat Messages** | `send_chat_message`, `get_chat_messages`, `clear_chat_messages`, `save_chat_message`, `get_chat_sessions` |
@@ -4880,7 +4891,7 @@ This function:
- **Performance**: Fast HMR updates and clean TypeScript compilation
- **AI Architecture**: 5-layer system with factory pattern and secure credential management
- **Android Architecture**: Factory-based node creation with ADB integration for device automation
-- **WebSocket-First Architecture**: 87 message handlers replace REST APIs for parameters, execution, API keys, Android, WhatsApp, and skill operations
+- **WebSocket-First Architecture**: 120 message handlers replace REST APIs for parameters, execution, API keys, Android, WhatsApp, and skill operations
- **WebSocket Hooks**: Dedicated React hooks (useWhatsApp, useExecution, useApiKeys, useAndroidOperations, useParameterPanel) for clean component integration
- **WebSocket Support**: Persistent remote Android device connections via WebSocket proxy with background tasks
- Connection stays alive across multiple API requests until switched to local ADB
@@ -4911,6 +4922,7 @@ This function:
- WebSocket handlers for status, QR code, send message, and start connection
- useWhatsApp hook provides clean React component integration
- Uses external npm package `whatsapp-rpc` with pre-built Go binaries
+ - Newsletter channels: send to channels (text/image/video/audio/document), query channel DB (list, info, messages, stats), follow/unfollow, create. Channel JID format: `<numeric_id>@newsletter`. Channel events dispatched via `event.newsletter_*` handlers.
- **Event-Driven Triggers**: Generic trigger node architecture with asyncio.Future
- `server/services/event_waiter.py` - Waiter registration, dispatch, cancellation
- TRIGGER_REGISTRY for extensible trigger types (WhatsApp, Webhook, future: Email, MQTT, Telegram)
diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsx
index eaac9700..f01869e8 100644
--- a/client/src/components/parameterPanel/InputSection.tsx
+++ b/client/src/components/parameterPanel/InputSection.tsx
@@ -204,6 +204,10 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
sender_jid: 'string',
sender_phone: 'string',
sender_name: 'string'
+ },
+ newsletter_meta: {
+ edit_ts: 'number',
+ original_ts: 'number'
}
},
whatsappDb: {
@@ -242,6 +246,9 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
is_business: 'boolean',
is_contact: 'boolean',
profile_pic: 'string',
+ // channel operations output
+ channels: [{ jid: 'string', name: 'string', subscriber_count: 'number' }],
+ channel_jid: 'string',
timestamp: 'string'
},
webhook: {
diff --git a/client/src/nodeDefinitions/whatsappNodes.ts b/client/src/nodeDefinitions/whatsappNodes.ts
index 83f79f17..7ebe8ccb 100644
--- a/client/src/nodeDefinitions/whatsappNodes.ts
+++ b/client/src/nodeDefinitions/whatsappNodes.ts
@@ -114,10 +114,11 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
options: [
{ name: 'Self (Connected Phone)', value: 'self' },
{ name: 'Phone Number', value: 'phone' },
- { name: 'Group', value: 'group' }
+ { name: 'Group', value: 'group' },
+ { name: 'Channel', value: 'channel' }
],
default: 'self',
- description: 'Send to self, individual, or group'
+ description: 'Send to self, individual, group, or channel (newsletter)'
},
{
displayName: 'Phone Number',
@@ -143,6 +144,18 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
show: { recipient_type: ['group'] }
}
},
+ {
+ displayName: 'Channel',
+ name: 'channel_jid',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: '120363198765432101@newsletter',
+ description: 'Newsletter JID (use Load button to select). Admin/owner role required to send.',
+ displayOptions: {
+ show: { recipient_type: ['channel'] }
+ }
+ },
// ===== MESSAGE TYPE =====
{
@@ -160,7 +173,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
{ name: 'Contact', value: 'contact' }
],
default: 'text',
- description: 'Type of message to send'
+ description: 'Type of message to send. Channels only support: text, image, video, audio, document.'
},
// ===== TEXT MESSAGE =====
@@ -434,6 +447,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
{ name: 'From Any Contact (Non-Group)', value: 'any_contact' },
{ name: 'From Specific Contact', value: 'contact' },
{ name: 'From Specific Group', value: 'group' },
+ { name: 'From Channel (Newsletter)', value: 'channel' },
{ name: 'Contains Keywords', value: 'keywords' }
],
default: 'all',
@@ -474,6 +488,18 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
placeholder: '1234567890',
description: 'Optional: Filter by sender phone number (use Load button to select from group members)'
},
+ {
+ displayName: 'Channel',
+ name: 'channel_jid',
+ type: 'string',
+ default: '',
+ required: true,
+ displayOptions: {
+ show: { filter: ['channel'] }
+ },
+ placeholder: '120363198765432101@newsletter',
+ description: 'Newsletter JID to receive messages from (use Load button to select)'
+ },
{
displayName: 'Keywords',
name: 'keywords',
@@ -495,7 +521,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
default: true,
description: 'Do not trigger on messages sent by this device',
displayOptions: {
- show: { filter: ['all', 'any_contact', 'contact', 'group', 'keywords'] }
+ show: { filter: ['all', 'any_contact', 'contact', 'group', 'channel', 'keywords'] }
}
},
{
@@ -581,6 +607,27 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
console.error('Error loading group members:', error);
return [{ name: 'Error loading members', value: '', description: 'Check WhatsApp connection' }];
}
+ },
+
+ async getWhatsAppChannels(): Promise<Array<{name: string, value: string, description?: string}>> {
+ try {
+ const response = await wsRequest('whatsapp_newsletters') as { success: boolean; channels?: Array<{ jid: string; name: string; subscriber_count?: number; role?: string }> };
+
+ if (response.success && response.channels) {
+ if (response.channels.length === 0) {
+ return [{ name: 'No channels found', value: '', description: 'Follow some channels first' }];
+ }
+ return response.channels.map((ch) => ({
+ name: ch.name || ch.jid,
+ value: ch.jid,
+ description: ch.subscriber_count ? `${ch.subscriber_count} subscribers` : undefined
+ }));
+ }
+ return [{ name: 'No channels found', value: '', description: 'Connect WhatsApp first' }];
+ } catch (error) {
+ console.error('Error loading WhatsApp channels:', error);
+ return [{ name: 'Error loading channels', value: '', description: 'Check WhatsApp connection' }];
+ }
}
}
}
@@ -629,7 +676,14 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
{ name: 'Get Group Info', value: 'get_group_info' },
{ name: 'Get Contact Info', value: 'get_contact_info' },
{ name: 'List Contacts', value: 'list_contacts' },
- { name: 'Check Contacts', value: 'check_contacts' }
+ { name: 'Check Contacts', value: 'check_contacts' },
+ { name: 'List Channels', value: 'list_channels' },
+ { name: 'Get Channel Info', value: 'get_channel_info' },
+ { name: 'Channel Messages', value: 'channel_messages' },
+ { name: 'Channel Stats', value: 'channel_stats' },
+ { name: 'Follow Channel', value: 'channel_follow' },
+ { name: 'Unfollow Channel', value: 'channel_unfollow' },
+ { name: 'Create Channel', value: 'channel_create' }
],
default: 'chat_history',
description: 'Operation to perform'
@@ -789,6 +843,76 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
displayOptions: {
show: { operation: ['check_contacts'] }
}
+ },
+
+ // ===== CHANNEL (NEWSLETTER) PARAMETERS =====
+ {
+ displayName: 'Channel JID or Invite',
+ name: 'channel_jid',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: '120363198765432101@newsletter or https://whatsapp.com/channel/...',
+ description: 'Newsletter JID or invite link (use Load button to select)',
+ displayOptions: {
+ show: { operation: ['get_channel_info', 'channel_messages', 'channel_stats', 'channel_follow', 'channel_unfollow'] }
+ }
+ },
+ {
+ displayName: 'Refresh Cache',
+ name: 'refresh',
+ type: 'boolean',
+ default: false,
+ description: 'Bypass 24h cache and fetch fresh data from WhatsApp servers',
+ displayOptions: {
+ show: { operation: ['list_channels', 'get_channel_info'] }
+ }
+ },
+ {
+ displayName: 'Message Count',
+ name: 'channel_count',
+ type: 'number',
+ default: 10,
+ typeOptions: { minValue: 1, maxValue: 100 },
+ description: 'Number of messages to retrieve',
+ displayOptions: {
+ show: { operation: ['channel_messages', 'channel_stats'] }
+ }
+ },
+ {
+ displayName: 'Before (Server ID)',
+ name: 'before_server_id',
+ type: 'number',
+ default: 0,
+ typeOptions: { minValue: 0 },
+ description: 'Pagination: get messages before this server ID (0 = latest)',
+ displayOptions: {
+ show: { operation: ['channel_messages'] }
+ }
+ },
+ {
+ displayName: 'Channel Name',
+ name: 'channel_name',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'My Channel',
+ description: 'Name for the new channel',
+ displayOptions: {
+ show: { operation: ['channel_create'] }
+ }
+ },
+ {
+ displayName: 'Channel Description',
+ name: 'channel_description',
+ type: 'string',
+ default: '',
+ typeOptions: { rows: 3 },
+ placeholder: 'A channel about...',
+ description: 'Optional description for the new channel',
+ displayOptions: {
+ show: { operation: ['channel_create'] }
+ }
}
],
methods: {
@@ -813,6 +937,27 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
console.error('Error loading WhatsApp groups:', error);
return [{ name: 'Error loading groups', value: '', description: 'Check WhatsApp connection' }];
}
+ },
+
+ async getWhatsAppChannels(): Promise<Array<{name: string, value: string, description?: string}>> {
+ try {
+ const response = await wsRequest('whatsapp_newsletters') as { success: boolean; channels?: Array<{ jid: string; name: string; subscriber_count?: number; role?: string }> };
+
+ if (response.success && response.channels) {
+ if (response.channels.length === 0) {
+ return [{ name: 'No channels found', value: '', description: 'Follow some channels first' }];
+ }
+ return response.channels.map((ch) => ({
+ name: ch.name || ch.jid,
+ value: ch.jid,
+ description: [ch.role, ch.subscriber_count ? `${ch.subscriber_count} subscribers` : ''].filter(Boolean).join(' - ') || undefined
+ }));
+ }
+ return [{ name: 'No channels found', value: '', description: 'Connect WhatsApp first' }];
+ } catch (error) {
+ console.error('Error loading WhatsApp channels:', error);
+ return [{ name: 'Error loading channels', value: '', description: 'Check WhatsApp connection' }];
+ }
}
}
}
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index b485cae9..ea6a33e8 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -1702,6 +1702,7 @@ from routers.whatsapp import (
handle_whatsapp_groups as _wa_groups,
handle_whatsapp_group_info as _wa_group_info,
handle_whatsapp_chat_history as _wa_chat_history,
+ handle_whatsapp_newsletters as _wa_newsletters,
whatsapp_rpc_call as _wa_rpc_call,
)
@@ -1736,6 +1737,11 @@ async def handle_whatsapp_groups(data: Dict[str, Any], websocket: WebSocket) ->
return await _wa_groups()
+async def handle_whatsapp_newsletters(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Get list of subscribed newsletter channels."""
+ return await _wa_newsletters()
+
+
async def handle_whatsapp_group_info(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
"""Get group participants with resolved phone numbers."""
group_id = data.get("group_id", "")
@@ -2943,6 +2949,7 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {
"whatsapp_start": handle_whatsapp_start,
"whatsapp_restart": handle_whatsapp_restart,
"whatsapp_groups": handle_whatsapp_groups,
+ "whatsapp_newsletters": handle_whatsapp_newsletters,
"whatsapp_group_info": handle_whatsapp_group_info,
"whatsapp_chat_history": handle_whatsapp_chat_history,
"whatsapp_rate_limit_get": handle_whatsapp_rate_limit_get,
diff --git a/server/routers/whatsapp.py b/server/routers/whatsapp.py
index c8f084b6..f62ea962 100644
--- a/server/routers/whatsapp.py
+++ b/server/routers/whatsapp.py
@@ -222,8 +222,21 @@ class RPCClient:
elif method == "event.message_received":
# Message received - broadcast as custom event for trigger nodes
+ # (includes newsletter messages with newsletter_meta field)
await broadcaster.send_custom_event("whatsapp_message_received", params)
+ elif method == "event.newsletter_join":
+ await broadcaster.send_custom_event("whatsapp_newsletter_join", params)
+
+ elif method == "event.newsletter_leave":
+ await broadcaster.send_custom_event("whatsapp_newsletter_leave", params)
+
+ elif method == "event.newsletter_mute_change":
+ await broadcaster.send_custom_event("whatsapp_newsletter_mute_change", params)
+
+ elif method == "event.newsletter_live_update":
+ await broadcaster.send_custom_event("whatsapp_newsletter_live_update", params)
+
# Forward to custom handler if set
if self._event_handler:
await self._event_handler(method, params)
@@ -449,9 +462,10 @@ async def handle_whatsapp_send(params: dict) -> dict:
Uses _send_lock to serialize sends - Go service processes sequentially.
Params from frontend node (snake_case):
- - recipient_type: 'self', 'phone', or 'group'
+ - recipient_type: 'self', 'phone', 'group', or 'channel'
- phone: recipient phone number (if recipient_type='phone')
- group_id: group JID (if recipient_type='group')
+ - channel_jid: newsletter JID (if recipient_type='channel')
- message_type: text, image, video, audio, document, sticker, location, contact
- message: text content (for text type)
- media_source: base64, file, url (for media types)
@@ -468,7 +482,18 @@ async def handle_whatsapp_send(params: dict) -> dict:
# Recipient (snake_case)
recipient_type = params.get("recipient_type", "self")
- if recipient_type == "group":
+ if recipient_type == "channel":
+ # Newsletter/channel send - uses newsletter_send RPC with group_id param
+ channel_jid = params.get("channel_jid")
+ if not channel_jid:
+ return {"success": False, "error": "channel_jid is required"}
+ # Validate channel-supported message types
+ msg_type = params.get("message_type", "text")
+ channel_types = {"text", "image", "video", "audio", "document"}
+ if msg_type not in channel_types:
+ return {"success": False, "error": f"Channels only support: {', '.join(sorted(channel_types))}. Got: {msg_type}"}
+ rpc_params["group_id"] = channel_jid # newsletter_send uses group_id for JID
+ elif recipient_type == "group":
group_id = params.get("group_id")
if not group_id:
return {"success": False, "error": "group_id is required"}
@@ -578,7 +603,9 @@ async def handle_whatsapp_send(params: dict) -> dict:
rpc_params["metadata"] = params["metadata"]
client = await get_client()
- result = await client.call("send", rpc_params)
+ # Use newsletter_send for channel recipients, regular send for others
+ rpc_method = "newsletter_send" if recipient_type == "channel" else "send"
+ result = await client.call(rpc_method, rpc_params)
return {
"success": True,
"message_id": result.get("message_id"),
@@ -830,3 +857,25 @@ async def whatsapp_rpc_call(method: str, params: dict = None) -> dict:
except Exception as e:
logger.error(f"WhatsApp RPC call '{method}' failed: {e}")
return {"success": False, "error": str(e)}
+
+
+async def handle_whatsapp_newsletters() -> dict:
+ """Get list of subscribed WhatsApp newsletter channels via RPC.
+
+ Used by WebSocket handler for loadOptions dropdown in whatsappDb/whatsappReceive nodes.
+
+ Returns:
+ Dict with channels list containing jid and name
+ """
+ try:
+ client = await get_client()
+ channels = await client.call("newsletters")
+
+ return {
+ "success": True,
+ "channels": channels or [],
+ "timestamp": time.time()
+ }
+ except Exception as e:
+ logger.error(f"WhatsApp newsletters fetch failed: {e}")
+ return {"success": False, "error": str(e), "channels": []}
diff --git a/server/services/ai.py b/server/services/ai.py
index e3758a60..59ca2789 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -2728,10 +2728,10 @@ class AIService:
# WhatsApp send schema (existing node used as tool)
if node_type == 'whatsappSend':
class WhatsAppSendSchema(BaseModel):
- """Send WhatsApp messages to contacts or groups."""
+ """Send WhatsApp messages to contacts, groups, or channels."""
recipient_type: str = Field(
default="phone",
- description="Send to: 'phone' for individual or 'group' for group chat"
+ description="Send to: 'phone' for individual, 'group' for group chat, or 'channel' for newsletter channel"
)
phone: Optional[str] = Field(
default=None,
@@ -2741,9 +2741,13 @@ class AIService:
default=None,
description="Group JID (e.g., [email protected]). Required for recipient_type='group'"
)
+ channel_jid: Optional[str] = Field(
+ default=None,
+ description="Newsletter JID (e.g., 120363198765432101@newsletter). Required for recipient_type='channel'. Only supports text, image, video, audio, document."
+ )
message_type: str = Field(
default="text",
- description="Message type: 'text', 'image', 'video', 'audio', 'document', 'sticker', 'location', 'contact'"
+ description="Message type: 'text', 'image', 'video', 'audio', 'document', 'sticker', 'location', 'contact'. Channels only support: text, image, video, audio, document."
)
message: Optional[str] = Field(
default=None,
@@ -2769,7 +2773,7 @@ class AIService:
# WhatsApp DB schema (existing node used as tool) - query contacts, groups, messages
if node_type == 'whatsappDb':
class WhatsAppDbSchema(BaseModel):
- """Query WhatsApp database - contacts, groups, messages.
+ """Query WhatsApp database - contacts, groups, messages, channels.
Operations:
- chat_history: Get messages from a chat (requires phone or group_id)
@@ -2778,10 +2782,17 @@ class AIService:
- get_contact_info: Get full contact info for sending/replying (requires phone)
- list_contacts: List contacts with saved names (optional query filter)
- check_contacts: Check WhatsApp registration (requires phones comma-separated)
+ - list_channels: List subscribed newsletter channels (optional refresh)
+ - get_channel_info: Get channel details (requires channel_jid)
+ - channel_messages: Get channel message history (requires channel_jid)
+ - channel_stats: Get channel subscriber/view stats (requires channel_jid)
+ - channel_follow: Follow/subscribe to a channel (requires channel_jid)
+ - channel_unfollow: Unfollow/unsubscribe from a channel (requires channel_jid)
+ - channel_create: Create a new newsletter channel (requires channel_name)
"""
operation: str = Field(
default="chat_history",
- description="Operation: 'chat_history', 'search_groups', 'get_group_info', 'get_contact_info', 'list_contacts', 'check_contacts'"
+ description="Operation: 'chat_history', 'search_groups', 'get_group_info', 'get_contact_info', 'list_contacts', 'check_contacts', 'list_channels', 'get_channel_info', 'channel_messages', 'channel_stats', 'channel_follow', 'channel_unfollow', 'channel_create'"
)
# For chat_history
chat_type: Optional[str] = Field(
@@ -2828,6 +2839,31 @@ class AIService:
default=None,
description="For get_group_info: max participants to return (1-100, default 50). Large groups may have hundreds of members."
)
+ # Channel (newsletter) operations
+ channel_jid: Optional[str] = Field(
+ default=None,
+ description="Newsletter JID (e.g., 120363198765432101@newsletter). Required for get_channel_info, channel_messages, channel_stats, channel_follow, channel_unfollow."
+ )
+ refresh: Optional[bool] = Field(
+ default=None,
+ description="For list_channels/get_channel_info: force refresh from server (default uses 24h cache)."
+ )
+ channel_count: Optional[int] = Field(
+ default=None,
+ description="For channel_messages/channel_stats: number of items to fetch (1-100, default 20 for messages, 10 for stats)."
+ )
+ before_server_id: Optional[int] = Field(
+ default=None,
+ description="For channel_messages: fetch messages before this server ID (pagination)."
+ )
+ channel_name: Optional[str] = Field(
+ default=None,
+ description="For channel_create: name of the new channel."
+ )
+ channel_description: Optional[str] = Field(
+ default=None,
+ description="For channel_create: description of the new channel."
+ )
return WhatsAppDbSchema
diff --git a/server/services/event_waiter.py b/server/services/event_waiter.py
index 680e9ae1..bc1b5814 100644
--- a/server/services/event_waiter.py
+++ b/server/services/event_waiter.py
@@ -247,6 +247,15 @@ def build_whatsapp_filter(params: Dict) -> Callable[[Dict], bool]:
if sender_number not in sender_phone:
return False
+ if sender_filter == 'channel':
+ # Only accept messages from newsletter channels (chat_id ends with @newsletter)
+ if not msg_chat_id.endswith('@newsletter'):
+ return False
+ # If specific channel JID provided, match exactly
+ channel_jid = params.get('channel_jid', '')
+ if channel_jid and msg_chat_id != channel_jid:
+ return False
+
if sender_filter == 'keywords':
text = (m.get('text') or '').lower()
if not any(kw in text for kw in keywords):
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index d3512d7b..d1abd77c 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -635,7 +635,7 @@ async def _execute_whatsapp_send(args: Dict[str, Any],
"""Send WhatsApp message with full message type support.
Supports all message types: text, image, video, audio, document, sticker, location, contact
- Recipients: phone number or group_id
+ Recipients: phone number, group_id, or channel_jid (newsletter)
Media sources: URL
Args:
@@ -652,6 +652,7 @@ async def _execute_whatsapp_send(args: Dict[str, Any],
'recipient_type': args.get('recipient_type', 'phone'),
'phone': args.get('phone', ''),
'group_id': args.get('group_id', ''),
+ 'channel_jid': args.get('channel_jid', ''),
'message_type': args.get('message_type', 'text'),
'message': args.get('message', ''),
'media_source': 'url' if args.get('media_url') else 'none',
@@ -673,6 +674,10 @@ async def _execute_whatsapp_send(args: Dict[str, Any],
return {"error": "Phone number is required for recipient_type='phone'"}
if recipient_type == 'group' and not parameters['group_id']:
return {"error": "Group ID is required for recipient_type='group'"}
+ if recipient_type == 'channel' and not parameters['channel_jid']:
+ return {"error": "Channel JID is required for recipient_type='channel'"}
+ if recipient_type == 'channel' and message_type not in ('text', 'image', 'video', 'audio', 'document'):
+ return {"error": f"Channels only support: text, image, video, audio, document. Got: {message_type}"}
if message_type == 'text' and not parameters['message']:
return {"error": "Message content is required for message_type='text'"}
if message_type in ('image', 'video', 'audio', 'document', 'sticker') and not parameters['media_url']:
@@ -682,7 +687,12 @@ async def _execute_whatsapp_send(args: Dict[str, Any],
if message_type == 'contact' and not parameters['vcard']:
return {"error": "vcard is required for message_type='contact'"}
- recipient = parameters['phone'] if recipient_type == 'phone' else parameters['group_id']
+ if recipient_type == 'channel':
+ recipient = parameters['channel_jid']
+ elif recipient_type == 'phone':
+ recipient = parameters['phone']
+ else:
+ recipient = parameters['group_id']
logger.info(f"[WhatsApp Tool] Sending {message_type} to {recipient[:15]}...")
try:
@@ -713,13 +723,20 @@ async def _execute_whatsapp_db(args: Dict[str, Any],
node_params: Dict[str, Any]) -> Dict[str, Any]:
"""Query WhatsApp database - contacts, groups, messages.
- Supports 6 operations:
+ Supports 13 operations:
- chat_history: Retrieve messages from a chat
- search_groups: Search groups by name
- get_group_info: Get group details with participant names
- get_contact_info: Get full contact info (for send/reply)
- list_contacts: List contacts with saved names
- check_contacts: Check WhatsApp registration status
+ - list_channels: List subscribed newsletter channels
+ - get_channel_info: Get channel details
+ - channel_messages: Get channel message history
+ - channel_stats: Get channel subscriber/view stats
+ - channel_follow: Follow/subscribe to a channel
+ - channel_unfollow: Unfollow/unsubscribe from a channel
+ - channel_create: Create a new newsletter channel
Args:
args: LLM-provided arguments matching WhatsAppDbSchema (snake_case)
@@ -781,6 +798,55 @@ async def _execute_whatsapp_db(args: Dict[str, Any],
return {"error": "phones (comma-separated) is required for check_contacts"}
parameters['phones'] = phones
+ elif operation == 'list_channels':
+ if args.get('refresh'):
+ parameters['refresh'] = True
+ parameters['limit'] = min(args.get('limit', 20), 50)
+
+ elif operation == 'get_channel_info':
+ channel_jid = args.get('channel_jid', '')
+ if not channel_jid:
+ return {"error": "channel_jid is required for get_channel_info"}
+ parameters['channel_jid'] = channel_jid
+ if args.get('refresh'):
+ parameters['refresh'] = True
+
+ elif operation == 'channel_messages':
+ channel_jid = args.get('channel_jid', '')
+ if not channel_jid:
+ return {"error": "channel_jid is required for channel_messages"}
+ parameters['channel_jid'] = channel_jid
+ parameters['channel_count'] = min(args.get('channel_count', 20), 100)
+ if args.get('before_server_id'):
+ parameters['before_server_id'] = args['before_server_id']
+
+ elif operation == 'channel_stats':
+ channel_jid = args.get('channel_jid', '')
+ if not channel_jid:
+ return {"error": "channel_jid is required for channel_stats"}
+ parameters['channel_jid'] = channel_jid
+ parameters['channel_count'] = min(args.get('channel_count', 10), 100)
+
+ elif operation == 'channel_follow':
+ channel_jid = args.get('channel_jid', '')
+ if not channel_jid:
+ return {"error": "channel_jid is required for channel_follow"}
+ parameters['channel_jid'] = channel_jid
+
+ elif operation == 'channel_unfollow':
+ channel_jid = args.get('channel_jid', '')
+ if not channel_jid:
+ return {"error": "channel_jid is required for channel_unfollow"}
+ parameters['channel_jid'] = channel_jid
+
+ elif operation == 'channel_create':
+ channel_name = args.get('channel_name', '')
+ if not channel_name:
+ return {"error": "channel_name is required for channel_create"}
+ parameters['channel_name'] = channel_name
+ if args.get('channel_description'):
+ parameters['channel_description'] = args['channel_description']
+
else:
return {"error": f"Unknown operation: {operation}"}
diff --git a/server/services/handlers/whatsapp.py b/server/services/handlers/whatsapp.py
index e6100d5f..da90cb77 100644
--- a/server/services/handlers/whatsapp.py
+++ b/server/services/handlers/whatsapp.py
@@ -17,7 +17,7 @@ async def handle_whatsapp_send(
"""Handle WhatsApp send message node via Go RPC service.
Supports all message types: text, image, video, audio, document, sticker, location, contact
- Recipients: phone number or group_id
+ Recipients: phone number, group_id, or channel_jid (newsletter)
Media sources: base64, file path, or URL
Args:
@@ -41,6 +41,14 @@ async def handle_whatsapp_send(
if recipient_type == 'self':
# Self will be resolved by the router using connected phone
recipient = 'self'
+ elif recipient_type == 'channel':
+ recipient = parameters.get('channel_jid')
+ if not recipient:
+ raise ValueError("Channel JID is required")
+ # Validate channel-supported message types
+ channel_types = {'text', 'image', 'video', 'audio', 'document'}
+ if message_type not in channel_types:
+ raise ValueError(f"Channels only support: {', '.join(sorted(channel_types))}. Got: {message_type}")
elif recipient_type == 'group':
recipient = parameters.get('group_id')
if not recipient:
@@ -135,6 +143,13 @@ async def handle_whatsapp_db(
- get_contact_info: Get full contact info (name, phone, photo)
- list_contacts: List contacts with saved names
- check_contacts: Check WhatsApp registration
+ - list_channels: List subscribed newsletter channels
+ - get_channel_info: Get channel details
+ - channel_messages: Get channel message history
+ - channel_stats: Get channel subscriber/view stats
+ - channel_follow: Follow/subscribe to a channel
+ - channel_unfollow: Unfollow/unsubscribe from a channel
+ - channel_create: Create a new newsletter channel
Args:
node_id: The node ID
@@ -166,6 +181,20 @@ async def handle_whatsapp_db(
return await _handle_list_contacts(node_id, parameters, start_time, whatsapp_rpc_call)
elif operation == 'check_contacts':
return await _handle_check_contacts(node_id, parameters, start_time, whatsapp_rpc_call)
+ elif operation == 'list_channels':
+ return await _handle_list_channels(node_id, parameters, start_time, whatsapp_rpc_call)
+ elif operation == 'get_channel_info':
+ return await _handle_get_channel_info(node_id, parameters, start_time, whatsapp_rpc_call)
+ elif operation == 'channel_messages':
+ return await _handle_channel_messages(node_id, parameters, start_time, whatsapp_rpc_call)
+ elif operation == 'channel_stats':
+ return await _handle_channel_stats(node_id, parameters, start_time, whatsapp_rpc_call)
+ elif operation == 'channel_follow':
+ return await _handle_channel_follow(node_id, parameters, start_time, whatsapp_rpc_call)
+ elif operation == 'channel_unfollow':
+ return await _handle_channel_unfollow(node_id, parameters, start_time, whatsapp_rpc_call)
+ elif operation == 'channel_create':
+ return await _handle_channel_create(node_id, parameters, start_time, whatsapp_rpc_call)
else:
raise ValueError(f"Unknown operation: {operation}")
@@ -429,3 +458,226 @@ async def _handle_check_contacts(node_id: str, parameters: Dict[str, Any], start
}
+async def _handle_list_channels(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:
+ """Handle list_channels operation - list subscribed newsletter channels."""
+ refresh = parameters.get('refresh', False)
+ limit = parameters.get('limit', 20)
+
+ rpc_params: Dict[str, Any] = {}
+ if refresh:
+ rpc_params['refresh'] = True
+
+ data = await rpc_call('newsletters', rpc_params)
+
+ if isinstance(data, dict) and not data.get('success', True):
+ raise Exception(data.get('error', 'Failed to list channels'))
+
+ channels = data if isinstance(data, list) else data.get('result', [])
+ total_found = len(channels)
+
+ # Return essential fields only
+ channels_limited = [
+ {"jid": c.get("jid", ""), "name": c.get("name", ""), "subscriber_count": c.get("subscriber_count", 0)}
+ for c in channels[:limit]
+ ]
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "whatsappDb",
+ "result": {
+ "operation": "list_channels",
+ "channels": channels_limited,
+ "total": total_found,
+ "returned": len(channels_limited),
+ "has_more": total_found > limit,
+ "hint": f"Showing {len(channels_limited)} of {total_found} channels." if total_found > limit else None,
+ "timestamp": datetime.now().isoformat()
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+
+async def _handle_get_channel_info(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:
+ """Handle get_channel_info operation - get channel details."""
+ channel_jid = parameters.get('channel_jid')
+ if not channel_jid:
+ raise ValueError("Channel JID is required")
+
+ rpc_params: Dict[str, Any] = {'jid': channel_jid}
+ if parameters.get('refresh'):
+ rpc_params['refresh'] = True
+
+ data = await rpc_call('newsletter_info', rpc_params)
+
+ if isinstance(data, dict) and not data.get('success', True):
+ raise Exception(data.get('error', 'Failed to get channel info'))
+
+ result = data if not isinstance(data, dict) or 'result' not in data else data.get('result', data)
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "whatsappDb",
+ "result": {
+ "operation": "get_channel_info",
+ **result,
+ "timestamp": datetime.now().isoformat()
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+
+async def _handle_channel_messages(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:
+ """Handle channel_messages operation - get channel message history."""
+ channel_jid = parameters.get('channel_jid')
+ if not channel_jid:
+ raise ValueError("Channel JID is required")
+
+ count = parameters.get('channel_count', 20)
+ rpc_params: Dict[str, Any] = {'jid': channel_jid, 'count': count}
+
+ before_server_id = parameters.get('before_server_id')
+ if before_server_id:
+ rpc_params['before_server_id'] = int(before_server_id)
+
+ data = await rpc_call('newsletter_messages', rpc_params)
+
+ if isinstance(data, dict) and not data.get('success', True):
+ raise Exception(data.get('error', 'Failed to get channel messages'))
+
+ messages = data if isinstance(data, list) else data.get('result', [])
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "whatsappDb",
+ "result": {
+ "operation": "channel_messages",
+ "messages": messages,
+ "count": len(messages),
+ "channel_jid": channel_jid,
+ "timestamp": datetime.now().isoformat()
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+
+async def _handle_channel_stats(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:
+ """Handle channel_stats operation - get channel subscriber/view stats."""
+ channel_jid = parameters.get('channel_jid')
+ if not channel_jid:
+ raise ValueError("Channel JID is required")
+
+ count = parameters.get('channel_count', 10)
+ rpc_params: Dict[str, Any] = {'jid': channel_jid, 'count': count}
+
+ data = await rpc_call('newsletter_stats', rpc_params)
+
+ if isinstance(data, dict) and not data.get('success', True):
+ raise Exception(data.get('error', 'Failed to get channel stats'))
+
+ result = data if not isinstance(data, dict) or 'result' not in data else data.get('result', data)
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "whatsappDb",
+ "result": {
+ "operation": "channel_stats",
+ **result,
+ "channel_jid": channel_jid,
+ "timestamp": datetime.now().isoformat()
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+
+async def _handle_channel_follow(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:
+ """Handle channel_follow operation - follow/subscribe to a channel."""
+ channel_jid = parameters.get('channel_jid')
+ if not channel_jid:
+ raise ValueError("Channel JID is required")
+
+ data = await rpc_call('newsletter_follow', {'jid': channel_jid})
+
+ if isinstance(data, dict) and not data.get('success', True):
+ raise Exception(data.get('error', 'Failed to follow channel'))
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "whatsappDb",
+ "result": {
+ "operation": "channel_follow",
+ "channel_jid": channel_jid,
+ "status": "followed",
+ "timestamp": datetime.now().isoformat()
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+
+async def _handle_channel_unfollow(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:
+ """Handle channel_unfollow operation - unfollow/unsubscribe from a channel."""
+ channel_jid = parameters.get('channel_jid')
+ if not channel_jid:
+ raise ValueError("Channel JID is required")
+
+ data = await rpc_call('newsletter_unfollow', {'jid': channel_jid})
+
+ if isinstance(data, dict) and not data.get('success', True):
+ raise Exception(data.get('error', 'Failed to unfollow channel'))
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "whatsappDb",
+ "result": {
+ "operation": "channel_unfollow",
+ "channel_jid": channel_jid,
+ "status": "unfollowed",
+ "timestamp": datetime.now().isoformat()
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+
+async def _handle_channel_create(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:
+ """Handle channel_create operation - create a new newsletter channel."""
+ channel_name = parameters.get('channel_name')
+ if not channel_name:
+ raise ValueError("Channel name is required")
+
+ rpc_params: Dict[str, Any] = {'name': channel_name}
+ description = parameters.get('channel_description')
+ if description:
+ rpc_params['description'] = description
+
+ data = await rpc_call('newsletter_create', rpc_params)
+
+ if isinstance(data, dict) and not data.get('success', True):
+ raise Exception(data.get('error', 'Failed to create channel'))
+
+ result = data if not isinstance(data, dict) or 'result' not in data else data.get('result', data)
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "whatsappDb",
+ "result": {
+ "operation": "channel_create",
+ **result,
+ "timestamp": datetime.now().isoformat()
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+
diff --git a/server/skills/social_agent/whatsapp-db-skill/SKILL.md b/server/skills/social_agent/whatsapp-db-skill/SKILL.md
index a19c0c0e..74fd05b8 100644
--- a/server/skills/social_agent/whatsapp-db-skill/SKILL.md
+++ b/server/skills/social_agent/whatsapp-db-skill/SKILL.md
@@ -1,6 +1,6 @@
---
name: whatsapp-db-skill
-description: Query WhatsApp database for contacts, groups, and chat history. Look up contact info, search groups, retrieve messages.
+description: Query WhatsApp database for contacts, groups, channels, and chat history. Look up contact info, search groups, manage channels, retrieve messages.
allowed-tools: whatsapp_db
metadata:
author: machina
@@ -12,7 +12,7 @@ metadata:
# WhatsApp Database Tool
-Query WhatsApp database for contacts, groups, and message history.
+Query WhatsApp database for contacts, groups, channels (newsletters), and message history.
## How It Works
@@ -20,7 +20,7 @@ This skill provides instructions for the **WhatsApp DB** tool node. Connect the
## whatsapp_db Tool
-Query contacts, groups, and chat history.
+Query contacts, groups, channels, and chat history.
### Schema Fields
@@ -38,6 +38,12 @@ Query contacts, groups, and chat history.
| sender_phone | string | No | Filter by sender (when group_filter="contact") |
| phones | string | For check_contacts | Comma-separated phone numbers |
| participant_limit | int | No | Max participants (for get_group_info, 1-100) |
+| channel_jid | string | For channel ops | Newsletter JID (e.g., `120363198765432101@newsletter`) |
+| refresh | boolean | No | Force refresh from server (for list_channels, get_channel_info) |
+| channel_count | int | No | Number of items to fetch (for channel_messages, channel_stats) |
+| before_server_id | int | No | Pagination cursor (for channel_messages) |
+| channel_name | string | For channel_create | Name of the new channel |
+| channel_description | string | No | Description (for channel_create) |
### Operations
@@ -49,6 +55,13 @@ Query contacts, groups, and chat history.
| `get_group_info` | Get group details with participants | group_id |
| `chat_history` | Retrieve message history | chat_type, phone/group_id |
| `check_contacts` | Check WhatsApp registration | phones |
+| `list_channels` | List subscribed newsletter channels | refresh (optional), limit |
+| `get_channel_info` | Get channel details | channel_jid |
+| `channel_messages` | Get channel message history | channel_jid, channel_count |
+| `channel_stats` | Get channel subscriber/view stats | channel_jid |
+| `channel_follow` | Follow/subscribe to a channel | channel_jid |
+| `channel_unfollow` | Unfollow/unsubscribe from a channel | channel_jid |
+| `channel_create` | Create a new newsletter channel | channel_name |
### Limits
@@ -58,6 +71,9 @@ Query contacts, groups, and chat history.
| search_groups | 20 | 50 |
| list_contacts | 50 | 100 |
| get_group_info participants | 50 | 100 |
+| list_channels | 20 | 50 |
+| channel_messages | 20 | 100 |
+| channel_stats | 10 | 100 |
**Important:** Always use small limits and specific queries to avoid context overflow.
@@ -232,6 +248,75 @@ Check if phone numbers have WhatsApp.
}
```
+### list_channels
+
+List subscribed newsletter channels.
+
+```json
+{
+ "operation": "list_channels",
+ "limit": 10
+}
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "operation": "list_channels",
+ "channels": [
+ {"jid": "120363198765432101@newsletter", "name": "Tech Updates", "subscriber_count": 5000}
+ ],
+ "total": 3
+}
+```
+
+### get_channel_info
+
+Get channel details.
+
+```json
+{
+ "operation": "get_channel_info",
+ "channel_jid": "120363198765432101@newsletter"
+}
+```
+
+### channel_messages
+
+Get channel message history.
+
+```json
+{
+ "operation": "channel_messages",
+ "channel_jid": "120363198765432101@newsletter",
+ "channel_count": 10
+}
+```
+
+### channel_follow
+
+Follow/subscribe to a channel.
+
+```json
+{
+ "operation": "channel_follow",
+ "channel_jid": "120363198765432101@newsletter"
+}
+```
+
+### channel_create
+
+Create a new newsletter channel.
+
+```json
+{
+ "operation": "channel_create",
+ "channel_name": "My Channel",
+ "channel_description": "A channel about interesting topics"
+}
+```
+
## Common Workflows
### Find and message someone by name
diff --git a/server/skills/social_agent/whatsapp-send-skill/SKILL.md b/server/skills/social_agent/whatsapp-send-skill/SKILL.md
index 925af159..becf01b2 100644
--- a/server/skills/social_agent/whatsapp-send-skill/SKILL.md
+++ b/server/skills/social_agent/whatsapp-send-skill/SKILL.md
@@ -1,6 +1,6 @@
---
name: whatsapp-send-skill
-description: Send WhatsApp messages to contacts or groups. Supports text, images, videos, audio, documents, stickers, locations, and contacts.
+description: Send WhatsApp messages to contacts, groups, or channels. Supports text, images, videos, audio, documents, stickers, locations, and contacts.
allowed-tools: whatsapp_send
metadata:
author: machina
@@ -12,7 +12,7 @@ metadata:
# WhatsApp Send Tool
-Send messages to WhatsApp contacts or groups.
+Send messages to WhatsApp contacts, groups, or newsletter channels.
## How It Works
@@ -20,15 +20,16 @@ This skill provides instructions for the **WhatsApp Send** tool node. Connect th
## whatsapp_send Tool
-Send messages to individual contacts or groups.
+Send messages to individual contacts, groups, or channels.
### Schema Fields
| Field | Type | Required | Description |
|-------|------|----------|-------------|
-| recipient_type | string | Yes | `"phone"` for individual or `"group"` for group chat |
+| recipient_type | string | Yes | `"phone"` for individual, `"group"` for group chat, or `"channel"` for newsletter |
| phone | string | If phone | Phone number without + prefix (e.g., `1234567890`) |
| group_id | string | If group | Group JID (e.g., `[email protected]`) |
+| channel_jid | string | If channel | Newsletter JID (e.g., `120363198765432101@newsletter`) |
| message_type | string | Yes | Message type (see below) |
| message | string | If text | Text message content |
| media_url | string | If media | URL for image/video/audio/document/sticker |
@@ -86,6 +87,18 @@ Send messages to individual contacts or groups.
}
```
+**Send to channel (newsletter):**
+```json
+{
+ "recipient_type": "channel",
+ "channel_jid": "120363198765432101@newsletter",
+ "message_type": "text",
+ "message": "Channel update: new features released!"
+}
+```
+
+> **Channel limitations:** Channels only support `text`, `image`, `video`, `audio`, and `document` message types. Sticker, location, and contact are NOT supported. You must be an admin/owner of the channel to send.
+
**Send video:**
```json
{
@@ -160,7 +173,8 @@ Send messages to individual contacts or groups.
1. **Phone numbers**: Always use without + prefix, just digits (e.g., `919876543210`)
2. **Group IDs**: Use JID format ending in `@g.us` (e.g., `[email protected]`)
-3. **Media URLs**: Must be publicly accessible URLs (https://)
+3. **Channel JIDs**: Use JID format ending in `@newsletter` (e.g., `120363198765432101@newsletter`)
+4. **Media URLs**: Must be publicly accessible URLs (https://)
4. **vCard format**: Use vCard 3.0 specification for contact cards
5. **Message length**: Text messages can be up to 4096 characters
6. **Media size**: Check WhatsApp limits for media file sizes