Skip to content

Self-improving AI Employees for everyone

feat: WhatsApp channel fixes - invite link resolution, mute, mark viewed

trohitgf4f60d8586fb
diff --git a/client/src/components/ParameterRenderer.tsx b/client/src/components/ParameterRenderer.tsx
index 84271fac..e89c17e7 100644
--- a/client/src/components/ParameterRenderer.tsx
+++ b/client/src/components/ParameterRenderer.tsx
@@ -699,6 +699,182 @@ const SenderNumberSelector: React.FC<{
);
};
+// Channel JID Selector - with Load Channels button and dropdown
+const ChannelJidSelector: React.FC<{
+ value: string;
+ onChange: (value: string) => void;
+ onNameChange?: (name: string) => void;
+ storedName?: string;
+ placeholder?: string;
+ theme: ReturnType<typeof useAppTheme>;
+ isDragOver: boolean;
+ onDragOver: (e: React.DragEvent) => void;
+ onDragLeave: (e: React.DragEvent) => void;
+ onDrop: (e: React.DragEvent) => void;
+}> = ({ value, onChange, onNameChange, storedName, placeholder, theme, isDragOver, onDragOver, onDragLeave, onDrop }) => {
+ const [channels, setChannels] = useState<Array<{ jid: string; name: string; subscriber_count?: number; role?: string }>>([]);
+ const [isLoading, setIsLoading] = useState(false);
+ const [showDropdown, setShowDropdown] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [localChannelName, setLocalChannelName] = useState<string | null>(null);
+ const selectedChannelName = storedName || localChannelName;
+ const { getWhatsAppChannels } = useWebSocket();
+
+ useEffect(() => {
+ if (storedName) setLocalChannelName(storedName);
+ }, [storedName]);
+
+ const handleLoadChannels = async () => {
+ setIsLoading(true);
+ setError(null);
+ try {
+ const result = await getWhatsAppChannels();
+ if (result.success && result.channels.length > 0) {
+ setChannels(result.channels);
+ setShowDropdown(true);
+ if (value) {
+ const match = result.channels.find(c => c.jid === value);
+ if (match && match.name !== storedName) {
+ setLocalChannelName(match.name);
+ onNameChange?.(match.name);
+ }
+ }
+ } else if (result.error) {
+ setError(result.error);
+ } else {
+ setError('No channels found');
+ }
+ } catch (err: any) {
+ setError(err.message || 'Failed to load channels');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleSelectChannel = (ch: { jid: string; name: string }) => {
+ onChange(ch.jid);
+ setLocalChannelName(ch.name);
+ onNameChange?.(ch.name);
+ setShowDropdown(false);
+ };
+
+ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ onChange(e.target.value);
+ setLocalChannelName(null);
+ onNameChange?.('');
+ };
+
+ const displayValue = selectedChannelName || value;
+ const isSelected = selectedChannelName !== null && value;
+ const isTemplate = value && value.includes('{{');
+
+ return (
+ <div style={{ position: 'relative' }}>
+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
+ <input
+ type="text"
+ value={displayValue}
+ onChange={handleInputChange}
+ placeholder={placeholder || '120363...@newsletter or https://whatsapp.com/channel/...'}
+ onDragOver={onDragOver}
+ onDragLeave={onDragLeave}
+ onDrop={onDrop}
+ style={{
+ flex: 1,
+ padding: '8px 12px',
+ border: isDragOver ? `2px solid ${theme.colors.focus}` : `1px solid ${theme.colors.border}`,
+ borderRadius: theme.borderRadius.md,
+ fontSize: theme.fontSize.base,
+ backgroundColor: isSelected ? theme.colors.backgroundAlt : (isDragOver ? theme.colors.focusRing : theme.colors.background),
+ color: isSelected ? theme.colors.success : (isTemplate ? theme.colors.templateVariable : theme.colors.text),
+ outline: 'none',
+ transition: 'all 0.2s ease',
+ fontFamily: isTemplate ? theme.fontFamily.mono : theme.fontFamily.sans,
+ fontWeight: isSelected ? theme.fontWeight.medium : theme.fontWeight.normal
+ }}
+ onFocus={(e) => e.target.style.borderColor = theme.colors.focus}
+ onBlur={(e) => e.target.style.borderColor = theme.colors.border}
+ />
+ <button
+ onClick={handleLoadChannels}
+ disabled={isLoading}
+ style={{
+ padding: '8px 12px',
+ border: `1px solid ${isLoading ? theme.colors.border : `${theme.colors.focus}40`}`,
+ borderRadius: theme.borderRadius.md,
+ backgroundColor: isLoading ? 'transparent' : `${theme.colors.focus}18`,
+ color: isLoading ? theme.colors.textMuted : theme.colors.focus,
+ cursor: isLoading ? 'wait' : 'pointer',
+ fontSize: theme.fontSize.sm,
+ fontWeight: theme.fontWeight.semibold,
+ fontFamily: theme.fontFamily.sans,
+ transition: 'all 0.2s ease',
+ whiteSpace: 'nowrap',
+ opacity: isLoading ? 0.7 : 1
+ }}
+ onMouseEnter={(e) => { if (!isLoading) e.currentTarget.style.backgroundColor = `${theme.colors.focus}30`; }}
+ onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = isLoading ? 'transparent' : `${theme.colors.focus}18`; }}
+ title="Load WhatsApp channels"
+ >
+ {isLoading ? 'Loading...' : 'Load'}
+ </button>
+ </div>
+ {isSelected && (
+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginTop: '4px', fontFamily: theme.fontFamily.mono }}>
+ {value}
+ </div>
+ )}
+ {error && (
+ <div style={{ fontSize: theme.fontSize.sm, color: theme.colors.error, marginTop: '4px', fontFamily: theme.fontFamily.sans }}>
+ {error}
+ </div>
+ )}
+ {showDropdown && channels.length > 0 && (
+ <div style={{
+ position: 'absolute', top: '100%', left: 0, right: 0, marginTop: '4px',
+ backgroundColor: theme.colors.background, border: `1px solid ${theme.colors.border}`,
+ borderRadius: theme.borderRadius.md, boxShadow: `0 4px 12px ${theme.colors.shadow}`,
+ maxHeight: '200px', overflowY: 'auto', zIndex: 1000
+ }}>
+ {channels.map((ch, i) => (
+ <button
+ key={ch.jid}
+ onClick={() => handleSelectChannel(ch)}
+ style={{
+ width: '100%', padding: '10px 12px', border: 'none', backgroundColor: 'transparent',
+ color: theme.colors.text, cursor: 'pointer', fontSize: theme.fontSize.sm,
+ fontFamily: theme.fontFamily.sans, textAlign: 'left',
+ borderBottom: i < channels.length - 1 ? `1px solid ${theme.colors.border}` : 'none'
+ }}
+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt}
+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}
+ >
+ <div style={{ fontWeight: theme.fontWeight.medium }}>{ch.name}</div>
+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginTop: '2px', fontFamily: theme.fontFamily.mono }}>
+ {ch.jid}
+ {ch.subscriber_count != null && <span style={{ marginLeft: '8px' }}>({ch.subscriber_count} subscribers)</span>}
+ </div>
+ </button>
+ ))}
+ <button
+ onClick={() => setShowDropdown(false)}
+ style={{
+ width: '100%', padding: '8px 12px', border: 'none',
+ borderTop: `1px solid ${theme.colors.border}`, backgroundColor: theme.colors.backgroundAlt,
+ color: theme.colors.textSecondary, cursor: 'pointer', fontSize: theme.fontSize.sm,
+ fontFamily: theme.fontFamily.sans, textAlign: 'center'
+ }}
+ onMouseEnter={(e) => e.currentTarget.style.color = theme.colors.text}
+ onMouseLeave={(e) => e.currentTarget.style.color = theme.colors.textSecondary}
+ >
+ Close
+ </button>
+ </div>
+ )}
+ </div>
+ );
+};
+
// Fixed Collection Renderer - n8n style fixed collection
const FixedCollectionRenderer: React.FC<{
parameter: any;
@@ -1374,6 +1550,25 @@ const ParameterRenderer: React.FC<ParameterRendererProps> = ({
);
}
+ // Special case for channel_jid parameter - add Load Channels button
+ if (parameter.name === 'channel_jid') {
+ const storedChannelName = allParameters?.channel_display_name || '';
+ return (
+ <ChannelJidSelector
+ value={currentValue || ''}
+ onChange={onChange}
+ onNameChange={(name) => onParameterChange?.('channel_display_name', name)}
+ storedName={storedChannelName}
+ placeholder={parameter.placeholder}
+ theme={theme}
+ isDragOver={isDragOver}
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ />
+ );
+ }
+
// Special case for senderNumber parameter - add Load Members button (uses group_id)
if (parameter.name === 'senderNumber') {
const groupId = resolvedParameters?.group_id || allParameters?.group_id || '';
diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsx
index e365941f..51d7a280 100644
--- a/client/src/components/parameterPanel/InputSection.tsx
+++ b/client/src/components/parameterPanel/InputSection.tsx
@@ -249,7 +249,11 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
// channel operations output
channels: [{ jid: 'string', name: 'string', subscriber_count: 'number' }],
channel_jid: 'string',
- timestamp: 'string'
+ timestamp: 'string',
+ // channel_mute / channel_mark_viewed / follow / unfollow output
+ muted: 'boolean',
+ server_ids: 'string',
+ status: 'string'
},
webhook: {
method: 'string',
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index befbd62d..17ed4f3c 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -318,6 +318,7 @@ interface WebSocketContextValue {
startWhatsAppConnection: () => Promise<{ success: boolean; message?: string }>;
restartWhatsAppConnection: () => Promise<{ success: boolean; message?: string }>;
getWhatsAppGroups: () => Promise<{ success: boolean; groups: Array<{ jid: string; name: string; topic?: string; size?: number; is_community?: boolean }>; error?: string }>;
+ getWhatsAppChannels: () => Promise<{ success: boolean; channels: Array<{ jid: string; name: string; subscriber_count?: number; role?: string }>; error?: string }>;
getWhatsAppGroupInfo: (groupId: string) => Promise<{ success: boolean; participants: Array<{ phone: string; name: string; jid: string; is_admin?: boolean }>; name?: string; error?: string }>;
getWhatsAppRateLimitConfig: () => Promise<{ success: boolean; config?: RateLimitConfig; stats?: RateLimitStats; error?: string }>;
setWhatsAppRateLimitConfig: (config: Partial<RateLimitConfig>) => Promise<{ success: boolean; config?: RateLimitConfig; error?: string }>;
@@ -1996,6 +1997,21 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
}, [sendRequest]);
+ const getWhatsAppChannelsAsync = useCallback(async (): Promise<{ success: boolean; channels: Array<{ jid: string; name: string; subscriber_count?: number; role?: string }>; error?: string }> => {
+ try {
+ const response = await sendRequest<any>('whatsapp_newsletters', {});
+ const channels = response.channels || response.result?.channels || [];
+ return {
+ success: response.success !== false,
+ channels,
+ error: response.error
+ };
+ } catch (error: any) {
+ console.error('[WebSocket] Failed to get WhatsApp channels:', error);
+ return { success: false, channels: [], error: error.message || 'Failed to get channels' };
+ }
+ }, [sendRequest]);
+
const getWhatsAppGroupInfoAsync = useCallback(async (groupId: string): Promise<{ success: boolean; participants: Array<{ phone: string; name: string; jid: string; is_admin?: boolean }>; name?: string; error?: string }> => {
try {
const response = await sendRequest<any>('whatsapp_group_info', { group_id: groupId });
@@ -2251,6 +2267,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
startWhatsAppConnection: startWhatsAppConnectionAsync,
restartWhatsAppConnection: restartWhatsAppConnectionAsync,
getWhatsAppGroups: getWhatsAppGroupsAsync,
+ getWhatsAppChannels: getWhatsAppChannelsAsync,
getWhatsAppGroupInfo: getWhatsAppGroupInfoAsync,
getWhatsAppRateLimitConfig: getWhatsAppRateLimitConfigAsync,
setWhatsAppRateLimitConfig: setWhatsAppRateLimitConfigAsync,
diff --git a/client/src/nodeDefinitions/whatsappNodes.ts b/client/src/nodeDefinitions/whatsappNodes.ts
index 7ebe8ccb..ee2bf01c 100644
--- a/client/src/nodeDefinitions/whatsappNodes.ts
+++ b/client/src/nodeDefinitions/whatsappNodes.ts
@@ -683,7 +683,9 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
{ name: 'Channel Stats', value: 'channel_stats' },
{ name: 'Follow Channel', value: 'channel_follow' },
{ name: 'Unfollow Channel', value: 'channel_unfollow' },
- { name: 'Create Channel', value: 'channel_create' }
+ { name: 'Create Channel', value: 'channel_create' },
+ { name: 'Mute/Unmute Channel', value: 'channel_mute' },
+ { name: 'Mark Channel Viewed', value: 'channel_mark_viewed' }
],
default: 'chat_history',
description: 'Operation to perform'
@@ -855,7 +857,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
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'] }
+ show: { operation: ['get_channel_info', 'channel_messages', 'channel_stats', 'channel_follow', 'channel_unfollow', 'channel_mute', 'channel_mark_viewed'] }
}
},
{
@@ -913,7 +915,29 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
displayOptions: {
show: { operation: ['channel_create'] }
}
+ },
+ {
+ displayName: 'Mute',
+ name: 'mute',
+ type: 'boolean',
+ default: true,
+ description: 'True to mute the channel, false to unmute',
+ displayOptions: {
+ show: { operation: ['channel_mute'] }
+ }
+ },
+ {
+ displayName: 'Server IDs',
+ name: 'server_ids',
+ type: 'string',
+ default: '',
+ placeholder: '100, 101, 102',
+ description: 'Comma-separated message server IDs to mark as viewed',
+ displayOptions: {
+ show: { operation: ['channel_mark_viewed'] }
+ }
}
+
],
methods: {
loadOptions: {
diff --git a/server/services/ai.py b/server/services/ai.py
index 8610888f..6411a8b9 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -2857,10 +2857,12 @@ class AIService:
- 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)
+ - channel_mute: Mute/unmute a channel (requires channel_jid, mute)
+ - channel_mark_viewed: Mark channel messages as viewed (requires channel_jid, server_ids)
"""
operation: str = Field(
default="chat_history",
- 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'"
+ 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', 'channel_mute', 'channel_mark_viewed'"
)
# For chat_history
chat_type: Optional[str] = Field(
@@ -2910,7 +2912,7 @@ class AIService:
# 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."
+ description="Newsletter JID (e.g., 120363198765432101@newsletter) or invite link (https://whatsapp.com/channel/...). Required for get_channel_info, channel_messages, channel_stats, channel_follow, channel_unfollow, channel_mute, channel_mark_viewed."
)
refresh: Optional[bool] = Field(
default=None,
@@ -2932,6 +2934,14 @@ class AIService:
default=None,
description="For channel_create: description of the new channel."
)
+ mute: Optional[bool] = Field(
+ default=None,
+ description="For channel_mute: True to mute, False to unmute."
+ )
+ server_ids: Optional[str] = Field(
+ default=None,
+ description="For channel_mark_viewed: comma-separated message server IDs to mark as viewed (e.g., '100, 101, 102')."
+ )
return WhatsAppDbSchema
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index fddd7307..ddc6abcd 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -873,6 +873,23 @@ async def _execute_whatsapp_db(args: Dict[str, Any],
if args.get('channel_description'):
parameters['channel_description'] = args['channel_description']
+ elif operation == 'channel_mute':
+ channel_jid = args.get('channel_jid', '')
+ if not channel_jid:
+ return {"error": "channel_jid is required for channel_mute"}
+ parameters['channel_jid'] = channel_jid
+ parameters['mute'] = args.get('mute', True)
+
+ elif operation == 'channel_mark_viewed':
+ channel_jid = args.get('channel_jid', '')
+ if not channel_jid:
+ return {"error": "channel_jid is required for channel_mark_viewed"}
+ parameters['channel_jid'] = channel_jid
+ server_ids = args.get('server_ids', '')
+ if not server_ids:
+ return {"error": "server_ids is required for channel_mark_viewed"}
+ parameters['server_ids'] = server_ids
+
else:
return {"error": f"Unknown operation: {operation}"}
diff --git a/server/services/handlers/whatsapp.py b/server/services/handlers/whatsapp.py
index da90cb77..4c3a5ab1 100644
--- a/server/services/handlers/whatsapp.py
+++ b/server/services/handlers/whatsapp.py
@@ -8,6 +8,48 @@ from core.logging import get_logger
logger = get_logger(__name__)
+def _is_invite_link(value: str) -> bool:
+ """Check if a channel identifier is an invite link URL."""
+ return value.strip().startswith('http://') or value.strip().startswith('https://')
+
+
+def _resolve_channel_identifier(value: str) -> Dict[str, str]:
+ """Route a channel identifier to the correct RPC parameter key.
+
+ For RPC methods that accept both 'jid' and 'invite' params
+ (newsletter_info, newsletter_stats).
+ """
+ if not value:
+ return {}
+ value = value.strip()
+ if _is_invite_link(value):
+ return {'invite': value}
+ return {'jid': value}
+
+
+async def _resolve_to_jid(value: str, rpc_call) -> str:
+ """Resolve a channel identifier to a JID string.
+
+ If the value is an invite link, calls newsletter_info to look up the JID.
+ For RPC methods that only accept 'jid' (newsletter_messages,
+ newsletter_follow, newsletter_unfollow, newsletter_mute,
+ newsletter_mark_viewed).
+ """
+ if not value:
+ raise ValueError("Channel JID is required")
+ value = value.strip()
+ if not _is_invite_link(value):
+ return value
+ # Resolve invite link to JID via newsletter_info
+ data = await rpc_call('newsletter_info', {'invite': value})
+ if isinstance(data, dict):
+ result = data.get('result', data)
+ jid = result.get('jid') or result.get('id')
+ if jid:
+ return jid
+ raise ValueError(f"Could not resolve invite link to channel JID: {value}")
+
+
async def handle_whatsapp_send(
node_id: str,
node_type: str,
@@ -150,6 +192,14 @@ async def handle_whatsapp_db(
- channel_follow: Follow/subscribe to a channel
- channel_unfollow: Unfollow/unsubscribe from a channel
- channel_create: Create a new newsletter channel
+ - channel_mute: Mute/unmute a newsletter channel
+ - channel_mark_viewed: Mark channel messages as viewed
+
+ Channel operations accept both JIDs (120363...@newsletter) and
+ invite links (https://whatsapp.com/channel/...). Methods that support
+ both params directly (newsletter_info, newsletter_stats) use
+ _resolve_channel_identifier(). Other methods use _resolve_to_jid()
+ which resolves invite links to JIDs via newsletter_info first.
Args:
node_id: The node ID
@@ -195,6 +245,10 @@ async def handle_whatsapp_db(
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)
+ elif operation == 'channel_mute':
+ return await _handle_channel_mute(node_id, parameters, start_time, whatsapp_rpc_call)
+ elif operation == 'channel_mark_viewed':
+ return await _handle_channel_mark_viewed(node_id, parameters, start_time, whatsapp_rpc_call)
else:
raise ValueError(f"Unknown operation: {operation}")
@@ -505,7 +559,7 @@ async def _handle_get_channel_info(node_id: str, parameters: Dict[str, Any], sta
if not channel_jid:
raise ValueError("Channel JID is required")
- rpc_params: Dict[str, Any] = {'jid': channel_jid}
+ rpc_params: Dict[str, Any] = _resolve_channel_identifier(channel_jid)
if parameters.get('refresh'):
rpc_params['refresh'] = True
@@ -533,15 +587,14 @@ async def _handle_get_channel_info(node_id: str, parameters: Dict[str, Any], sta
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")
+ jid = await _resolve_to_jid(channel_jid, rpc_call)
count = parameters.get('channel_count', 20)
- rpc_params: Dict[str, Any] = {'jid': channel_jid, 'count': count}
+ rpc_params: Dict[str, Any] = {'jid': jid, 'count': count}
before_server_id = parameters.get('before_server_id')
if before_server_id:
- rpc_params['before_server_id'] = int(before_server_id)
+ rpc_params['before'] = int(before_server_id)
data = await rpc_call('newsletter_messages', rpc_params)
@@ -573,7 +626,7 @@ async def _handle_channel_stats(node_id: str, parameters: Dict[str, Any], start_
raise ValueError("Channel JID is required")
count = parameters.get('channel_count', 10)
- rpc_params: Dict[str, Any] = {'jid': channel_jid, 'count': count}
+ rpc_params: Dict[str, Any] = {**_resolve_channel_identifier(channel_jid), 'count': count}
data = await rpc_call('newsletter_stats', rpc_params)
@@ -600,10 +653,9 @@ async def _handle_channel_stats(node_id: str, parameters: Dict[str, Any], start_
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")
+ jid = await _resolve_to_jid(channel_jid, rpc_call)
- data = await rpc_call('newsletter_follow', {'jid': channel_jid})
+ data = await rpc_call('newsletter_follow', {'jid': jid})
if isinstance(data, dict) and not data.get('success', True):
raise Exception(data.get('error', 'Failed to follow channel'))
@@ -626,10 +678,9 @@ async def _handle_channel_follow(node_id: str, parameters: Dict[str, Any], start
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")
+ jid = await _resolve_to_jid(channel_jid, rpc_call)
- data = await rpc_call('newsletter_unfollow', {'jid': channel_jid})
+ data = await rpc_call('newsletter_unfollow', {'jid': jid})
if isinstance(data, dict) and not data.get('success', True):
raise Exception(data.get('error', 'Failed to unfollow channel'))
@@ -681,3 +732,68 @@ async def _handle_channel_create(node_id: str, parameters: Dict[str, Any], start
}
+async def _handle_channel_mute(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:
+ """Handle channel_mute operation - mute/unmute a newsletter channel."""
+ channel_jid = parameters.get('channel_jid')
+ jid = await _resolve_to_jid(channel_jid, rpc_call)
+
+ mute = parameters.get('mute', True)
+ rpc_params = {'jid': jid, 'mute': bool(mute)}
+
+ data = await rpc_call('newsletter_mute', rpc_params)
+
+ if isinstance(data, dict) and not data.get('success', True):
+ raise Exception(data.get('error', 'Failed to mute/unmute channel'))
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "whatsappDb",
+ "result": {
+ "operation": "channel_mute",
+ "channel_jid": channel_jid,
+ "muted": mute,
+ "status": "muted" if mute else "unmuted",
+ "timestamp": datetime.now().isoformat()
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+
+async def _handle_channel_mark_viewed(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:
+ """Handle channel_mark_viewed operation - mark channel messages as viewed."""
+ channel_jid = parameters.get('channel_jid')
+ jid = await _resolve_to_jid(channel_jid, rpc_call)
+
+ server_ids_raw = parameters.get('server_ids', '')
+ if not server_ids_raw:
+ raise ValueError("server_ids is required (comma-separated message IDs)")
+
+ server_ids = [int(sid.strip()) for sid in str(server_ids_raw).split(',') if sid.strip()]
+ if not server_ids:
+ raise ValueError("At least one server_id is required")
+
+ rpc_params = {'jid': jid, 'server_ids': server_ids}
+
+ data = await rpc_call('newsletter_mark_viewed', rpc_params)
+
+ if isinstance(data, dict) and not data.get('success', True):
+ raise Exception(data.get('error', 'Failed to mark channel as viewed'))
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "whatsappDb",
+ "result": {
+ "operation": "channel_mark_viewed",
+ "channel_jid": channel_jid,
+ "server_ids": ','.join(str(s) for s in server_ids),
+ "status": "marked_viewed",
+ "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 74fd05b8..ecc24c3f 100644
--- a/server/skills/social_agent/whatsapp-db-skill/SKILL.md
+++ b/server/skills/social_agent/whatsapp-db-skill/SKILL.md
@@ -38,12 +38,14 @@ Query contacts, groups, channels, 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`) |
+| channel_jid | string | For channel ops | Newsletter JID or invite link URL (e.g., `120363198765432101@newsletter` or `https://whatsapp.com/channel/...`) |
| 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) |
+| mute | boolean | For channel_mute | True to mute, false to unmute |
+| server_ids | string | For channel_mark_viewed | Comma-separated message server IDs to mark as viewed |
### Operations
@@ -62,6 +64,8 @@ Query contacts, groups, channels, and chat history.
| `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 |
+| `channel_mute` | Mute or unmute a channel | channel_jid, mute |
+| `channel_mark_viewed` | Mark channel messages as viewed | channel_jid, server_ids |
### Limits
@@ -74,6 +78,8 @@ Query contacts, groups, channels, and chat history.
| list_channels | 20 | 50 |
| channel_messages | 20 | 100 |
| channel_stats | 10 | 100 |
+| channel_mute | - | - |
+| channel_mark_viewed | - | - |
**Important:** Always use small limits and specific queries to avoid context overflow.
@@ -317,6 +323,41 @@ Create a new newsletter channel.
}
```
+### channel_mute
+
+Mute or unmute a newsletter channel.
+
+```json
+{
+ "operation": "channel_mute",
+ "channel_jid": "120363198765432101@newsletter",
+ "mute": true
+}
+```
+
+### channel_mark_viewed
+
+Mark channel messages as viewed by server ID.
+
+```json
+{
+ "operation": "channel_mark_viewed",
+ "channel_jid": "120363198765432101@newsletter",
+ "server_ids": "100, 101, 102"
+}
+```
+
+### get_channel_info (with invite link)
+
+Get channel details using an invite link instead of JID.
+
+```json
+{
+ "operation": "get_channel_info",
+ "channel_jid": "https://whatsapp.com/channel/0029Va12345abcdef"
+}
+```
+
## Common Workflows
### Find and message someone by name
@@ -348,6 +389,8 @@ Create a new newsletter channel.
3. **Limits**: Use small limits to avoid context overflow
4. **Queries**: Be specific to narrow results
5. **Pagination**: Use offset to page through chat_history
+6. **Channel JIDs**: JID format ending in `@newsletter`, or pass an invite link URL
+7. **Invite links**: `channel_jid` accepts both JIDs and `https://whatsapp.com/channel/...` URLs
## Error Responses
diff --git a/server/skills/social_agent/whatsapp-send-skill/SKILL.md b/server/skills/social_agent/whatsapp-send-skill/SKILL.md
index becf01b2..1120f944 100644
--- a/server/skills/social_agent/whatsapp-send-skill/SKILL.md
+++ b/server/skills/social_agent/whatsapp-send-skill/SKILL.md
@@ -175,9 +175,9 @@ Send messages to individual contacts, groups, or channels.
2. **Group IDs**: Use JID format ending in `@g.us` (e.g., `[email protected]`)
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
+5. **vCard format**: Use vCard 3.0 specification for contact cards
+6. **Message length**: Text messages can be up to 4096 characters
+7. **Media size**: Check WhatsApp limits for media file sizes
## Common Use Cases