Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(whatsapp): add send_media to the Business Send node
trohitg414061f2b300
diff --git a/server/nodes/whatsapp_business/whatsapp_business_send.py b/server/nodes/whatsapp_business/whatsapp_business_send.pyindex 601307f0..ed9519a0 100644--- a/server/nodes/whatsapp_business/whatsapp_business_send.py+++ b/server/nodes/whatsapp_business/whatsapp_business_send.py@@ -2,7 +2,7 @@from __future__ import annotations-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Field@@ -20,6 +20,13 @@ _MAX_TEXT_BODY = 4096class WhatsAppBusinessSendParams(BaseModel):"""Operator configuration, persisted on the node."""+ # Required once a node declares more than one @Operation: _pick_operation+ # reads this off the raw parameters, and an absent value resolves to no+ # operation at all rather than a default.+ operation: Literal["send_text", "send_media"] = Field(+ default="send_text",+ description="What to send.",+ )to: str = Field(default="",description="Recipient phone number in international format (e.g. +14155551234).",@@ -42,6 +49,55 @@ class WhatsAppBusinessSendParams(BaseModel):description="Convert GFM markdown to WhatsApp's *bold* / _italic_ syntax.",)+ # --- send_media ---------------------------------------------------------+ # Named media_type, NOT message_type. ParameterRenderer.getFileAcceptType+ # hardcodes a switch on a sibling parameter literally called+ # `message_type` and, when present, overrides whatever `accept` the+ # backend declared. Sidestepping the name keeps this node's accept list+ # authoritative without a frontend change.+ media_type: Literal["image", "video", "audio", "document", "sticker"] = Field(+ default="image",+ description="Kind of media to send.",+ json_schema_extra={"displayOptions": {"show": {"operation": ["send_media"]}}},+ )+ media_source: Literal["file", "id", "link"] = Field(+ default="file",+ description=(+ "file: upload from the workspace. id: a media ID already uploaded. "+ "link: a public URL Meta fetches itself."+ ),+ json_schema_extra={"displayOptions": {"show": {"operation": ["send_media"]}}},+ )+ media: Any = Field(+ default=None,+ description="File to send.",+ json_schema_extra={+ "widget": "file",+ "accept": "*/*",+ "displayOptions": {"show": {"media_source": ["file"]}},+ },+ )+ media_id: str = Field(+ default="",+ description="Existing Meta media ID.",+ json_schema_extra={"displayOptions": {"show": {"media_source": ["id"]}}},+ )+ media_url: str = Field(+ default="",+ description="Publicly reachable URL. Meta downloads it directly.",+ json_schema_extra={"displayOptions": {"show": {"media_source": ["link"]}}},+ )+ caption: str = Field(+ default="",+ description="Caption. Not supported for audio or sticker.",+ json_schema_extra={"displayOptions": {"show": {"operation": ["send_media"]}}},+ )+ media_filename: str = Field(+ default="",+ description="Filename shown to the recipient. Documents only.",+ json_schema_extra={"displayOptions": {"show": {"media_type": ["document"]}}},+ )+# There is deliberately NO phone_number_id parameter.## It selects which business identity a message is sent *from*, so it is@@ -140,18 +196,91 @@ class WhatsAppBusinessSendNode(ActionNode):payload["context"] = {"message_id": reply_to}result = await graph_post(ctx, f"{phone_number_id}/messages", payload)+ return _shape_send_result(result, recipient, phone_number_id)++ @Operation("send_media", cost={"service": "whatsapp_business", "action": "send_media", "count": 1})+ async def send_media(+ self, ctx: NodeContext, params: WhatsAppBusinessSendParams+ ) -> WhatsAppBusinessSendOutput:+ recipient = normalize_recipient(params.to)+ phone_number_id = await resolve_phone_number_id(ctx)+ media_type = params.media_type++ # `id` and `link` are a strict oneOf in Meta's schema -- sending both+ # is rejected, so exactly one is built here.+ media_object: Dict[str, Any] = {}+ if params.media_source == "link":+ if not params.media_url.strip():+ raise NodeUserError("Provide a media URL, or switch the source to file/id.")+ media_object["link"] = params.media_url.strip()+ elif params.media_source == "id":+ if not params.media_id.strip():+ raise NodeUserError("Provide a media ID, or switch the source to file/link.")+ media_object["id"] = params.media_id.strip()+ else:+ media_object["id"] = await _upload_for_send(ctx, params, phone_number_id)++ # Meta rejects a caption on audio and sticker rather than ignoring it.+ if params.caption.strip() and media_type not in {"audio", "sticker"}:+ media_object["caption"] = params.caption.strip()+ if media_type == "document" and params.media_filename.strip():+ media_object["filename"] = params.media_filename.strip()++ payload: Dict[str, Any] = {+ "messaging_product": "whatsapp",+ "recipient_type": "individual",+ "to": recipient,+ "type": media_type,+ media_type: media_object,+ }+ reply_to = (params.reply_to_message_id or "").strip()+ if reply_to:+ payload["context"] = {"message_id": reply_to}++ result = await graph_post(ctx, f"{phone_number_id}/messages", payload)+ return _shape_send_result(result, recipient, phone_number_id)+++async def _upload_for_send(+ ctx: NodeContext, params: WhatsAppBusinessSendParams, phone_number_id: str+) -> str:+ """Upload a workspace file and return the media id Meta assigns."""+ from services.media import coerce_file_param++ if params.media in (None, ""):+ raise NodeUserError("Select a file to send, or switch the media source to id/link.")++ filename, blob = coerce_file_param(params.media, ctx=ctx)+ import mimetypes- messages: List[Dict[str, Any]] = result.get("messages") or []- contacts: List[Dict[str, Any]] = result.get("contacts") or []- first = messages[0] if messages else {}-- return WhatsAppBusinessSendOutput(- message_id=first.get("id"),- message_status=first.get("message_status"),- to=recipient,- wa_id=(contacts[0].get("wa_id") if contacts else None),- phone_number_id=phone_number_id,- )+ mime_type = mimetypes.guess_type(filename)[0] or "application/octet-stream"+ result = await graph_post(+ ctx,+ f"{phone_number_id}/media",+ # Bytes, not a file handle: Connection.request replays the same kwargs+ # on its one auth retry, and a consumed handle would replay empty.+ files={"file": (filename, blob, mime_type)},+ data={"messaging_product": "whatsapp", "type": mime_type},+ )+ media_id = result.get("id")+ if not media_id:+ raise NodeUserError("WhatsApp accepted the upload but returned no media ID.")+ return str(media_id)+++def _shape_send_result(+ result: Dict[str, Any], recipient: str, phone_number_id: str+) -> WhatsAppBusinessSendOutput:+ messages: List[Dict[str, Any]] = result.get("messages") or []+ contacts: List[Dict[str, Any]] = result.get("contacts") or []+ first = messages[0] if messages else {}+ return WhatsAppBusinessSendOutput(+ message_id=first.get("id"),+ message_status=first.get("message_status"),+ to=recipient,+ wa_id=(contacts[0].get("wa_id") if contacts else None),+ phone_number_id=phone_number_id,+ )__all__ = [diff --git a/server/tests/nodes/test_whatsapp_business.py b/server/tests/nodes/test_whatsapp_business.pyindex 07885c48..d912046e 100644--- a/server/tests/nodes/test_whatsapp_business.py+++ b/server/tests/nodes/test_whatsapp_business.py@@ -97,7 +97,7 @@ class TestModelCannotChooseTheSendingNumber:result = _run(node.execute_as_tool({"to": "+14155551234", "text": "hi", "phone_number_id": "ATTACKER_NUMBER"},- {},+ {"operation": "send_text"},_ctx(),))@@ -114,7 +114,7 @@ class TestModelCannotChooseTheSendingNumber:return_value=SimpleNamespace(get_api_key=AsyncMock(return_value=None)),):envelope = _run(- node.execute("wac-1", {"to": "+14155551234", "text": "hi"}, _ctx())+ node.execute("wac-1", {"operation": "send_text", "to": "+14155551234", "text": "hi"}, _ctx()))assert envelope["success"] is False@@ -139,7 +139,7 @@ class TestSendText:return_value=SimpleNamespace(get_api_key=AsyncMock(return_value=number)),),):- _run(node.execute("wac-1", params, _ctx()))+ _run(node.execute("wac-1", {"operation": "send_text", **params}, _ctx()))return captureddef test_builds_the_documented_text_envelope(self):@@ -179,7 +179,7 @@ class TestSendText:envelope = _run(node.execute("wac-1",- {"to": "+14155551234", "text": "a" * 5000, "format_markdown": False},+ {"operation": "send_text", "to": "+14155551234", "text": "a" * 5000, "format_markdown": False},_ctx(),))@@ -192,7 +192,7 @@ class TestSendText:"services.plugin.deps.get_auth_service",return_value=SimpleNamespace(get_api_key=AsyncMock(return_value="PN1")),):- envelope = _run(node.execute("wac-1", {"to": "+14155551234", "text": " "}, _ctx()))+ envelope = _run(node.execute("wac-1", {"operation": "send_text", "to": "+14155551234", "text": " "}, _ctx()))assert envelope["success"] is False