Skip to content

harshxframe/whatsapp-leads-automation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Coaching AI Bot - WhatsApp Leads Automation

A WhatsApp-based AI coaching bot that automates lead generation and qualification for coaching businesses. The bot uses Google Generative AI (Gemini) to engage with customers, extract information, and track conversions.


Table of Contents


Supported Features

✅ Client Management

  • Create new coaching business clients
  • Retrieve individual client details
  • Update client information and AI settings
  • Block/deactivate clients
  • List all clients
  • Client login functionality

✅ WhatsApp Integration

  • Webhook validation with Meta WhatsApp Business API
  • Receive incoming messages from WhatsApp
  • Send outbound messages to customers
  • Mark messages as read
  • Message parsing and extraction
  • Typing indicators/status updates

✅ AI-Powered Conversations

  • Google Generative AI (Gemini) integration for intelligent responses
  • Conversational history tracking
  • Context-aware replies based on business profile
  • Configurable tone (professional, casual, etc.)
  • Multi-language support (including Hinglish)
  • Response style customization

✅ Lead Management

  • Automatic lead creation from WhatsApp conversations
  • Lead information extraction and enrichment
  • Lead status tracking
  • Lead caching for performance
  • Export leads to spreadsheets
  • Chat history preservation per lead

✅ Analytics & Reporting

  • Daily analytics tracking
  • Message count statistics
  • Lead generation metrics
  • Conversion tracking by conversion goal type
  • Business metrics per client

✅ Authentication

  • JWT-based authentication
  • Email-based verification (send code)
  • Token generation and validation

✅ Caching & Performance

  • Redis-based caching for leads
  • Redis-based caching for client data
  • In-memory optimization for frequently accessed data

✅ Queue Management

  • Background job processing using BullMQ
  • Database queue for async operations
  • Message and lead processing pipelines

✅ Developer Tools

  • Ngrok tunnel support for local development
  • Public URL generation for webhook testing
  • Nodemon for hot-reload development

Architecture

Core Components

src/
├── routes/              # API endpoint definitions
│   ├── client.route.js
│   ├── auth.route.js
│   ├── whatsapp.route.js
│   ├── leads.route.js
│   └── dailyAnalytics.route.js
├── controller/          # Request handlers
├── services/            # Business logic
│   ├── whatsApp.service.js
│   ├── client.service.js
│   ├── ai.leads.services.js
│   ├── leads.service.js
│   └── dailyAnalytics.service.js
├── models/              # MongoDB schemas
│   ├── Clients.js
│   ├── Leads.js
│   └── DailyStats.js
├── config/              # Database & Redis config
├── middlewares/         # Express middlewares
├── jobs/                # Queue jobs
├── utils/               # Helper functions
└── ai/                  # AI integration logic

Data Flow

  1. Incoming WhatsApp Message → Webhook receives message
  2. Message Parsing → Extract sender, content, metadata
  3. Client & Lead Lookup → Cache check for performance
  4. AI Processing → Generate response using Gemini
  5. Message Sending → Send response back to WhatsApp
  6. Data Storage → Update lead info, analytics, chat history
  7. Background Jobs → Database sync, notifications (async)

API Endpoints

Authentication

POST /auth/sendCode
- Sends verification code to email

Client Management

GET /app/v1/clientLogin
- Client login endpoint

POST /app/v1/createClient
- Create new coaching business client
- Required: ownerName, email, businessName, industry, businessContext, 
  businessDetails, services, tone, language, responseStyle, 
  conversionGoal, numberID, notifyOwner

POST /app/v1/getClient
- Retrieve specific client details

POST /app/v1/updateClient
- Update existing client information

POST /app/v1/blockClient
- Deactivate/block a client account

GET /app/v1/getClients
- List all active clients

WhatsApp Webhooks

GET /handShake/webhook
- Webhook verification (Meta handshake)

POST /handShake/webhook
- Receive incoming WhatsApp messages
- Trigger AI processing and response

Leads Management

GET /leads/getLeads
- Retrieve leads with optional filtering

GET /leads/exportLeads
- Export leads to spreadsheet format

