The WhatsApp Cloud API adapter for pyfect.chat (Effect's
@effect/chat-whatsapp/WhatsAppChat): the Registry layer for one
business phone number, the webhook, the pure normaliser, delivery keys,
templates, read receipts and the scoped post options.
- Cloud API only. One adapter is one business phone number, and a
Registryholds one adapter per platform. - An address is
{phoneNumberId}/u/{user}, whereuseris a phone number in digits or a business-scoped user id (BSUID), such asUS.13491208655302741918.{phoneNumberId}/g/{groupId}is reserved for groups, which are not supported yet: every op on it failsInvalidRequestwith detailgroup_unsupported, and group webhooks are logged and dropped. - Inbound messages carry the BSUID form when the webhook has a BSUID, and
the phone number only when it has none. The adapter never rewrites an
address: a reply goes where the thread says.
whatsapp_update.Aliasreports a phone number and a BSUID that name one user. - A business may only write freely within 24 hours of the user's last
message. Outside it, a
postfailsForbiddenwith detailOUTSIDE_WINDOW, andsend_templateis the way to write. - The access token needs
whatsapp_business_messaging. Subscribe the app to the WhatsApp Business Account'smessagesfield.
Re-exports#
- From
pyfect.chat.chat_error:ChatError - From
pyfect.chat.chat_handler:NotAccepted - From
pyfect.chat.whatsapp:Template,WhatsAppPostOptions
Values#
| Attribute | Type | Description |
|---|---|---|
OUTSIDE_WINDOW | str | The detail of a |
Types#
| Type | Definition | Description |
|---|---|---|
OnUpdate | type OnUpdate = Callable[[WhatsAppUpdate], Effect[None, NotAccepted]] | |
Inbound | type Inbound = MessageCreated | ReactionAdded | ButtonClicked | SelectChanged | WhatsAppUpdate | What one webhook delivery holds, in order: messages and reactions, clicks, and updates. |
Classes#
Functions#
layer#
layer(*, access_token, phone_number_id, messaging_account_id=None, base_url=DEFAULT_BASE_URL, max_retry_after=None) -> Layer[WhatsAppChat | WhatsAppGraphApi, Never, HttpClient | Registry]Registers the WhatsApp adapter in the Registry, for one business
phone number, and provides WhatsAppChat and WhatsAppGraphApi.
- Capabilities:
replyTo,files,download,getThread,opener,buttonsandselects; every other op failsUnsupported. WhatsApp has no edit, sochat_markdownposts each part of a streamed reply once. - Every
postis one send, and every check runs before any upload or send.Postedmeans Meta accepted the message, not that it was delivered: a laterfailedstatus goes toon_update. - Markdown is rendered to WhatsApp's formatting (
*b*,_i_,~s~, a link aslabel (url), a heading as bold), each replacement only when it is no longer than the Markdown it replaces, so the text never grows. Anything else is sent as typed. descriptor.measureand the label limits count UTF-16 units.- Link previews are off unless
WhatsAppPostOptions(link_preview=True). - One file per post, uploaded, then sent as one media message with the
text as its caption, or as the header of reply buttons or a link
button. Refused with
TooLarge, subjectfilesand detailfile_refused, before anything is sent: more than one file, a MIME type outside Meta's table, a file past its type's size limit, audio with text or actions, text over 1,024 beside a file, and a file beside a list.text/markdownis uploaded astext/plain. - Actions: one to three buttons with labels up to 20 go as reply
buttons; a lone link button with a label up to 20 as a link button;
otherwise buttons and select options become the rows of one list, at
most ten, with labels up to 24. Other link buttons are appended to the
text as
Label: urllines. get_threadis built from the address alone, asdirect.openeris alwaysNone.messaging_account_idis sent asmessaging_account_idon every message, to say which Messaging account sends.- A rate limit is retried after Meta's
Retry-After, however long, unlessmax_retry_afteris set: a longer wait then fails the op at once withRateLimited, itsretry_afterthe wait asked for.
| Parameter | Type | Description |
|---|---|---|
access_token | Redacted[str] | |
phone_number_id | str | |
messaging_account_id | str | None = None | |
base_url | str = DEFAULT_BASE_URL | |
max_retry_after | DurationInput | None = None |
Returns Layer[WhatsAppChat | WhatsAppGraphApi, Never, HttpClient | Registry]
def layer(
*,
access_token: Redacted[str],
phone_number_id: str,
messaging_account_id: str | None = None,
base_url: str = DEFAULT_BASE_URL,
max_retry_after: DurationInput | None = None,
) -> Layer[WhatsAppChat | WhatsAppGraphApi, Never, HttpClient | Registry]:
"""Registers the WhatsApp adapter in the ``Registry``, for one business
phone number, and provides ``WhatsAppChat`` and ``WhatsAppGraphApi``.
- Capabilities: ``replyTo``, ``files``, ``download``, ``getThread``,
``opener``, ``buttons`` and ``selects``; every other op fails
``Unsupported``. WhatsApp has no edit, so ``chat_markdown`` posts each
part of a streamed reply once.
- Every ``post`` is one send, and every check runs before any upload or
send. ``Posted`` means Meta accepted the message, not that it was
delivered: a later ``failed`` status goes to ``on_update``.
- Markdown is rendered to WhatsApp's formatting (``*b*``, ``_i_``,
``~s~``, a link as ``label (url)``, a heading as bold), each
replacement only when it is no longer than the Markdown it replaces, so
the text never grows. Anything else is sent as typed.
- ``descriptor.measure`` and the label limits count UTF-16 units.
- Link previews are off unless ``WhatsAppPostOptions(link_preview=True)``.
- One file per post, uploaded, then sent as one media message with the
text as its caption, or as the header of reply buttons or a link
button. Refused with ``TooLarge``, subject ``files`` and detail
``file_refused``, before anything is sent: more than one file, a MIME
type outside Meta's table, a file past its type's size limit, audio
with text or actions, text over 1,024 beside a file, and a file beside
a list. ``text/markdown`` is uploaded as ``text/plain``.
- Actions: one to three buttons with labels up to 20 go as reply
buttons; a lone link button with a label up to 20 as a link button;
otherwise buttons and select options become the rows of one list, at
most ten, with labels up to 24. Other link buttons are appended to the
text as ``Label: url`` lines.
- ``get_thread`` is built from the address alone, as ``direct``.
``opener`` is always ``None``.
- ``messaging_account_id`` is sent as ``messaging_account_id`` on every
message, to say which Messaging account sends.
- A rate limit is retried after Meta's ``Retry-After``, however long,
unless ``max_retry_after`` is set: a longer wait then fails the op at
once with ``RateLimited``, its ``retry_after`` the wait asked for.
"""
@fx.gen
def build() -> Generator[Effect[Any, Never, Any], Any, WhatsAppChatService]:
graph = yield from WhatsAppGraphApi()
http = yield from HttpClient()
registry = yield from Registry()
adapter = WhatsAppAdapter(
graph=graph,
http=http,
access_token=access_token,
phone_number_id=phone_number_id,
messaging_account_id=messaging_account_id,
)
yield from registry.register(adapter)
return WhatsAppChatService(phone_number_id=phone_number_id, adapter=adapter)
return _layer_effect(WhatsAppChat, build).pipe(
_provide_merge(
_graph_api_layer(
access_token=access_token, base_url=base_url, max_retry_after=max_retry_after
)
)
)thread#
thread(*, phone_number_id, user) -> ChatThreadThe address of a WhatsApp user: {phoneNumberId}/u/{user}, where
user is a phone number in digits or a BSUID.
| Parameter | Type | Description |
|---|---|---|
phone_number_id | str | |
user | str |
Returns ChatThread
def thread(*, phone_number_id: str, user: str) -> ChatThread:
"""The address of a WhatsApp user: ``{phoneNumberId}/u/{user}``, where
``user`` is a phone number in digits or a BSUID."""
return _address.thread(Parts(phone_number_id, "user", user))parts#
parts(address) -> Parts | NoneThe parts of a WhatsApp address, or None for another platform's or
a malformed one. A group address, which is reserved, has kind
"group".
| Parameter | Type | Description |
|---|---|---|
address | ChatThread |
Returns Parts | None
def parts(address: ChatThread) -> Parts | None:
"""The parts of a WhatsApp address, or ``None`` for another platform's or
a malformed one. A group address, which is reserved, has ``kind``
``"group"``."""
return _address.parts(address)layer_webhook#
layer_webhook(*, path, app_secret, verify_token, on_update=None, deadline=_webhook.DEFAULT_DEADLINE, max_body_bytes=_webhook.DEFAULT_MAX_BODY_BYTES) -> Layer[Never, Never, HttpRouter | WhatsAppChat | ChatHandler | Mac]GET {path} and POST {path}: the webhook's subscription check
and its deliveries.
GETanswers Meta's check withhub.challengewhenhub.verify_tokenisverify_token(compared in constant time), and 403 otherwise.POSTreads at mostmax_body_bytes(3 MiB by default, 413; a body that can't be read is 400), checksX-Hub-Signature-256with the app secret in constant time throughMac(401), refuses a body that is not a JSON object or nests past 64 levels (400), and drops a delivery for another object or another phone number with a 200.- The updates run in order. Messages and reactions go to the
ChatHandler, clicks tochat_interaction.handle, and statuses and changed ids toon_update. A removed reaction is dropped. - A
NotAcceptedstops the delivery and answers 503, as does a request that takes longer thandeadline, 10 seconds by default. Meta then delivers the whole batch again, for up to 7 days. At the deadline the work is interrupted without waiting for its finalizers. - A click never causes a 503. It gets what is left of the deadline, less
a margin.
OpenModalgoes toHandler.refusedasUnsupported("modals"). Without achat_interaction.Handlerin the layer's context, a click is logged and dropped. - Delivery is at least once and not in order: drop repeated events with
chat_event.dedupe_key, and claimdelivery_keybefore a click's side effects.
Signature checks use Mac (pyfect.crypto.native.layer_mac).
| Parameter | Type | Description |
|---|---|---|
path | str | |
app_secret | Redacted[str] | |
verify_token | Redacted[str] | |
on_update | OnUpdate | None = None | |
deadline | DurationInput = _webhook.DEFAULT_DEADLINE | |
max_body_bytes | int = _webhook.DEFAULT_MAX_BODY_BYTES |
Returns Layer[Never, Never, HttpRouter | WhatsAppChat | ChatHandler | Mac]
def layer_webhook(
*,
path: str,
app_secret: Redacted[str],
verify_token: Redacted[str],
on_update: OnUpdate | None = None,
deadline: DurationInput = _webhook.DEFAULT_DEADLINE,
max_body_bytes: int = _webhook.DEFAULT_MAX_BODY_BYTES,
) -> Layer[Never, Never, HttpRouter | WhatsAppChat | ChatHandler | Mac]:
"""``GET {path}`` and ``POST {path}``: the webhook's subscription check
and its deliveries.
- ``GET`` answers Meta's check with ``hub.challenge`` when
``hub.verify_token`` is ``verify_token`` (compared in constant time),
and 403 otherwise.
- ``POST`` reads at most ``max_body_bytes`` (3 MiB by default, 413; a
body that can't be read is 400), checks ``X-Hub-Signature-256`` with
the app secret in constant time through ``Mac`` (401), refuses a body
that is not a JSON object or nests past 64 levels (400), and drops a
delivery for another object or another phone number with a 200.
- The updates run in order. Messages and reactions go to the
``ChatHandler``, clicks to ``chat_interaction.handle``, and statuses
and changed ids to ``on_update``. A removed reaction is dropped.
- A ``NotAccepted`` stops the delivery and answers 503, as does a request
that takes longer than ``deadline``, 10 seconds by default. Meta then
delivers the whole batch again, for up to 7 days. At the deadline the
work is interrupted without waiting for its finalizers.
- A click never causes a 503. It gets what is left of the deadline, less
a margin. ``OpenModal`` goes to ``Handler.refused`` as
``Unsupported("modals")``. Without a ``chat_interaction.Handler`` in
the layer's context, a click is logged and dropped.
- Delivery is at least once and not in order: drop repeated events with
``chat_event.dedupe_key``, and claim ``delivery_key`` before a click's
side effects.
Signature checks use ``Mac`` (``pyfect.crypto.native.layer_mac``).
"""
max_body_size = _max_body_size(max_body_bytes)
limit = from_input_unsafe(deadline)
def register(router: HttpRouterService) -> Effect[None, Never, Any]:
@fx.gen
def body() -> Generator[Effect[Any, Never, Any], Any]:
whatsapp = yield from WhatsAppChat()
handler = yield from ChatHandler()
interactions = yield from fx.service_option(Handler)
verify = yield from _webhook.make_verifier(app_secret)
phone_number_id = whatsapp.phone_number_id
options = _webhook.Options(
verify=verify,
normalize=lambda envelope: _normalize.normalize(
envelope, phone_number_id=phone_number_id
),
handle=handler.handle,
on_update=on_update,
deadline=limit,
max_body_size=max_body_size,
)
def post(request: Any) -> Effect[Any, Never, Any]:
response = _webhook.handle_request(request, options)
if interactions is None:
return response
return response.pipe(fx.provide_service(Handler, interactions.value))
yield from router.add(
"GET",
path,
lambda request: fx.succeed(_webhook.handle_verification(request, verify_token)),
)
yield from router.add("POST", path, post)
return body
return _router_use(register)normalize#
normalize(envelope, *, phone_number_id) -> list[Inbound]The normaliser, for a consumer's own transport.
- Pure: takes a parsed webhook body, gives what it holds, in order. A change for another phone number, and a group message, give nothing.
- A message's
threadis the sender's BSUID address when the webhook has one, and its phone number address otherwise;kindisdirect. Text is as the user typed it, a caption for media, and empty for a message with neither. Media are attachments, with the media id as theirid. rawof an event or a click is the change'smetadata, the sender's entry ofcontactsand the one message.message.rawis the message.- A reaction with an emoji is
ReactionAdded; a removed reaction gives nothing. - A reply button or a list row the adapter built is
ButtonClickedorSelectChanged, whosemessage_idis the message that carried it. Any other interactive reply gives nothing. - Statuses give
Status, andAliastoo when they carry both ids. Asystemmessage about a changed number or id givesUserIdChanged.
| Parameter | Type | Description |
|---|---|---|
envelope | object | |
phone_number_id | str |
Returns list[Inbound]
def normalize(envelope: object, *, phone_number_id: str) -> list[Inbound]:
"""The normaliser, for a consumer's own transport.
- Pure: takes a parsed webhook body, gives what it holds, in order. A
change for another phone number, and a group message, give nothing.
- A message's ``thread`` is the sender's BSUID address when the webhook
has one, and its phone number address otherwise; ``kind`` is
``direct``. Text is as the user typed it, a caption for media, and
empty for a message with neither. Media are attachments, with the media
id as their ``id``.
- ``raw`` of an event or a click is the change's ``metadata``, the
sender's entry of ``contacts`` and the one message. ``message.raw`` is
the message.
- A reaction with an emoji is ``ReactionAdded``; a removed reaction gives
nothing.
- A reply button or a list row the adapter built is ``ButtonClicked`` or
``SelectChanged``, whose ``message_id`` is the message that carried it.
Any other interactive reply gives nothing.
- Statuses give ``Status``, and ``Alias`` too when they carry both ids. A
``system`` message about a changed number or id gives ``UserIdChanged``.
"""
return _normalize.normalize(envelope, phone_number_id=phone_number_id)delivery_key#
delivery_key(event) -> strThe key of one delivery of a click or a reaction:
{phoneNumberId}/{messageId}, the id of the webhook message that
carried it, each part percent-encoded.
Meta redelivers a batch that was not answered in time, so a click can run again, even at the same time as the first run. Claim the key atomically, such as with an insert that fails on a duplicate, before any side effect, and skip the click when the claim fails.
| Parameter | Type | Description |
|---|---|---|
event | ButtonClicked | SelectChanged | ReactionAdded |
Returns str
def delivery_key(event: ButtonClicked | SelectChanged | ReactionAdded) -> str:
"""The key of one delivery of a click or a reaction:
``{phoneNumberId}/{messageId}``, the id of the webhook message that
carried it, each part percent-encoded.
Meta redelivers a batch that was not answered in time, so a click can run
again, even at the same time as the first run. Claim the key atomically,
such as with an insert that fails on a duplicate, before any side effect,
and skip the click when the claim fails."""
raw = _json.as_object(event.raw)
messages = _json.as_list(None if raw is None else raw.get("messages"))
id = _json.string(messages[0], "id") if messages else None
return _encode_key([_phone_number_of(event.thread), id or ""])update_key#
update_key(update) -> strThe key of an update, for dropping a redelivered one, its parts
percent-encoded and joined by /.
Status:{phoneNumberId}/status/{messageId}/{status}.UserIdChanged:{phoneNumberId}/user_changed/{id}.Alias:{phoneNumberId}/alias/{messageId}/{status}/{phone}/{userId}.
| Parameter | Type | Description |
|---|---|---|
update | WhatsAppUpdate |
Returns str
def update_key(update: WhatsAppUpdate) -> str:
"""The key of an update, for dropping a redelivered one, its parts
percent-encoded and joined by ``/``.
- ``Status``: ``{phoneNumberId}/status/{messageId}/{status}``.
- ``UserIdChanged``: ``{phoneNumberId}/user_changed/{id}``.
- ``Alias``: ``{phoneNumberId}/alias/{messageId}/{status}/{phone}/{userId}``.
"""
phone_number_id = _phone_number_of(update.thread)
match update:
case Status():
return _encode_key([phone_number_id, "status", update.message_id, update.status])
case UserIdChanged():
return _encode_key([phone_number_id, "user_changed", update.id])
case Alias():
return _encode_key(
[
phone_number_id,
"alias",
update.message_id,
update.status,
update.phone,
update.user_id,
]
)with_post_options#
with_post_options[A, E, R](options) -> Callable[[Effect[A, E, R]], Effect[A, E, R]]Scoped WhatsApp options for every write inside an effect; use with
.pipe. Nested calls merge, the inner one winning field by field.
| Parameter | Type | Description |
|---|---|---|
options | WhatsAppPostOptions |
Returns Callable[[Effect[A, E, R]], Effect[A, E, R]]
def with_post_options[A, E, R](
options: WhatsAppPostOptions,
) -> Callable[[Effect[A, E, R]], Effect[A, E, R]]:
"""Scoped WhatsApp options for every write inside an effect; use with
``.pipe``. Nested calls merge, the inner one winning field by field."""
def apply(effect: Effect[A, E, R]) -> Effect[A, E, R]:
require_effect(effect, "effect")
return CurrentPostOptions().flat_map(
lambda current: effect.pipe(
fx.provide_service(CurrentPostOptions, current.merge(options))
)
)
return applyparse_mention#
parse_mention(text) -> MentionToken | NoneWhatsApp has no mention tokens outside groups, so nothing is a
mention: for chat_test's checks and conformance suite.
| Parameter | Type | Description |
|---|---|---|
text | str |
Returns MentionToken | None
def parse_mention(text: str) -> MentionToken | None:
"""WhatsApp has no mention tokens outside groups, so nothing is a
mention: for ``chat_test``'s checks and conformance suite."""
del text
return None