Skip to content

Commit 4e431db

Browse files
authored
Merge pull request #370 from Tanzania-AI-Community/feat/local-whatsapp-transport
feat: add local WhatsApp transport
2 parents 44da26d + 6244c1d commit 4e431db

8 files changed

Lines changed: 365 additions & 9 deletions

‎.env.template‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ DATABASE_URL=
3737
ENVIRONMENT="local"
3838
DEBUG=True
3939
MOCK_WHATSAPP=True # Set to True if you want to use the mock WhatsApp API and not the real WhatsApp API
40+
MOCK_WHATSAPP_API_URL=http://127.0.0.1:3000/api/whatsapp
41+
MOCK_WHATSAPP_TOKEN=change-me-local-token
4042
BUSINESS_ENV=False # Set to True if you want to use WhatsApp Flows in a verified business account
4143

4244

‎.env.template.simple‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ DATABASE_URL=postgresql://postgres:mysecurepassword@127.0.0.1:5432/twiga_db
2929
ENVIRONMENT="local"
3030
DEBUG=True
3131
MOCK_WHATSAPP=True
32+
MOCK_WHATSAPP_API_URL=http://127.0.0.1:3000/api/whatsapp
33+
MOCK_WHATSAPP_TOKEN=change-me-local-token
3234
BUSINESS_ENV=False
3335

3436
# Meta API credentials

‎app/clients/whatsapp_client.py‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import httpx
99
from fastapi import Request
10+
from fastapi.encoders import jsonable_encoder
1011
from fastapi.responses import JSONResponse, PlainTextResponse
1112

1213
import app.database.db as db
@@ -48,20 +49,22 @@ class WhatsAppClient:
4849
_MAX_TEXT_LENGTH_CHARS = 4096
4950

5051
def __init__(self):
52+
token = settings.whatsapp_api_token.get_secret_value()
53+
self.url = f"https://graph.facebook.com/{settings.meta_api_version}/{settings.whatsapp_cloud_number_id}"
54+
if settings.mock_whatsapp:
55+
assert settings.mock_whatsapp_api_url and settings.mock_whatsapp_token
56+
self.url = settings.mock_whatsapp_api_url.rstrip("/")
57+
token = settings.mock_whatsapp_token.get_secret_value()
5158
self.headers = {
5259
"Content-type": "application/json",
53-
"Authorization": f"Bearer {settings.whatsapp_api_token.get_secret_value()}",
60+
"Authorization": f"Bearer {token}",
5461
}
55-
self.url = f"https://graph.facebook.com/{settings.meta_api_version}/{settings.whatsapp_cloud_number_id}"
5662
self.logger = logging.getLogger(__name__)
5763
self.client = httpx.AsyncClient(base_url=self.url)
5864

