Skip to content

WhatsApp channel, through Meta's WhatsApp Business Cloud API - #119

Merged
Crokily merged 11 commits into
Crokily:mainfrom
GotinhaAzul:feat/whatsapp-channel
Dec 4, 2026
Merged

Crokily merged 11 commits into
Crokily:mainfrom
GotinhaAzul:feat/whatsapp-channel

Conversation

@GotinhaAzul

Copy link
Copy Markdown
Contributor

What

A WhatsApp channel, through Meta's WhatsApp Business Cloud API.

The bot gets its messages from a webhook on the page server (/channel/<bot>/whatsapp): a GET answers Meta's verification challenge with WHATSAPP_VERIFY_TOKEN, and a POST is checked with X-Hub-Signature-256, an HMAC-SHA256 of the raw body keyed with WHATSAPP_APP_SECRET. Each event is stored before the answer, so Meta sends it again when a store fails; it retries for up to 7 days.

WhatsApp has no groups or history here: every place is one person's DM with the business number. The channel translates text, images, documents, audio, video, stickers, locations, contacts, button and list replies, and reactions; a reply quotes the message it answers. It sends text (refused over 4096 characters, never cut), reactions, the typing sign (which marks the person's message read), and media, which it downloads only from Meta's hosts, with the token. A send outside the 24-hour window fails with WhatsApp's code 131047 and a sentence saying what to do; when Meta accepts a send and reports the failure later, that status webhook becomes a system event in the same DM, so the bot is told. call reaches the Graph API.

No new dependency: the channel is built on fetch, like the other adapters' platform calls.

The core change

ChannelRequest gains url (path and query) and ChannelResponse gains text, because Meta checks the webhook with a GET query and expects the challenge as plain text. The page server writes it, and the Teams playground request fills the URL in.

Tests

test/whatsapp.test.ts, 29 cases, against a fake Graph API (test/support/whatsapp.ts) and webhook deliveries in Meta's shape: the verification challenge and a wrong token, signatures on the raw bytes (unicode escaped or not; another scheme, extra hex or none refused), store-before-answer and Meta's redelivery, a delivery for another number of the same app left to that number's channel, failed delivery statuses, every message kind (text, reply, reaction added and removed, image with caption, sticker, location, button reply, number change, form reply, unknown type), a wamid that holds a slash, the send payload and its reply context, Markdown written as WhatsApp's with a fenced block left alone, a message sent with call stored as the bot's own, the 4096-character limit, reactions, the typing sign, media only from Meta's hosts over HTTPS, and the start errors (no page server, a token Meta does not accept, never printed).

$ npm run check
> tsc --noEmit
(no errors)

$ TMPDIR=/var/tmp/ether-tests npm test
 Test Files  49 passed (49)
      Tests  755 passed | 4 skipped (759)
   Duration  167.41s

The 4 skips are the existing ones (two Microsoft 365 Agents Playground tests, two real-cloudflared tests). npm run tla was not run: no inbox, waker, outbox, timer or model-wait code changed.

