Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

replybots is an automated WhatsApp reply platform for small businesses, built as a single Cloudflare Worker in Rust (WebAssembly) with an Elm frontend and Cloudflare D1 for all persistent state.

It supports two reply modes per WhatsApp Business number:

  • Static reply — send a fixed message immediately or after a short burst wait.
  • AI quick-handoff — a single built-in front-desk persona answers greetings and simple questions briefly, then hands the conversation to a human the moment pricing, commitments, or custom requests come up.

Key Properties

  • D1-only state — all tenants, sessions, WhatsApp accounts, conversation state, inbound burst buffers, rate limits, metadata logs, and billing records live in a single Cloudflare D1 SQLite database.
  • Metadata-only logging — inbound and outbound message text passes through in memory and is never persisted to D1.
  • Strict prepaid billing — 1 credit = 1 reply (static or AI), powered by Razorpay Orders and fail-closed webhooks.

Self-hosting

replybots runs on Cloudflare Workers with D1, Workers AI, and Cloudflare Email Routing (send_email).

1. Prerequisites

  • Cloudflare account with Workers, D1, and Workers AI enabled
  • Meta App with WhatsApp Business API & Embedded Signup configured
  • Razorpay account (for prepaid credit top-ups)

2. Create the D1 Database & Apply Migrations

wrangler d1 create replybots

Update database_id in wrangler.toml, then apply the schema migration:

wrangler d1 execute replybots --remote --file migrations/0001_create_schema.sql

3. Configure Environment Variables & Secrets

Set runtime variables at deploy time (or in wrangler.toml):

  • PUBLIC_BASE_URL — e.g. https://replybots.io
  • EMAIL_DOMAIN — domain for outbound handoff alert emails (e.g. replybots.io)
  • WHATSAPP_WABA_ID — fallback WhatsApp Business Account ID
  • WHATSAPP_SIGNUP_CONFIG_ID — Meta Embedded Signup configuration ID

Set secrets via wrangler secret put:

  • WHATSAPP_ACCESS_TOKEN, WHATSAPP_VERIFY_TOKEN
  • META_APP_ID, META_APP_SECRET
  • RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET, RAZORPAY_WEBHOOK_SECRET

See Bindings & Environment for the full list extracted from wrangler.toml and src/.

4. Configure Webhooks

  • Meta WhatsApp webhook: point to <PUBLIC_BASE_URL>/webhook/whatsapp with your WHATSAPP_VERIFY_TOKEN.
  • Meta data deletion callback: point to <PUBLIC_BASE_URL>/data-deletion.
  • Razorpay webhook: point to <PUBLIC_BASE_URL>/webhook/razorpay using RAZORPAY_WEBHOOK_SECRET.

5. Build & Deploy

npm ci
npm run build:frontend
wrangler deploy

Local Development

Set DEV_MODE=1 to stub Workers AI / safety checks and enable POST /auth/dev-login without Meta OAuth:

node scripts/test-server.mjs

scripts/test-server.mjs applies migrations/ to local D1 and starts wrangler dev --local with DEV_MODE=1.

Architecture

replybots compiles to a single WebAssembly Worker (src/lib.rs) paired with static assets (public/) served from Cloudflare’s edge.

D1-Only State

All persistent state is stored in Cloudflare D1 (migrations/0001_create_schema.sql):

  • No KV, no Durable Objects, no Queues — burst debouncing, conversation sessions, rate limits, and billing ledgers all use atomic D1 queries.
  • Metadata-only messages table — stores channel, direction, sender, recipient, action_taken, conversation_id, and created_at, never message bodies.

Inbound Reply Pipeline

  1. Webhook verification & dispatch (src/handlers/webhook.rs) — verifies X-Hub-Signature-256 with META_APP_SECRET and parses inbound WhatsApp events.
  2. Burst debounce (pending_inbound) — buffers rapid consecutive customer messages for the configured wait_seconds (0–30s) so multiple short texts receive a single coherent reply.
  3. Prompt-injection screening (src/ai.rs) — runs @cf/meta/prompt-guard-2-86m on inbound text.
  4. Reply generation (src/ai.rs) — in AI mode, calls @cf/meta/llama-4-scout-17b-16e-instruct with the single built-in core persona and recent conversation context (conversation_sessions).
  5. Safety & risk gate (src/safety.rs, src/risk.rs) — vets output via @cf/meta/llama-guard-3-8b and risk::signal checks (unauthorized prices, commitments, or [[HANDOFF]] markers).
  6. Handoff & escalation (src/escalations.rs) — when handed off, sends a holding reply, puts the thread into handoff_cooldown_mins, and optionally sends an alert email via Cloudflare send_email.

Extending Channels

Outbound delivery and channel metadata are abstracted behind the Channel trait (src/channel/), allowing additional channels (such as Discord or Telegram) to plug into the same pipeline and D1 tables.

Billing