5965
async def send_message(
6066
self, wa_id: str, message: str, options: list[str] | None = None
6167
) -> bool:
62-
if settings.mock_whatsapp:
63-
return True
64-
6568
i, total = 0, 0
6669
try:
6770
# Margin: Meta may count emoji as 2 chars (UTF-16 units)
@@ -73,8 +76,14 @@ async def send_message(
7376
payload: dict[str, Any] = generate_payload(
7477
wa_id, chunk, options if i == total else None
7578
)
79+
# The local mock reads JSON; Meta keeps its existing form encoding
80+
body = (
81+
{"json": jsonable_encoder(payload)}
82+
if settings.mock_whatsapp
83+
else {"data": payload}
84+
)
7685
response = await self.client.post(
77-
"/messages", data=payload, headers=self.headers
86+
"/messages", headers=self.headers, **body
7887
)
7988

8089
log_httpx_response(response)
@@ -109,9 +118,6 @@ async def send_read_receipt_with_typing_indicator(self, message_id: str) -> None
109118
110119
https://developers.facebook.com/documentation/business-messaging/whatsapp/typing-indicators/
111120
"""
112-
if settings.mock_whatsapp:
113-
return
114-
115121
if not message_id:
116122
self.logger.warning(
117123
"Skipping WhatsApp typing indicator because inbound message id is empty."

‎app/config.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import os
66
from enum import Enum
77
from typing import Optional
8+
from urllib.parse import urlsplit
89

910
from pydantic import BaseModel, Field, SecretStr, field_validator, model_validator
1011
from pydantic_settings import BaseSettings, SettingsConfigDict
@@ -56,6 +57,7 @@ class Settings(BaseSettings):
5657
extra="ignore",
5758
case_sensitive=False,
5859
env_nested_delimiter="__",
60+
hide_input_in_errors=True,
5961
)
6062
""" REQUIRED SETTINGS """
6163
# Meta settings
@@ -70,6 +72,8 @@ class Settings(BaseSettings):
7072

7173
# WhatsApp mock
7274
mock_whatsapp: bool = False
75+
mock_whatsapp_api_url: Optional[str] = None
76+
mock_whatsapp_token: Optional[SecretStr] = None
7377

7478
# Message limiting settings
7579
message_character_limit: int = 65000
@@ -116,6 +120,32 @@ def parse_business_env(cls, v):
116120
return v.lower() in ("true", "True")
117121
return False
118122

123+
@model_validator(mode="after")
124+
def validate_mock_transport(self):
125+
if not self.mock_whatsapp:
126+
return self
127+
if self.environment not in (Environment.LOCAL, Environment.DEVELOPMENT):
128+
raise ValueError(
129+
"Mock WhatsApp requires a local or development environment"
130+
)
131+
url = urlsplit(self.mock_whatsapp_api_url or "")
132+
if (
133+
url.scheme != "http"
134+
or url.hostname
135+
not in ("localhost", "127.0.0.1", "::1", "host.docker.internal")
136+
or url.username
137+
or url.password
138+
or url.query
139+
or url.fragment
140+
):
141+
raise ValueError("MOCK_WHATSAPP_API_URL must be a local HTTP URL")
142+
if (
143+
not self.mock_whatsapp_token
144+
or not self.mock_whatsapp_token.get_secret_value().strip()
145+
):
146+
raise ValueError("MOCK_WHATSAPP_TOKEN is required in mock mode")
147+
return self
148+
119149

120150
class LLMSettings(BaseSettings):
121151
model_config = SettingsConfigDict(

‎docs/en/MOCK_WHATSAPP_GETTING_STARTED.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,28 @@ git clone https://github.com/Tanzania-AI-Community/mock-whatsapp.git
7171

7272
2. Navigate to the mock WhatsApp directory and follow the README instructions to install dependencies and start the server.
7373

74+
3. Configure the outgoing text receiver in Twiga's environment:
75+
76+
```dotenv
77+
MOCK_WHATSAPP=True
78+
MOCK_WHATSAPP_API_URL=http://127.0.0.1:3000/api/whatsapp
79+
MOCK_WHATSAPP_TOKEN=change-me-local-token
80+
```
81+
82+
Set the same local token in the mock's environment, along with `CHATBOT_CALLBACK_URL=http://127.0.0.1:8000/devhooks`. Keep the placeholder Meta values from the simple template; real Meta credentials are not needed.
83+
84+
The mock displays accepted outgoing text, individual chunks, progress notifications, read receipts, and typing actions. Its local event log survives restarts. Media and interactive messages are not supported yet. Observer mode remains a separate read-only database view.
85+
86+
When Twiga runs in Docker, try `http://host.docker.internal:3000/api/whatsapp` for the receiver URL. Host loopback connectivity depends on the Docker platform; verify that the container can reach the mock without exposing the host listener publicly.
87+
88+
To run the transport integration test, start the mock with a temporary event directory and `CHATBOT_CALLBACK_URL=http://127.0.0.1:1/devhooks`, then run:
89+
90+
```sh
91+
MOCK_WHATSAPP_TEST_URL=http://127.0.0.1:3000 uv run pytest tests/integration/test_mock_whatsapp_transport.py
92+
```
93+
94+
This test uses the actual WhatsApp client and mock receiver, without model calls or database queries.
95+
7496
## 🖥️ Run the FastAPI application
7597

7698
Run the following command to run the project:
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import json
2+
3+
import httpx
4+
import pytest
5+
from pydantic import SecretStr
6+
7+
from app.clients.whatsapp_client import WhatsAppClient
8+
from app.config import settings
9+
from app.utils.whatsapp_utils import generate_payload
10+
11+
12+
def use_mock(monkeypatch, enabled=True):
13+
monkeypatch.setattr(settings, "mock_whatsapp", enabled)
14+
monkeypatch.setattr(
15+
settings, "mock_whatsapp_api_url", "http://127.0.0.1:3100/api/whatsapp"
16+
)
17+
monkeypatch.setattr(settings, "mock_whatsapp_token", SecretStr("local-token"))
18+
19+
20+
async def send_with(client, receive, *args):
21+
await client.client.aclose()
22+
async with httpx.AsyncClient(
23+
base_url=client.url, transport=httpx.MockTransport(receive)
24+
) as transport:
25+
client.client = transport
26+
return await client.send_message(*args)
27+
28+
29+
async def test_production_keeps_meta_destination_and_form_encoding(monkeypatch):
30+
use_mock(monkeypatch, enabled=False)
31+
client = WhatsAppClient()
32+
requests = []
33+
34+
def receive(request):
35+
requests.append(request)
36+
return httpx.Response(200)
37+
38+
assert await send_with(client, receive, "255700000001", "Hello 🦒")
39+
request = requests[0]
40+
expected = httpx.Request(
41+
"POST", "https://x", data=generate_payload("255700000001", "Hello 🦒")
42+
)
43+
assert request.content == expected.content
44+
assert request.url.host == "graph.facebook.com"
45+
assert (
46+
request.url.path
47+
== f"/{settings.meta_api_version}/{settings.whatsapp_cloud_number_id}/messages"
48+
)
49+
assert (
50+
request.headers["authorization"]
51+
== f"Bearer {settings.whatsapp_api_token.get_secret_value()}"
52+
)
53+
54+
55+
async def test_mock_sends_json_to_the_local_receiver(monkeypatch):
56+
use_mock(monkeypatch)
57+
client = WhatsAppClient()
58+
requests = []
59+
60+
def receive(request):
61+
requests.append(request)
62+
return httpx.Response(200, json={"messages": [{"id": "wamid.test"}]})
63+
64+
assert await send_with(client, receive, "255700000001", "Hello 🦒")
65+
assert await send_with(client, receive, "1", "Select", ["a", "b", "c", "d"])
66+
request = requests[0]
67+
assert str(request.url) == "http://127.0.0.1:3100/api/whatsapp/messages"
68+
assert request.headers["authorization"] == "Bearer local-token"
69+
assert json.loads(request.content) == generate_payload("255700000001", "Hello 🦒")
70+
assert json.loads(requests[1].content)["type"] == "interactive"
71+
72+
73+
@pytest.mark.parametrize("reject_second", [False, True])
74+
async def test_long_text_preserves_chunks_and_stops_on_rejection(
75+
monkeypatch, reject_second
76+
):
77+
use_mock(monkeypatch)
78+
client = WhatsAppClient()
79+
chunks = []
80+
81+
def receive(request):
82+
chunks.append(json.loads(request.content)["text"]["body"])
83+
return httpx.Response(429 if reject_second and len(chunks) == 2 else 200)
84+
85+
sent = await send_with(client, receive, "255700000001", "x" * 9001)
86+
assert sent is not reject_second
87+
assert [len(chunk) for chunk in chunks] == (
88+
[4000, 4000] if reject_second else [4000, 4000, 1001]
89+
)
90+
91+
92+
async def test_mock_read_receipt_and_typing_use_the_same_transport(monkeypatch):
93+
use_mock(monkeypatch)
94+
client = WhatsAppClient()
95+
await client.client.aclose()
96+
requests = []
97+
98+
def receive(request):
99+
requests.append(request)
100+
return httpx.Response(200)
101+
102+
async with httpx.AsyncClient(
103+
base_url=client.url, transport=httpx.MockTransport(receive)
104+
) as transport:
105+
client.client = transport
106+
await client.send_read_receipt_with_typing_indicator("wamid.inbound")
107+
await client.send_read_receipt_with_typing_indicator("")
108+
assert len(requests) == 1
109+
assert json.loads(requests[0].content) == {
110+
"messaging_product": "whatsapp",
111+
"status": "read",
112+
"message_id": "wamid.inbound",
113+
"typing_indicator": {"type": "text"},
114+
}
115+
116+
117+
@pytest.mark.parametrize("failure", [httpx.ConnectError, httpx.ReadTimeout])
118+
async def test_transport_errors_return_false_without_retry(monkeypatch, failure):
119+
use_mock(monkeypatch)
120+
client = WhatsAppClient()
121+
attempts = 0
122+
123+
def receive(request):
124+
nonlocal attempts
125+
attempts += 1
126+
raise failure("Simulated local failure", request=request)
127+
128+
assert not await send_with(client, receive, "255700000001", "Hello")
129+
assert attempts == 1
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import asyncio
2+
import os
3+
from urllib.parse import urlsplit
4+
from uuid import uuid4
5+
6+
import httpx
7+
import pytest
8+
9+
from app.clients.whatsapp_client import WhatsAppClient
10+
from app.config import settings
11+
12+
pytestmark = [
13+
pytest.mark.integration,
14+
pytest.mark.skipif(
15+
not os.getenv("MOCK_WHATSAPP_TEST_URL"),
16+
reason="Start the local mock and set MOCK_WHATSAPP_TEST_URL",
17+
),
18+
]
19+
20+
21+
async def test_text_transport_with_local_mock(monkeypatch):
22+
origin = os.environ["MOCK_WHATSAPP_TEST_URL"].rstrip("/")
23+
url = urlsplit(origin)
24+
assert url.scheme == "http" and url.hostname in ("127.0.0.1", "localhost", "::1")
25+
assert not url.username and not url.password and not url.query and not url.fragment
26+
assert settings.mock_whatsapp_token
27+
recipient = f"2557{int(uuid4().hex[:8], 16):010d}"
28+
message_id = f"wamid.integration.{uuid4().hex}"
29+
monkeypatch.setattr(settings, "mock_whatsapp", True)
30+
monkeypatch.setattr(settings, "mock_whatsapp_api_url", f"{origin}/api/whatsapp")
31+
client = WhatsAppClient()
32+
token = settings.mock_whatsapp_token.get_secret_value()
33+
try:
34+
async with httpx.AsyncClient(base_url=origin, trust_env=False) as mock:
35+
seeded = await mock.post(
36+
"/api/inbound",
37+
headers={"Origin": origin},
38+
json={
39+
"body": "help",
40+
"recipientId": recipient,
41+
"messageId": message_id,
42+
},
43+
)
44+
assert (
45+
seeded.status_code == 502
46+
), "Run the mock with CHATBOT_CALLBACK_URL=http://127.0.0.1:1/devhooks"
47+
await client.send_read_receipt_with_typing_indicator(message_id)
48+
assert await client.send_message(recipient, "Working...")
49+
assert await client.send_message(recipient, "x" * 9001)
50+
configured = await mock.put(
51+
"/api/whatsapp/faults",
52+
headers={"Authorization": f"Bearer {token}"},
53+
json={
54+
"rule": {
55+
"target": "text",
56+
"recipientId": recipient,
57+
"skip": 1,
58+
"status": 429,
59+
}
60+
},
61+
)
62+
configured.raise_for_status()
63+
assert not await client.send_message(recipient, "y" * 9001)
64+
assert all(
65+
await asyncio.gather(
66+
client.send_message(recipient, "first"),
67+
client.send_message(recipient, "second"),
68+
)
69+
)
70+
response = await mock.get("/api/events", params={"recipientId": recipient})
71+
response.raise_for_status()
72+
events = response.json()["events"]
73+
finally:
74+
await client.client.aclose()
75+
outgoing = [event for event in events if event["kind"] == "outgoing"]
76+
bodies = [event["payload"]["text"]["body"] for event in outgoing]
77+
assert bodies[:5] == ["Working...", "x" * 4000, "x" * 4000, "x" * 1001, "y" * 4000]
78+
assert set(bodies[5:]) == {"first", "second"}
79+
assert len({event["messageId"] for event in outgoing}) == len(outgoing)
80+
assert len([event for event in events if event["kind"] == "rejected"]) == 1
81+
assert any(
82+
event["kind"] == "action" and event["payload"]["message_id"] == message_id
83+
for event in events
84+
)

0 commit comments

Comments
 (0)