Repository navigation
WhatsApp: opt out on STOP, back in on START, warn in the inbox - #55
Conversation
… 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>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Deploying dikho with
|
| Latest commit: |
446e177
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://8014139e.dikho.pages.dev |
| Branch Preview URL: | https://feat-stop-keyword.dikho.pages.dev |
There was a problem hiding this comment.
💡 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 }) |
There was a problem hiding this comment.
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 👍 / 👎.
| `UPDATE contacts SET opted_out = ?1, updated_at = datetime('now') WHERE phone = ?2 AND opted_out <> ?1`, | ||
| ).bind(optedOut, conv.phone).run() |
There was a problem hiding this comment.
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 👍 / 👎.
| `UPDATE contacts SET opted_out = ?1, updated_at = datetime('now') WHERE phone = ?2 AND opted_out <> ?1`, | ||
| ).bind(optedOut, conv.phone).run() |
There was a problem hiding this comment.
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 👍 / 👎.
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>
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 fromprocessInboundMessage):An inbound message that is only
STOP(any capitals, an optional.or!, typed or a quick-reply/interactive button label) setscontacts.opted_out = 1and sends one confirmation:The confirmation is a free-form reply inside the 24-hour window (the customer just messaged), sent in
waitUntiland 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.STARTsetsopted_out = 0and, only when that opted the person back in, replies (also kept in the chat):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:optedevent; older dashboard tabs ignore it.The chat list query now returns
ct.opted_out AS opted_out.Inbox:
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
npm run deploy:apifrom this branch, so STOP/START handling goes live.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, andopted_outon the chat list.npm test: 283 of 283 pass; lint, build and the secret scan are clean;wrangler deploy --dry-runbundles the API with the new code.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 insightsshowed one query making up 94% of reads over three days: the 10-minute cron'sreconcileInbound, an unindexedNOT EXISTSscan 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.pending/failedmessage events throughidx_webhook_events_status, skips anything under 10 minutes old, and marks a replayed event processed. Against SQLite the plan changes fromSCAN wtoSEARCH w USING INDEX idx_webhook_events_status, and only the event that needs repair is returned.POST /api/whatsapp/reconcile?includeProcessed=1.tests/reconcile-inbound.test.jscovers both paths.npm test: 285 of 285 pass.🤖 Generated with Claude Code