replybots uses strict prepaid credits:

  • 1 credit = 1 reply (whether static or AI-generated).
  • No subscriptions, no free trials — accounts start with 0 credits and top up via Razorpay Orders.
  • No charge on held or failed replies — if the risk gate withholds a draft or AI generation / delivery fails before sending, no credit is deducted.
  • Purchased credits do not expire.

Payment Flow

  1. Order creation (POST /api/billing/order) — creates a Razorpay Order for the requested credit count (between minCredits and maxCredits) in the tenant’s currency (INR or USD).
  2. Checkout & verification — the Elm dashboard opens Razorpay Checkout (public/boot.js) and posts the payment signature to /api/billing/verify.
  3. Authoritative webhook (POST /webhook/razorpay, src/billing/webhook.rs) — verifies X-Razorpay-Signature (HMAC-SHA256) and fails closed if RAZORPAY_WEBHOOK_SECRET is unset or empty. Credits are recorded idempotently in payments and tenant_billing.

API Documentation (rustdoc)

The full Rust crate documentation generated by cargo doc --no-deps is published alongside this book:

To build it locally:

./scripts/build-frontend.sh   # required by build.rs to hash public/app.js
cargo doc --no-deps --open

Bindings & Environment

Worker name: replybots (compatibility date 2024-01-01).

Cloudflare Bindings

BindingTypeTarget / Config
DBD1 Databasedatabase_name = "replybots"
AIWorkers AIReply generation, injection & safety guardrails
EMAILSend EmailOutbound platform-to-tenant handoff alerts
—Static Assetsdirectory = "./public"

Environment Variables ([vars])

Default values in wrangler.toml:

  • ENVIRONMENT = "production"
VariableDescriptionRead in
AI_INJECTION_MODELWorkers AI injection classifier (default @cf/meta/prompt-guard-2-86m)src/ai.rs
AI_MODELWorkers AI reply model (default @cf/meta/llama-4-scout-17b-16e-instruct)src/ai.rs
AI_SAFETY_MODELWorkers AI safety classifier (default @cf/meta/llama-guard-3-8b)src/safety.rs
DEV_MODESet to “1” or “true” in local dev to stub AI/safety & enable /auth/dev-loginsrc/dev_bypass.rs
EMAIL_DOMAINDomain outbound handoff emails are sent from, e.g. replybots.iosrc/escalations.rs
PUBLIC_BASE_URLPrimary site URL, e.g. https://replybots.iosrc/escalations.rs, src/handlers/data_deletion.rs, src/lib.rs
WHATSAPP_SIGNUP_CONFIG_IDMeta Embedded Signup config IDsrc/api/whatsapp.rs
WHATSAPP_WABA_IDFallback WhatsApp Business Account IDsrc/handlers/whatsapp_signup.rs

Secrets (wrangler secret put)

SecretDescriptionRead in
META_APP_IDMeta app ID (WhatsApp Embedded Signup)src/api/whatsapp.rs, src/handlers/whatsapp_signup.rs
META_APP_SECRETMeta app secretsrc/handlers/data_deletion.rs, src/handlers/webhook.rs, src/handlers/whatsapp_signup.rs
RAZORPAY_KEY_IDRazorpay key IDsrc/api/billing.rs
RAZORPAY_KEY_SECRETRazorpay key secretsrc/api/billing.rs
RAZORPAY_WEBHOOK_SECRETRazorpay webhook secretsrc/billing/webhook.rs
WHATSAPP_ACCESS_TOKENSystem user token for WhatsApp Graph API callssrc/channel/whatsapp.rs, src/handlers/whatsapp_signup.rs
WHATSAPP_VERIFY_TOKENWhatsApp webhook verification tokensrc/handlers/webhook.rs

Routes & Endpoints

Webhooks & Callbacks

MethodPathHandler
GET, POST/webhook/whatsappWhatsApp Cloud API verification & inbound messages (src/handlers/webhook.rs)
POST/webhook/razorpayRazorpay payment webhook, HMAC-SHA256 verified (src/billing/webhook.rs)
POST/data-deletionMeta data-deletion callback (src/handlers/data_deletion.rs)
POST/auth/whatsapp/startStart Meta / WhatsApp Embedded Signup login (src/handlers/auth.rs)
POST/auth/dev-loginLocal dev sign-in when DEV_MODE=1 (src/handlers/auth.rs)
POST/whatsapp/signup/callbackMeta Embedded Signup completion (src/handlers/whatsapp_signup.rs)

Health & Static Assets

Static files in public/ are served directly by Cloudflare’s [assets] edge layer before the Worker runs. Built-in Worker routes:

  • /robots.txt
  • /sitemap.txt
  • /logo.svg
  • /site.webmanifest
  • /browserconfig.xml
  • /favicon-16.png
  • /favicon-32.png
  • /apple-touch-icon.png
  • /logo-192.png
  • /logo-512.png
  • /mstile-150x150.png
  • /health