Not yet

  • Not tested against a live Meta app; the payload shapes are Meta's documented ones.
  • No automatic template when the 24-hour window is closed: the send fails and says so. A template needs an approved template and its parameters, so that is a change of its own.
  • No backfill (the API has no history) and no findSent (no search by an ID of the bot's own).
  • Sending a file needs a public link or an uploaded media ID; call sends JSON only, so no upload.
  • WhatsApp charges per delivered message after a free allowance of 1,000 service messages a month per business phone number; the whatsapp-channel skill says so and links Meta's pricing page. The README marks the channel as tested against a fake API, not live.

A platform that checks a webhook with a GET reads its query, and one that
answers a challenge sends text, not JSON: WhatsApp's Meta callback needs both.
The page server passes the request's URL along, and writes a ChannelResponse's
text as it is. Teams' playground request fills the URL in.
A webhook on the page server, checked with the verify token and the app secret's
X-Hub-Signature-256; each message is stored before the answer, so Meta's delivery
comes again when a store fails. One DM per person, as WhatsApp has no groups
here: text, images, documents, audio, video, stickers, locations, contacts and
reactions, with a reply quoting what it answers, the typing sign, and media
downloaded only from Meta's hosts. A text over 4096 characters is refused before
the outbox records the send, never cut; a send outside the 24-hour window fails
with WhatsApp's code and a sentence saying what to do. The whatsapp-channel skill
says how to make the Meta app and connect it.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-03T21:07:39.394371Z 67f5218 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 67f5218cf5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/channels/whatsapp/index.ts Outdated
Comment on lines +281 to +284
const emoji = message.reaction.emoji ?? "";
const reacted = message.reaction.message_id;
if (!reacted) return [];
return [{ ...base, kind: emoji ? "reaction_added" : "reaction_removed", message: this.message(phoneNumberId, wa, reacted), text: emoji }];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reconcile reaction removals and replacements before logging them

When a person clears a reaction, this emits reaction_removed with an empty emoji; replacing a reaction emits only another addition. However, MessageLog.reactions() in src/gateway/log.ts:437-442 matches removals by message, emoji and person. Replaying an addition followed by removal therefore leaves the original emoji active, while replacing 👍 with 👎 reports both. Normalize WhatsApp's single-reaction state in the adapter into matching removal/addition events so the common reaction reducer can reconstruct the actual state.

AGENTS.md reference: AGENTS.md:L6-L6

Useful? React with 👍 / 👎.

Comment thread skills/whatsapp-channel/SKILL.md Outdated
React with `react`, a message address and an emoji: WhatsApp keeps one reaction per person per message, and an empty emoji takes it away. Names such as `:eyes:` are not resolved here; use the emoji itself.

WhatsApp takes at most three reply buttons on a message, and they are sent with `call` as an interactive message:
`call whatsapp messages {"to": "5511999999999", "type": "interactive", "interactive": {"type": "button", "body": {"text": "Where should we deploy?"}, "action": {"buttons": [{"type": "reply", "reply": {"id": "deploy:test", "title": "Test"}}, {"type": "reply", "reply": {"id": "deploy:prod", "title": "Production"}}]}}}`

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include the required product in the skill's message payloads

When the agent follows this reply-button example or the document-send example above, the request omits messaging_product: "whatsapp", which the Graph API's messages endpoint requires. WhatsAppChannel.call() forwards these parameters unchanged to #graph, so the documented requests are rejected rather than sending buttons or files. Include the required field in both examples, or supply it in the adapter.

Useful? React with 👍 / 👎.

Comment on lines +375 to +378
const id = answer?.messages?.[0]?.id;
// A reaction or a read mark answers with no message ID: only a message is stored.
if (phone && to && id) {
const sent = { id, to: this.message(phone, to, id), text: sentText(params), at: Date.now() };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude reactions from the call sent-message path

When a script sends a reaction through call, WhatsApp also returns a messages[0].id; that ID does not mean a new chat message was posted. This condition consequently stores a synthetic [reaction message] as a normal outgoing message, polluting gw_messages and triggering the inbox's ownMessage notification. The fake API's {success: true} reaction response hides this case. Classify the operation by its request type in the adapter instead of treating every returned ID as a posted message.

AGENTS.md reference: AGENTS.md:L6-L6

Useful? React with 👍 / 👎.

…loads

A new emoji on a message takes the old one away first, as the log keeps one
reaction per emoji; a reaction sent with `call` is no longer stored as a posted
message; the skill's examples carry `messaging_product`, and its link points at
the current API page. The tests share one helper for the page server and the
channel, which takes 18 lines off the test file.
@GotinhaAzul

Copy link
Copy Markdown
Contributor Author

@Crokily the macOS leg never acquired a runner again: job 144658509920 waited 15m01s with no runner and no steps, then was cancelled — "The job was not acquired by Runner of type hosted even after multiple attempts" (macOS arm64 capacity).

Ubuntu and Windows are green on 5886c1b. Could you re-run the macOS job, or merge with that leg red as with #121?

…lace, every number of the app, and a preview

- A person is their BSUID (from_user_id, user_id, recipient_user_id), the phone number only where WhatsApp gives
  none; sends, replies and reactions go to a BSUID with "recipient". A person with a username, whose webhook has no
  "from", had every such person in one DM ".../undefined" and replies went to "undefined".
- A replaced or removed reaction is taken away in the log: the channel keeps each message's emoji in its state file
  (channels/<id>.json, owner-only), also across a restart and a second translation; the log's raws it read before hold
  no reactions. A late older reaction is dropped.
- A message for another number of the same Meta app is kept and answered from that number, as Meta sends it nowhere
  else; the gateway's output says so once. The skill says how to give another bot's number a callback of its own.
- A changed number's notice goes to the person's old DM and names the new one.
- *italic* is sent as WhatsApp's _italic_, not bold.
- README and docs/for-agents.md call WhatsApp a preview; README and the skill say what Meta's AI Providers terms allow.
…"to" first, presses on their message, raw in the log

From one Codex review round (GPT-6.2 Astra), the findings that hold:
- The page server takes a channel request of up to 4 MB: Meta's webhooks are up to 3 MB, and one over 1 MB was
  refused with 413 on every retry for 7 days. Tested through the real page server, with the challenge as plain text.
- A send to a person goes from the number they wrote to, when that is another number of the app.
- A message sent with call to both "to" and "recipient" is stored where WhatsApp sends it, "to"; a messages path
  with a query is still stored.
- A button, list or template button press is about the message with the buttons, with its title and ID; a Flow's
  answers come as a form.
- A lone contact is given only to a lone message; the bot's quoted reply keeps what it answers.
- Every happening carries the platform's data (raw), as on the other channels.
- A file download is tested against a CDN host, with redirects refused.
@Crokily

Crokily commented Dec 4, 2026

Copy link
Copy Markdown
Owner

Thanks, and sorry for the wait. We're taking it from here so it can go out soon: we're adding a few fixes on top of your commits (users with a username who come only with a BSUID, reaction replace and remove, messages for other numbers of the same Meta app) and testing it live against Meta's test number. Your commits stay as they are. Before we merge, we'll explain each change here.

…number needs, and the subscribed app in the skill

Live on Meta's test number, a reply to a person's BSUID alone failed with 131030 "Recipient phone number not in
allowed list", though their number was on the list: the test number's list holds phone numbers. The channel now keeps
each person's phone number with their BSUID when a webhook gives both (state file), and sends and reacts with "to"
and "recipient" (WhatsApp takes "to"), the BSUID alone when no number is known. A failed status that names only the
phone number, and a call to it, land in the BSUID's DM. The skill says that the app must be subscribed to the WhatsApp
account (no message came until then), and that Meta refuses "WhatsApp" in an app's name.
…ed, and that sending needs a verified business
@Crokily

Crokily commented Dec 4, 2026

Copy link
Copy Markdown
Owner

Thanks again for this, @GotinhaAzul. The channel is clean and fits Pots well, and your quick answers to the Codex comments helped. As said above, we finished it here so it can go out with our next release. Your commits are unchanged; ours are on top (21c8fb9, 98648fd, 7725737, d88f15a, and a merge of main). Here is each change and why.

1. People with a username (BSUID). Since April 2026 Meta sends from_user_id (the business-scoped user ID) in every messages webhook, and leaves out from for a person with a username unless the business talked with that number in the last 30 days (BSUID docs). With from missing, every such person landed in one place whatsapp:#<id>/undefined, and replies went to "to": "undefined".

  • A person is now keyed by the BSUID (from_user_id, contacts[].user_id, recipient_user_id); the phone number only when WhatsApp gives no BSUID.
  • Live on Meta's test number, a reply to a BSUID alone failed with 131030 ("not in allowed list"), because the test number's list holds phone numbers. So the channel keeps each person's phone number with their BSUID (state file) and sends and reacts with both to and recipient (WhatsApp takes to); recipient alone when no number is known. A failed status that names only the phone number lands in the BSUID's DM.
  • A changed number (system message user_changed_number / user_changed_user_id) is a notice in the person's old DM, naming the new one.
  • The contact (name, username) is matched to its message by BSUID or phone; a lone contact goes only to a lone message.

2. Replaced and removed reactions. #previousReaction read earlier reactions through sink.logged(), which reads gw_messages only. Reactions live in gw_events, so in a real gateway it never found one, and a replaced emoji stayed next to the new one. (The test passed because its fake logged returned a reaction.) The adapter now keeps each message's current emoji in its state file (channels/<id>.json, as wechat and feishu do) and gives the log a removal of the old emoji. This holds after a restart and when an event is translated twice after a crash, and a late older reaction is dropped. A test runs it against the real MessageLog reducer, and the live test showed 👍 → ❤️ → none right in the log.

3. Other numbers of the same Meta app. A Meta app's callback gets the messages of every number of the app that has no callback of its own, so a message for another number was acknowledged and lost. It is now kept and answered from the number it came to (the address already holds it), and a send to a person goes from the number they wrote to. The skill shows how to give another bot's number its own callback override.

4. Smaller fixes

  • The page server takes channel requests up to 4 MB: Meta's webhooks can be 3 MB, and those over 1 MB got 413 on every retry. Tested through the real page server, with the challenge answered as plain text.
  • Button, list and template-button presses are about the message with the buttons, with the button's ID; a Flow's answers come as a form.
  • Every happening carries the platform's data (raw), as on the other channels.
  • call with both to and recipient is stored where WhatsApp sends it; a /messages path with a query is still stored.
  • Markdown *italic* is sent as WhatsApp's _italic_ (it showed bold).
  • The bot's quoted reply keeps what it answers in the log.

5. Docs and skill. WhatsApp stays a preview, with rows in the README's Channels tables. README and the skill say what Meta's terms allow: since 15 January 2026 the WhatsApp Business Solution Terms bar general-purpose AI assistants from the Business Platform, except for users in the EEA, Brazil and Türkiye; a business's bot for its own customers is fine. The skill adds what the live setup needed: the app must be subscribed to the WhatsApp account (POST /<WABA ID>/subscribed_apps) or no message comes, Meta refuses "WhatsApp" in an app's name, the dashboard's Test button uses a phone number ID that is not yours, and a new business can send only once Meta has verified it.

Live test on Meta's free test number with a real WhatsApp account: Meta's webhook check, signature checks, text, a picture and a PDF downloaded, reactions added, replaced and removed, quote replies, the typing sign (with read ticks), people keyed by BSUID, a message sent while the gateway was down arriving when Meta sent it again, and a failed send shown in the person's DM all worked. The bot's messages, reactions and buttons were taken by the API but not delivered: Meta now lets a new business portfolio send only after business verification (131031, "Business Account locked"). So delivery is the one part still untested, and the README says so.

Checks: your tests pass (a few expectations changed with the behaviour above), plus new ones from Meta's documented payloads and the live payload's shape; npm run check and the full suite pass; CI passed on Linux, macOS and Windows; one Codex review round, with its real points fixed.

@Crokily
Crokily merged commit 9e09420 into Crokily:main Dec 4, 2026
11 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants