Skip to content

WhatsApp: opt out on STOP, back in on START, warn in the inbox - #55

Merged
Axoineo merged 3 commits into
mainfrom
feat/stop-keyword
Nov 8, 2026
Merged

Axoineo merged 3 commits into
mainfrom
feat/stop-keyword

Conversation

@Axoineo

@Axoineo Axoineo commented Nov 8, 2026 •

Copy link
Copy Markdown
Owner

Why

Customers who reply STOP should stop getting updates, be told so, and be easy to spot for staff; a later START should make them a normal contact again. Until now a STOP was just another message in the inbox.

What changes

Worker (src/api/services/whatsapp/optKeywords.js, called from processInboundMessage):

  • An inbound message that is only STOP (any capitals, an optional . or !, typed or a quick-reply/interactive button label) sets contacts.opted_out = 1 and sends one confirmation:

    Your request to STOP receiving updates has been successfully registered.

    Please reply START if you would like to start receiving important updates on WhatsApp again. Thank you.

  • The confirmation is a free-form reply inside the 24-hour window (the customer just messaged), sent in waitUntil and recorded in the thread as an outbound message with no sender. It runs once per inbound wamid (the existing duplicate check returns early), so a redelivered webhook is not answered twice. A blocked number is opted out but gets no reply. A failed send is logged (no message text) and leaves the opt-out in place.

  • START sets opted_out = 0 and, only when that opted the person back in, replies (also kept in the chat):

    Your request to START receiving updates has been successfully registered.

    Please reply STOP if you would like to stop receiving important updates on WhatsApp. Thank you.

    A stray "Start" from someone who was never opted out gets no reply. Longer messages ("please stop calling") are left for a person.

  • Both broadcast a new conversation:opted event; older dashboard tabs ignore it.

  • The chat list query now returns ct.opted_out AS opted_out.

Inbox:

  • An Opted out tag next to the name in the chat list, Opted out · replied STOP in Contact info, and a warning above the message box. Sending is still allowed, as requested: it is a warning, not a block.

Campaigns already exclude opted-out contacts, and the app's send-to-a-number route already refuses them. No migration and no new secret.

Deploy order

  1. npm run deploy:api from this branch, so STOP/START handling goes live.
  2. Merge, which publishes the inbox warnings. Either order is safe: an older site ignores the new field and event.

Verification

  • tests/opt-keywords.test.js (9 tests): keyword matching (capitals, punctuation, buttons, longer messages), STOP through the signed webhook (opt-out, exact reply text, recorded outbound row), START (opt-in with its confirmation; none when they were not opted out), an ordinary message, a redelivered STOP, a blocked number, a failed confirmation, and opted_out on the chat list.
  • npm test: 283 of 283 pass; lint, build and the secret scan are clean; wrangler deploy --dry-run bundles the API with the new code.
  • The inbox was checked in headless Chrome against the preview harness with one chat marked opted out (desktop and phone, light and dark): chat list tag, warning above the composer, Contact info tag, composer still usable, no warning on other chats.

Not verified: a real STOP from a phone. First real check after deploying: send STOP from a test number, confirm the reply arrives and the tag appears, then send START.

Also in this PR: D1 read budget fix

On 2026-11-08 every API query started failing with D1_ERROR: Your account has exceeded D1's free tier daily row read limit, which took the inbox, the dashboard and the new STOP/START handling down until the 00:00 UTC reset. wrangler d1 insights showed one query making up 94% of reads over three days: the 10-minute cron's reconcileInbound, an unindexed NOT EXISTS scan of the whole webhook ledger (about 11,000 rows a run, ~137 runs a day). It was parked on the cron "for if the cron ever starts working"; crons now fire.

  • The routine pass reads only pending/failed message events through idx_webhook_events_status, skips anything under 10 minutes old, and marks a replayed event processed. Against SQLite the plan changes from SCAN w to SEARCH w USING INDEX idx_webhook_events_status, and only the event that needs repair is returned.
  • The full scan stays behind the manual POST /api/whatsapp/reconcile?includeProcessed=1.
  • tests/reconcile-inbound.test.js covers both paths. npm test: 285 of 285 pass.
  • Deployed to the API on 2026-11-08 with the STOP/START handling. Messages Meta could not deliver while D1 was refusing queries are redelivered by Meta and processed after the reset.

