GitHub

WhatsApp

Run a pyfect.chat bot on WhatsApp with the Cloud API adapter: the signed webhook, templates for the 24 hour window and the checks made before sending.

pyfect.chat.whatsapp is Effect's @effect/chat-whatsapp, the WhatsApp Cloud API adapter for Chat. whatsapp_chat.layer(access_token=..., phone_number_id=...) registers it for one business phone number and needs only an HttpClient. It calls Meta's Graph API over HTTP, with no SDK. A thread is whatsapp_chat.thread(phone_number_id=..., user=...), where user is a phone number in digits or a business-scoped user id (BSUID) such as US.13491208655302741918.

WhatsApp has no edits, deletes, history or reactions you can send, so those ops fail Unsupported, and a streamed reply posts each part once. Posts, files, downloads, reply buttons and lists work through Chat as on any adapter. Markdown becomes WhatsApp's own formatting (*bold*, _italic_, ~strike~, a link as label (url)), and each replacement is used only when it is no longer than what it replaces, so a post that fits before rendering still fits after.

There is no escape_markdown for WhatsApp, as there is for Slack, Telegram and Teams. WhatsApp has no link markup, so a link always shows its URL and text a user wrote cannot hide one, and it has no escape character: *bold* in a display name is bold in WhatsApp however it is sent. A backslash is sent as it is and shows to the user, so escaping with one only adds a \ to the message.

The webhook

whatsapp_chat.layer_webhook(path=..., app_secret=..., verify_token=...) adds two routes to an HttpRouter. GET answers Meta's subscription check with hub.challenge when hub.verify_token matches, compared in constant time, and 403 otherwise. POST takes deliveries, and every one is untrusted until its X-Hub-Signature-256 passes: an HMAC-SHA256 of the raw body with your app secret, checked in constant time through Mac (pyfect.crypto.native.layer_mac). A body over max_body_bytes (3 MiB) is answered 413 before that, a bad signature 401, and a body that is not a JSON object, or nests past 64 levels, 400.

Messages and reactions go to the ChatHandler in order, clicks on reply buttons and list rows to the chat_interaction.Handler, and delivery statuses and changed user ids to on_update. When the handler fails NotAccepted, or the request runs past deadline (10 seconds), the route answers 503 and Meta delivers the batch again. Delivery is at least once: drop repeats with chat_event.dedupe_key and whatsapp_chat.update_key, and claim whatsapp_chat.delivery_key before a click's side effects.

whatsapp_bot.py
import hashlib
import hmac
import json
from typing import Never

import pyfect as fx
from pyfect import layer
from pyfect.chat import chat, chat_handler, chat_markdown
from pyfect.chat.chat import Chat
from pyfect.chat.chat_event import ChatEvent, MessageCreated
from pyfect.chat.chat_ui import Button
from pyfect.chat.whatsapp import whatsapp_chat
from pyfect.crypto.native import layer_mac
from pyfect.http import body as http_body
from pyfect.http import client, router
from pyfect.http import request as http_request
from pyfect.http import response as http_response
from pyfect.http.request import HttpClientRequest
from pyfect.redacted import make as redacted

APP_SECRET = "6f1e0c9a2b4d4e8f9a1b2c3d4e5f6a7b"
PHONE_NUMBER_ID = "106540352242922"


# Answers every message with **bold** Markdown and two reply buttons.
def on_event(event: ChatEvent) -> fx.Effect[None, Never, Chat]:
    if not isinstance(event, MessageCreated):
        return fx.void
    actions = [Button(id="yes", label="Deploy"), Button(id="no", label="Cancel")]
    reply = chat_markdown.post(event.thread, "Deploy **docs** now?", actions=actions)
    return reply.as_void().or_die()


# The WhatsApp app: the webhook, the adapter and the handler.
app = (
    whatsapp_chat.layer_webhook(
        path="/whatsapp", app_secret=redacted(APP_SECRET), verify_token=redacted("my-token")
    )
    .pipe(layer.provide(layer.merge(chat_handler.layer(on_event), layer_mac)))
    .pipe(
        layer.provide_merge(
            whatsapp_chat.layer(access_token=redacted("EAAG-1"), phone_number_id=PHONE_NUMBER_ID)
        )
    )
    .pipe(layer.provide_merge(chat.layer))
)