JSON API (/api/*)

Mutations (POST, PUT, DELETE) require the X-Replybots-Request: 1 header (src/api/mod.rs).

MethodPath
*/api/bootstrap
POST/api/demo/chat
GET/api/session
DELETE/api/session
DELETE/api/account
GET/api/wizard
PUT/api/wizard/basics
POST/api/wizard/channels/done
POST/api/wizard/step
POST/api/wizard/complete
GET/api/whatsapp
PUT/api/whatsapp
DELETE/api/whatsapp
GET/api/billing
POST/api/billing/checkout
*/api/settings/*

SPA Shell Routes

Handled by is_app_route in src/lib.rs (plus /wizard/*):

  • /
  • /index.html
  • /pricing
  • /features
  • /terms
  • /privacy
  • /login
  • /wizard
  • /dashboard
  • /dashboard/channels
  • /dashboard/billing
  • /dashboard/settings
  • /wizard/

D1 Database Schema

Defined in migrations/0001_create_schema.sql.

Tables

tenants

ColumnDefinition
idTEXT PRIMARY KEY
emailTEXT UNIQUE
nameTEXT
facebook_idTEXT
planTEXT DEFAULT 'paid'
localeTEXT NOT NULL DEFAULT 'en-IN'
currencyTEXT NOT NULL DEFAULT 'INR'
created_atTEXT DEFAULT (datetime('now'))
updated_atTEXT DEFAULT (datetime('now'))

sessions

ColumnDefinition
tokenTEXT PRIMARY KEY
tenant_idTEXT NOT NULL
expires_atINTEGER NOT NULL
created_atTEXT NOT NULL

whatsapp_accounts

ColumnDefinition
idTEXT PRIMARY KEY
tenant_idTEXT NOT NULL
nameTEXT NOT NULL
phone_number_idTEXT NOT NULL UNIQUE
display_phone_numberTEXT NOT NULL
waba_idTEXT
reply_jsonTEXT NOT NULL
canned_safety_jsonTEXT NOT NULL
created_atTEXT NOT NULL

tenant_onboarding

ColumnDefinition
tenant_idTEXT PRIMARY KEY
state_jsonTEXT NOT NULL
updated_atTEXT NOT NULL

signup_states

ColumnDefinition
stateTEXT PRIMARY KEY
tenant_idTEXT NOT NULL
expires_atINTEGER NOT NULL

conversation_sessions

ColumnDefinition
session_keyTEXT PRIMARY KEY
session_jsonTEXT NOT NULL
expires_atINTEGER NOT NULL
updated_atTEXT NOT NULL

rate_limits

ColumnDefinition
bucket_keyTEXT PRIMARY KEY
countINTEGER NOT NULL
expires_atINTEGER NOT NULL

pending_inbound

ColumnDefinition
idTEXT PRIMARY KEY
batch_keyTEXT NOT NULL
message_jsonTEXT NOT NULL
created_at_msINTEGER NOT NULL

messages

ColumnDefinition
idTEXT PRIMARY KEY
tenant_idTEXT NOT NULL
channelTEXT NOT NULL
channel_account_idTEXT NOT NULL DEFAULT ''
directionTEXT NOT NULL
senderTEXT NOT NULL
recipientTEXT NOT NULL
action_takenTEXT
conversation_idTEXT
created_atTEXT NOT NULL DEFAULT (datetime('now'))

payments

ColumnDefinition
idTEXT PRIMARY KEY
tenant_idTEXT
razorpay_payment_idTEXT
razorpay_order_idTEXT
amountINTEGER NOT NULL
creditsINTEGER NOT NULL DEFAULT 0
currencyTEXT NOT NULL
statusTEXT NOT NULL
created_atTEXT NOT NULL DEFAULT (datetime('now'))

tenant_billing

ColumnDefinition
tenant_idTEXT PRIMARY KEY
credits_jsonTEXT NOT NULL DEFAULT '[]'
replies_usedINTEGER NOT NULL DEFAULT 0
updated_atTEXT NOT NULL DEFAULT (datetime('now'))

Indexes

IndexTableColumnsUnique
idx_tenants_emailtenantsemailYes
idx_tenants_facebooktenantsfacebook_idNo
idx_sessions_tenantsessionstenant_idNo
idx_sessions_expiressessionsexpires_atNo
idx_whatsapp_accounts_tenantwhatsapp_accountstenant_idNo
idx_whatsapp_accounts_phonewhatsapp_accountsphone_number_idYes
idx_signup_states_expiressignup_statesexpires_atNo
idx_conversation_sessions_expiresconversation_sessionsexpires_atNo
idx_rate_limits_expiresrate_limitsexpires_atNo
idx_pending_inbound_batchpending_inboundbatch_key, created_at_msNo
idx_messages_tenantmessagestenant_id, created_atNo
idx_messages_channelmessageschannel, tenant_id, created_atNo
idx_messages_channel_accountmessageschannel_account_idNo
idx_messages_conversationmessagesconversation_id, created_atNo
idx_payments_tenantpaymentstenant_id, created_atNo
idx_payments_razorpay_idpaymentsrazorpay_payment_idYes