$ cd ~/projects

CureSlot

updated today

// how it works

# CureSlot WhatsApp Bot CureSlot is an automated, serverless WhatsApp bot built on **Cloudflare Workers** and **D1**, integrating with the **Meta WhatsApp Cloud API**. It is designed for medical clinics to automate patient appointment booking, schedule management, and reminder notifications. ## Key Features - **Patient Self-Serve Booking**: Patients can view available slots, book appointments, and cancel (subject to a configurable cancellation window). - **Staff Management**: Clinic staff can view daily schedules, block out dates, and manually add walk-in patients directly through WhatsApp.

CureSlot WhatsApp Bot

CureSlot is an automated, serverless WhatsApp bot built on Cloudflare Workers and D1, integrating with the Meta WhatsApp Cloud API. It is designed for medical clinics to automate patient appointment booking, schedule management, and reminder notifications.

Key Features

  • Patient Self-Serve Booking: Patients can view available slots, book appointments, and cancel (subject to a configurable cancellation window).
  • Staff Management: Clinic staff can view daily schedules, block out dates, and manually add walk-in patients directly through WhatsApp.
  • Automated Reminders: Built-in Cloudflare Cron triggers hourly to send WhatsApp template reminders 4 hours before upcoming appointments.
  • Robust Architecture: Uses Cloudflare Queues to decouple webhook ingestion from business logic processing, preventing timeouts and handling high concurrency.
  • Idempotency & Race Condition Prevention: Database unique constraints prevent double-booking the same slot, and message idempotency tracking prevents duplicate processing from Meta API retries.

️ Architecture Overview

  1. Webhook Ingestion (src/webhook.js): Receives POST requests from Meta, verifies HMAC signatures, and immediately places the payload onto a Cloudflare Queue.
  2. Queue Consumer (src/consumer.js): Pulls batches from the Queue, checks idempotency, determines user roles (Staff vs Patient), and routes messages to the appropriate flow.
  3. Patient Flow (src/flows/patient.js): Manages the state machine for patients (Menu -> Select Slot -> Enter Name).
  4. Staff Flow (src/flows/staff.js): Manages the state machine for doctors/staff (View Today's Appts -> Block Dates -> Walk-ins).
  5. Database (src/db/): Cloudflare D1 SQL database storing Clinics, Appointments, Conversation State, and Blocked dates.

Testing Override (For Single-Device Testing)

During development, a testing override is active in src/consumer.js. This allows you to test both flows from a single WhatsApp number without constantly updating your database role:

  • Text exactly staff -> Forces the Staff Menu.
  • Text any other message (e.g. hi) -> Forces the Patient Menu.
  • Note: This override must be removed before production handoff!

Complete Deployment & Wiring Guide

This guide details every single step required to take this codebase to a live, production-ready system connected to Meta and Cloudflare.

1. Cloudflare Account & CLI Setup

  1. Sign up for Cloudflare and activate Workers & Pages.
  2. Authenticate your CLI:
    npx wrangler login
    

2. Cloudflare Production Resources Creation

  1. Create D1 Database (Remote):
    npx wrangler d1 create curesslot-db
    
    Copy the resulting database_id and paste it into wrangler.toml.
  2. Create Cloudflare Queues:
    npx wrangler queues create curesslot-queue
    npx wrangler queues create curesslot-dlq
    
  3. Execute Database Schema on Production D1:
    npx wrangler d1 execute curesslot-db --remote --file=migrations/0001_init.sql
    npx wrangler d1 execute curesslot-db --remote --file=seed/seed.sql
    

3. Meta Developer Account Setup

  1. Create an App at developers.facebook.com.
  2. Select App Type: Business -> CureSlot App.
  3. Add the WhatsApp product.

4. Retrieving Meta API Credentials

  1. Phone Number ID: From the API Setup screen, copy the Phone Number ID. Update seed.sql with this ID and re-run the seed query.
  2. Meta System Token: Generate a permanent System User Token under Business Manager (or use the Temporary token for sandbox).
  3. Meta App Secret: From App Settings -> Basic.

5. Configuring Wrangler Settings & Secrets

Secrets must never be committed to Git.

Production Secrets (Cloudflare Cloud):

npx wrangler secret put META_APP_SECRET
npx wrangler secret put WHATSAPP_VERIFY_TOKEN
npx wrangler secret put META_SYSTEM_TOKEN

Local Secrets (curesslot/.dev.vars):

META_APP_SECRET="your_app_secret_here"
WHATSAPP_VERIFY_TOKEN="your_verify_token_here"
META_SYSTEM_TOKEN="your_token_here"

6. Deploying to Cloudflare Workers

npm run deploy

Note your live webhook URL: https://curesslot.your-subdomain.workers.dev/webhook

7. Wiring the Webhook in Meta Dashboard

  1. Go to WhatsApp -> Configuration.
  2. Callback URL: Enter your live webhook URL.
  3. Verify Token: Enter your WHATSAPP_VERIFY_TOKEN.
  4. Subscribe to Events: Check the box for messages and click Subscribe.

8. Critical Subscribed Apps Registration

Due to a Meta API quirk, explicitly subscribe your app via Graph Explorer:

  1. Method: POST
  2. URL: v19.0/{WHATSAPP_BUSINESS_ACCOUNT_ID}/subscribed_apps
  3. Execute and expect {"success": true}.

9. Local Sandbox Testing

To debug locally:

  1. Start wrangler locally: npx wrangler dev
  2. Expose via ngrok: ngrok http 8787
  3. Update Meta Webhook configuration with your ngrok URL.
  4. Add your personal phone number to the Whitelist in the API Setup tab to receive sandbox messages.

// stack

Cloudflare WorkersQueuesD1WhatsApp Cloud APITypeScript