🤖 Generated with Claude Code

… the inbox

- An inbound message that is only STOP (any capitals, an optional . or !,
  typed or a button label) sets contacts.opted_out and sends one
  confirmation reply, kept in the chat with no sender: "Your request to STOP
  receiving updates has been successfully registered. Please reply START if
  you would like to start receiving important updates on WhatsApp again.
  Thank you." It runs once per inbound wamid, so a redelivered webhook is not
  answered twice, and a blocked number gets no reply.
- START opts the person back in, without a reply.
- Open inboxes hear `conversation:opted`; the chat list query carries
  opted_out. The inbox shows an "Opted out" tag in the chat list and Contact
  info and a warning above the message box. Replies are still allowed.

Campaigns already skip opted-out contacts. No migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 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-11-08T12:50:59.804599Z 34c077c 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.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Deploying dikho with  Cloudflare Pages  Cloudflare Pages

Latest commit: 446e177
Status: ✅  Deploy successful!
Preview URL: https://8014139e.dikho.pages.dev
Branch Preview URL: https://feat-stop-keyword.dikho.pages.dev

View logs

@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: 34c077c7e7

ℹ️ 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".

// 5. Re-host media in the background so the webhook can return its 200 fast.
// 5. "STOP" opts the person out (with a confirmation reply), "START" back in.
const keyword = optKeyword(m)
if (keyword) await applyOptKeyword(c, { keyword, conv })

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 Retry keyword processing after message deduplication

If this contact update fails after the inbound message row is inserted, the webhook marks the event failed and retries it; the retry hits the duplicate-message early return in processInboundMessage before reaching this call, then marks the event processed without applying STOP or sending its confirmation. Make keyword persistence retryable independently of message-row deduplication.

AGENTS.md reference: src/api/AGENTS.md:L44-L47

Useful? React with 👍 / 👎.

Comment on lines +36 to +37
`UPDATE contacts SET opted_out = ?1, updated_at = datetime('now') WHERE phone = ?2 AND opted_out <> ?1`,
).bind(optedOut, conv.phone).run()

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 Recheck opt-out status before sending queued campaign recipients

If a customer sends STOP after a campaign batch has loaded and claimed its recipients, sendToRecipients still sends from that captured list without rechecking contacts.opted_out; a recipient whose send has not started yet can therefore receive the campaign after opting out. Check current eligibility before each send or otherwise remove opted-out recipients from the queued batch.

Useful? React with 👍 / 👎.

Comment on lines +36 to +37
`UPDATE contacts SET opted_out = ?1, updated_at = datetime('now') WHERE phone = ?2 AND opted_out <> ?1`,
).bind(optedOut, conv.phone).run()

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 Order opt decisions by the inbound message timestamp

When Meta delivers inbound messages out of order, this unconditional update lets an older START overwrite a newer STOP and make the contact eligible for future campaigns; an older STOP can also override a newer START. Compare each keyword decision with the latest decision's message timestamp before applying it.

AGENTS.md reference: src/api/AGENTS.md:L30-L32

Useful? React with 👍 / 👎.

Axoineo and others added 2 commits November 8, 2026 18:22
START now replies, kept in the chat like the STOP confirmation: "You have
successfully subscribed again. You will now receive important updates from
us on WhatsApp. Reply STOP at any time to stop receiving them." Only when it
actually opted the person back in, so a stray "Start" from someone who was
never opted out gets no "subscribed again" message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
"Your request to START receiving updates has been successfully registered.
Please reply STOP if you would like to stop receiving important updates on
WhatsApp. Thank you." It mirrors the STOP confirmation, blank line included;
the trailing "again" of the draft is dropped because it reads oddly after
"stop".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Axoineo
Axoineo merged commit ff7d9d3 into main Nov 8, 2026
10 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.

1 participant