Adds `whatsapp_agent`, an additive channel that connects nanobot to the official WhatsApp Agent Platform API (https://api.whatsapp.com/agent/v1). It authenticates with a per-agent API token and long-polls `GET /updates` instead of linking a device, so it is the officially supported interface rather than the Neonize linked-device protocol used by the existing `whatsapp` channel. The existing `whatsapp` channel is unchanged; both can run at once under different names. Design notes: - The poll cursor, dedup window, and creator identifier live in one atomically replaced state file. A message id is recorded before it is handled, so a crash re-reads the batch without answering twice, and the cursor is only accepted after the batch is processed. - The first poll omits `offset`, which resolves the head and never replays up to 30 days of history into an auto-replying agent. - A changed token resets the cursor, because `next_offset` is only valid for the agent that issued it. - Each API method is paced below its own rolling 60-second limit, and progress/tool-hint messages default to off because they spend the shared 12-per-minute send budget. - Retries are limited to confirmed non-delivery (`429`, `503`/`131016`). A `500` or read timeout is ambiguous, so it is not retried unless `retryAmbiguousSends` is set; a duplicate is worse than a missed reply. - Inbound media is downloaded through the shared SSRF guard, size-capped, and verified against the reported digest. Outbound media is validated before upload. - Reactions are receive-only, matching the API. The token is never logged or persisted; state stores only a SHA-256 fingerprint. Docs compare both WhatsApp channels, including the lack of end-to-end encryption, country availability, and rate limits.
104 lines
3.2 KiB
Python
104 lines
3.2 KiB
Python
"""WhatsApp Agent Platform setup validation owned by the channel package."""
|
|
|
|
from typing import Any, cast
|
|
|
|
import httpx
|
|
|
|
from nanobot.channels.contracts import ChannelValidationContext
|
|
from nanobot.channels.validation import (
|
|
check,
|
|
required_checks,
|
|
status_from_checks,
|
|
string_value,
|
|
)
|
|
from nanobot.channels.whatsapp_agent.protocol import API_BASE
|
|
|
|
_PROBE_TIMEOUT_SECONDS = 6.0
|
|
# A poll probe with timeout=0 returns immediately instead of holding a slot.
|
|
_PROBE_URL = f"{API_BASE}/updates?limit=1&timeout=0"
|
|
|
|
|
|
def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:
|
|
checks, missing = required_checks("whatsapp_agent", values)
|
|
token = string_value(values.get("token"))
|
|
if not token:
|
|
return status_from_checks("whatsapp_agent", checks, missing)
|
|
|
|
try:
|
|
response = httpx.get(
|
|
_PROBE_URL,
|
|
headers={"Authorization": f"Bearer {token}"},
|
|
timeout=_PROBE_TIMEOUT_SECONDS,
|
|
follow_redirects=False,
|
|
)
|
|
except httpx.HTTPError as exc:
|
|
checks.append(
|
|
check(
|
|
"agent_token",
|
|
"API token",
|
|
"warn",
|
|
f"Could not reach the WhatsApp Agent API now: {exc}",
|
|
)
|
|
)
|
|
return status_from_checks("whatsapp_agent", checks, missing)
|
|
|
|
code = _error_code(response)
|
|
if response.status_code == 401 or code == 190:
|
|
checks.append(
|
|
check(
|
|
"agent_token",
|
|
"API token",
|
|
"fail",
|
|
"The Authorization header was rejected. Re-copy the API key from the agent's chat.",
|
|
)
|
|
)
|
|
elif response.status_code == 400 and code == 100:
|
|
checks.append(
|
|
check(
|
|
"agent_token",
|
|
"API token",
|
|
"fail",
|
|
"WhatsApp rejected this token. Regenerate it from the agent's chat info.",
|
|
)
|
|
)
|
|
elif response.status_code in {200, 204} or response.status_code == 409:
|
|
# 409 means the token is valid but another poller is already running.
|
|
detail = (
|
|
"The token is accepted. A poller is already active for this agent; "
|
|
"keep one gateway instance per agent."
|
|
if response.status_code == 409
|
|
else "The token is accepted by the WhatsApp Agent API."
|
|
)
|
|
checks.append(check("agent_token", "API token", "pass", detail))
|
|
else:
|
|
checks.append(
|
|
check(
|
|
"agent_token",
|
|
"API token",
|
|
"warn",
|
|
f"WhatsApp returned HTTP {response.status_code} while checking the token.",
|
|
)
|
|
)
|
|
return status_from_checks("whatsapp_agent", checks, missing)
|
|
|
|
|
|
def _error_code(response: httpx.Response) -> int:
|
|
try:
|
|
payload_data: object = response.json()
|
|
except ValueError:
|
|
return 0
|
|
if not isinstance(payload_data, dict):
|
|
return 0
|
|
body = cast(dict[str, Any], payload_data)
|
|
error = body.get("error")
|
|
if not isinstance(error, dict):
|
|
return 0
|
|
raw_code = cast(dict[str, Any], error).get("code")
|
|
try:
|
|
return int(cast(Any, raw_code))
|
|
except (TypeError, ValueError):
|
|
return 0
|
|
|
|
|
|
__all__ = ["validate"]
|