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.
Links
- Hosted SaaS: https://replybots.io
- Source repository: https://github.com/ananthb/replybots
- Rust API reference (
cargo doc): /api/replybots/index.html
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.ioEMAIL_DOMAIN— domain for outbound handoff alert emails (e.g.replybots.io)WHATSAPP_WABA_ID— fallback WhatsApp Business Account IDWHATSAPP_SIGNUP_CONFIG_ID— Meta Embedded Signup configuration ID
Set secrets via wrangler secret put:
WHATSAPP_ACCESS_TOKEN,WHATSAPP_VERIFY_TOKENMETA_APP_ID,META_APP_SECRETRAZORPAY_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/whatsappwith yourWHATSAPP_VERIFY_TOKEN. - Meta data deletion callback: point to
<PUBLIC_BASE_URL>/data-deletion. - Razorpay webhook: point to
<PUBLIC_BASE_URL>/webhook/razorpayusingRAZORPAY_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
messagestable — storeschannel,direction,sender,recipient,action_taken,conversation_id, andcreated_at, never message bodies.
Inbound Reply Pipeline
- Webhook verification & dispatch (
src/handlers/webhook.rs) — verifiesX-Hub-Signature-256withMETA_APP_SECRETand parses inbound WhatsApp events. - Burst debounce (
pending_inbound) — buffers rapid consecutive customer messages for the configuredwait_seconds(0–30s) so multiple short texts receive a single coherent reply. - Prompt-injection screening (
src/ai.rs) — runs@cf/meta/prompt-guard-2-86mon inbound text. - Reply generation (
src/ai.rs) — in AI mode, calls@cf/meta/llama-4-scout-17b-16e-instructwith the single built-in core persona and recent conversation context (conversation_sessions). - Safety & risk gate (
src/safety.rs,src/risk.rs) — vets output via@cf/meta/llama-guard-3-8bandrisk::signalchecks (unauthorized prices, commitments, or[[HANDOFF]]markers). - Handoff & escalation (
src/escalations.rs) — when handed off, sends a holding reply, puts the thread intohandoff_cooldown_mins, and optionally sends an alert email via Cloudflaresend_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
- Order creation (
POST /api/billing/order) — creates a Razorpay Order for the requested credit count (betweenminCreditsandmaxCredits) in the tenant’s currency (INRorUSD). - Checkout & verification — the Elm dashboard opens Razorpay Checkout (
public/boot.js) and posts the payment signature to/api/billing/verify. - Authoritative webhook (
POST /webhook/razorpay,src/billing/webhook.rs) — verifiesX-Razorpay-Signature(HMAC-SHA256) and fails closed ifRAZORPAY_WEBHOOK_SECRETis unset or empty. Credits are recorded idempotently inpaymentsandtenant_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
| Binding | Type | Target / Config |
|---|---|---|
DB | D1 Database | database_name = "replybots" |
AI | Workers AI | Reply generation, injection & safety guardrails |
EMAIL | Send Email | Outbound platform-to-tenant handoff alerts |
| — | Static Assets | directory = "./public" |
Environment Variables ([vars])
Default values in wrangler.toml:
ENVIRONMENT="production"
| Variable | Description | Read in |
|---|---|---|
AI_INJECTION_MODEL | Workers AI injection classifier (default @cf/meta/prompt-guard-2-86m) | src/ai.rs |
AI_MODEL | Workers AI reply model (default @cf/meta/llama-4-scout-17b-16e-instruct) | src/ai.rs |
AI_SAFETY_MODEL | Workers AI safety classifier (default @cf/meta/llama-guard-3-8b) | src/safety.rs |
DEV_MODE | Set to “1” or “true” in local dev to stub AI/safety & enable /auth/dev-login | src/dev_bypass.rs |
EMAIL_DOMAIN | Domain outbound handoff emails are sent from, e.g. replybots.io | src/escalations.rs |
PUBLIC_BASE_URL | Primary site URL, e.g. https://replybots.io | src/escalations.rs, src/handlers/data_deletion.rs, src/lib.rs |
WHATSAPP_SIGNUP_CONFIG_ID | Meta Embedded Signup config ID | src/api/whatsapp.rs |
WHATSAPP_WABA_ID | Fallback WhatsApp Business Account ID | src/handlers/whatsapp_signup.rs |
Secrets (wrangler secret put)
| Secret | Description | Read in |
|---|---|---|
META_APP_ID | Meta app ID (WhatsApp Embedded Signup) | src/api/whatsapp.rs, src/handlers/whatsapp_signup.rs |
META_APP_SECRET | Meta app secret | src/handlers/data_deletion.rs, src/handlers/webhook.rs, src/handlers/whatsapp_signup.rs |
RAZORPAY_KEY_ID | Razorpay key ID | src/api/billing.rs |
RAZORPAY_KEY_SECRET | Razorpay key secret | src/api/billing.rs |
RAZORPAY_WEBHOOK_SECRET | Razorpay webhook secret | src/billing/webhook.rs |
WHATSAPP_ACCESS_TOKEN | System user token for WhatsApp Graph API calls | src/channel/whatsapp.rs, src/handlers/whatsapp_signup.rs |
WHATSAPP_VERIFY_TOKEN | WhatsApp webhook verification token | src/handlers/webhook.rs |
Routes & Endpoints
Webhooks & Callbacks
| Method | Path | Handler |
|---|---|---|
GET, POST | /webhook/whatsapp | WhatsApp Cloud API verification & inbound messages (src/handlers/webhook.rs) |
POST | /webhook/razorpay | Razorpay payment webhook, HMAC-SHA256 verified (src/billing/webhook.rs) |
POST | /data-deletion | Meta data-deletion callback (src/handlers/data_deletion.rs) |
POST | /auth/whatsapp/start | Start Meta / WhatsApp Embedded Signup login (src/handlers/auth.rs) |
POST | /auth/dev-login | Local dev sign-in when DEV_MODE=1 (src/handlers/auth.rs) |
POST | /whatsapp/signup/callback | Meta 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).
| Method | Path |
|---|---|
* | /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
| Column | Definition |
|---|---|
id | TEXT PRIMARY KEY |
email | TEXT UNIQUE |
name | TEXT |
facebook_id | TEXT |
plan | TEXT DEFAULT 'paid' |
locale | TEXT NOT NULL DEFAULT 'en-IN' |
currency | TEXT NOT NULL DEFAULT 'INR' |
created_at | TEXT DEFAULT (datetime('now')) |
updated_at | TEXT DEFAULT (datetime('now')) |
sessions
| Column | Definition |
|---|---|
token | TEXT PRIMARY KEY |
tenant_id | TEXT NOT NULL |
expires_at | INTEGER NOT NULL |
created_at | TEXT NOT NULL |
whatsapp_accounts
| Column | Definition |
|---|---|
id | TEXT PRIMARY KEY |
tenant_id | TEXT NOT NULL |
name | TEXT NOT NULL |
phone_number_id | TEXT NOT NULL UNIQUE |
display_phone_number | TEXT NOT NULL |
waba_id | TEXT |
reply_json | TEXT NOT NULL |
canned_safety_json | TEXT NOT NULL |
created_at | TEXT NOT NULL |
tenant_onboarding
| Column | Definition |
|---|---|
tenant_id | TEXT PRIMARY KEY |
state_json | TEXT NOT NULL |
updated_at | TEXT NOT NULL |
signup_states
| Column | Definition |
|---|---|
state | TEXT PRIMARY KEY |
tenant_id | TEXT NOT NULL |
expires_at | INTEGER NOT NULL |
conversation_sessions
| Column | Definition |
|---|---|
session_key | TEXT PRIMARY KEY |
session_json | TEXT NOT NULL |
expires_at | INTEGER NOT NULL |
updated_at | TEXT NOT NULL |
rate_limits
| Column | Definition |
|---|---|
bucket_key | TEXT PRIMARY KEY |
count | INTEGER NOT NULL |
expires_at | INTEGER NOT NULL |
pending_inbound
| Column | Definition |
|---|---|
id | TEXT PRIMARY KEY |
batch_key | TEXT NOT NULL |
message_json | TEXT NOT NULL |
created_at_ms | INTEGER NOT NULL |
messages
| Column | Definition |
|---|---|
id | TEXT PRIMARY KEY |
tenant_id | TEXT NOT NULL |
channel | TEXT NOT NULL |
channel_account_id | TEXT NOT NULL DEFAULT '' |
direction | TEXT NOT NULL |
sender | TEXT NOT NULL |
recipient | TEXT NOT NULL |
action_taken | TEXT |
conversation_id | TEXT |
created_at | TEXT NOT NULL DEFAULT (datetime('now')) |
payments
| Column | Definition |
|---|---|
id | TEXT PRIMARY KEY |
tenant_id | TEXT |
razorpay_payment_id | TEXT |
razorpay_order_id | TEXT |
amount | INTEGER NOT NULL |
credits | INTEGER NOT NULL DEFAULT 0 |
currency | TEXT NOT NULL |
status | TEXT NOT NULL |
created_at | TEXT NOT NULL DEFAULT (datetime('now')) |
tenant_billing
| Column | Definition |
|---|---|
tenant_id | TEXT PRIMARY KEY |
credits_json | TEXT NOT NULL DEFAULT '[]' |
replies_used | INTEGER NOT NULL DEFAULT 0 |
updated_at | TEXT NOT NULL DEFAULT (datetime('now')) |
Indexes
| Index | Table | Columns | Unique |
|---|---|---|---|
idx_tenants_email | tenants | email | Yes |
idx_tenants_facebook | tenants | facebook_id | No |
idx_sessions_tenant | sessions | tenant_id | No |
idx_sessions_expires | sessions | expires_at | No |
idx_whatsapp_accounts_tenant | whatsapp_accounts | tenant_id | No |
idx_whatsapp_accounts_phone | whatsapp_accounts | phone_number_id | Yes |
idx_signup_states_expires | signup_states | expires_at | No |
idx_conversation_sessions_expires | conversation_sessions | expires_at | No |
idx_rate_limits_expires | rate_limits | expires_at | No |
idx_pending_inbound_batch | pending_inbound | batch_key, created_at_ms | No |
idx_messages_tenant | messages | tenant_id, created_at | No |
idx_messages_channel | messages | channel, tenant_id, created_at | No |
idx_messages_channel_account | messages | channel_account_id | No |
idx_messages_conversation | messages | conversation_id, created_at | No |
idx_payments_tenant | payments | tenant_id, created_at | No |
idx_payments_razorpay_id | payments | razorpay_payment_id | Yes |