# Stands in for Meta's Graph API here, printing what the bot sends.
def graph(request: HttpClientRequest) -> fx.Effect[http_response.HttpClientResponse]:
    assert isinstance(request.body, http_body.Bytes)
    sent = json.loads(request.body.body)
    interactive = sent["interactive"]
    titles = [button["reply"]["title"] for button in interactive["action"]["buttons"]]
    print("to", sent["recipient"], repr(interactive["body"]["text"]), titles)
    answer = {"messaging_product": "whatsapp", "messages": [{"id": "wamid.out1"}]}
    return fx.succeed(http_response.make(request, json.dumps(answer)))


# What Meta would send when someone writes to the number, signed with the app secret.
def delivery() -> tuple[bytes, dict[str, str]]:
    message = {
        "from": "16505551234",
        "from_user_id": "US.13491208655302741918",
        "id": "wamid.in1",
        "timestamp": "1794600000",
        "type": "text",
        "text": {"body": "deploy the docs"},
    }
    value = {
        "messaging_product": "whatsapp",
        "metadata": {"display_phone_number": "15550783881", "phone_number_id": PHONE_NUMBER_ID},
        "messages": [message],
    }
    body = json.dumps(
        {
            "object": "whatsapp_business_account",
            "entry": [{"id": "1", "changes": [{"field": "messages", "value": value}]}],
        }
    ).encode()
    signature = hmac.new(APP_SECRET.encode(), body, hashlib.sha256).hexdigest()
    return body, {"x-hub-signature-256": "sha256=" + signature}


@fx.gen
def program():
    http = yield from router.in_memory_client(app)
    check = "hub.mode=subscribe&hub.verify_token=my-token&hub.challenge=1158201444"
    subscribed = yield from http.get(f"http://localhost/whatsapp?{check}")
    print("subscription check", subscribed.status, (yield from subscribed.text))
    body, headers = delivery()
    sent = http_request.post("http://localhost").body_bytes(body, "application/json").body
    response = yield from http.post("http://localhost/whatsapp", body=sent, headers=headers)
    print("answered", response.status)
    unsigned = yield from http.post("http://localhost/whatsapp", body=sent)
    print("unsigned", unsigned.status)


fx.run_blocking(fx.scoped(program).pipe(fx.provide(client.layer_test(graph))).or_die())

The access token needs whatsapp_business_messaging. Subscribe the app to the WhatsApp Business Account's messages field.

The 24 hour window

A business may write freely only within 24 hours of the user's last message. Outside it a post fails Forbidden with detail whatsapp_chat.OUTSIDE_WINDOW, and the way to write is an approved template: WhatsAppChat().flat_map(lambda w: w.send_template(thread, Template(name=..., language="en_US"))). mark_read(thread, message_id, typing=True) marks a message read and shows the typing indicator.

Checks before sending

Every check runs before any upload or send, so a refused post sends nothing. One file per post, of a type and size Meta accepts; one to three buttons with labels up to 20 go as reply buttons, a lone link button as a link button, and anything else as the rows of one list, at most ten, with labels up to 24. Lengths count UTF-16 units, as Meta does. whatsapp_chat.with_post_options(WhatsAppPostOptions(...)) turns on link previews and names a list's button and its buttons section.

A send Meta rate limits is retried after its Retry-After, however long, and with a backoff from half a second when there is none. Pass max_retry_after to whatsapp_chat.layer, such as "1 minute", and a longer wait fails the op at once with RateLimited, its retry_after the wait Meta asked for.

Testing

whatsapp_chat.normalize(envelope, phone_number_id=...) is a pure function from a delivery's JSON to events, so captured payloads test it directly, and WhatsAppChatService.receive runs one delivery for your own transport. For writes, provide an HttpClient from pyfect.http.client.layer_test that answers like the Graph API, as the example above does. Effect's conformance suite runs against the adapter this way in pyfect's own tests.

Reference: whatsapp_chat, whatsapp_graph_api, whatsapp_update.