Analytics

GET /analytics/getAnalytics
- Get daily analytics and metrics

System Health

GET /health
- Server health check endpoint

Setup & Configuration

Prerequisites

  • Node.js 16+
  • MongoDB (local or cloud)
  • Redis (local or cloud)
  • WhatsApp Business Account with verified number
  • Google Generative AI API key
  • Ngrok account (for local development)

Installation

# Install dependencies
npm install

# Create .env file with required variables (see below)
cp .env.example .env

# Start development server
npm run dev

# Or production
npm start

Running the Server

Development Mode (with hot reload)

npm run dev

This starts the server with Nodemon, which automatically restarts on file changes.

Production Mode

node server.js

The server will:

  1. Connect to MongoDB
  2. Initialize Redis connection
  3. Sync database indexes
  4. Start Express server on specified PORT
  5. Establish Ngrok tunnel (if configured)
  6. Display public webhook URL

Environment Variables

Variable Purpose Example
PORT Server port 2000
ENVIRONMENT Environment type development / production
DB_URL MongoDB connection string mongodb+srv://...
GEMINI_API_KEY Google Generative AI key AIzaSy...
WHATSAPP_MASTER_TOKEN Meta WhatsApp API token EAA8...
WEBHOOK_VERIFY_TOKEN Custom webhook verification token harsh_ai_master_123...
META_APP_ID Meta App ID 4230678500576731
NGROK_AUTHTOKEN Ngrok authentication token 3CyVtf...
REDIS_HOST Redis host 127.0.0.1
REDIS_PORT Redis port 6379
ZEPTO_MAIL_HOST Email service host https://api.zeptomail.in/v1.1/email
ZEPTO_MAIL_TOKEN Email service token Zoho-encza...
JSON_WEB_TOKEN_SCERET JWT secret key uehfe434r4u9...

Technology Stack

Core Framework

  • Express.js (5.2.1) - Web server & routing
  • Node.js - Runtime environment

Database & Caching

  • MongoDB (7.2.0) - Primary data store
  • Mongoose (9.5.0) - MongoDB ODM
  • Redis (IORedis 5.10.1) - Caching & sessions

AI & External APIs

  • Google Generative AI (1.51.0) - Gemini model for responses
  • Axios (1.15.2) - HTTP client

Queue & Jobs

  • BullMQ (5.76.5) - Job queue for background processing

Authentication & Security

  • JWT (jsonwebtoken 9.0.3) - Token-based auth
  • CORS (2.8.6) - Cross-origin requests

Email Service

  • Zeptomail (7.0.2) - Email notifications

Development & Utilities

  • Ngrok (1.7.0) - Public URL tunneling
  • Nodemon (3.1.14) - Auto-restart on changes
  • Winston (3.19.0) - Logging
  • Dotenv (17.4.2) - Environment variables
  • Body-parser (2.2.2) - Request parsing
  • Google Spreadsheet (5.2.0) - Spreadsheet integration

Supported Conversion Goals

When creating a client, use one of these conversion goals:

  • BOOK_DEMO - Demo booking
  • BOOK_APPOINTMENT - Appointment booking
  • GET_QUOTE - Quote request
  • SCHEDULE_VISIT - Visit scheduling
  • MAKE_PURCHASE - Direct purchase

Client Configuration

AI Settings (per client)

  • Tone: Professional, casual, friendly, etc.
  • Language: Hinglish, English, Hindi, etc.
  • Response Style: Short, detailed, conversational, etc.

Business Context

  • businessContext - Company history and unique selling points
  • businessDetails - Detailed service/product information
  • services - List of available services
  • industry - Business industry (default: "COACHING")

Notes

  • All timestamps use MongoDB's automatic timestamps: true (createdAt, updatedAt)
  • Client records require unique email addresses
  • Leads are linked to clients via clientId
  • Chat history is preserved per lead for context
  • Daily analytics reset per day per client
  • Redis caching is used for performance optimization
  • Background jobs handle database sync operations

Last Updated: 2026-06-17

About

WhatsApp Leads Automation – AI-Powered Lead Qualification Platform

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors