WhatsApp has 2+ billion users, making it the perfect platform for astrology consultations. Users can ask questions naturally, share birth details easily, and receive personalized predictions - all within their favorite messaging app.
In this tutorial, we'll build a production-ready WhatsApp astrology bot using Twilio and Vedika API.
What We'll Build
Prerequisites
- Twilio Account - For WhatsApp Business API
- Vedika API Key - Get from vedika.io/dashboard
- Node.js - v18 or later
- ngrok - For local development
Project Setup
Step 1: Initialize Project
# Create project directory
mkdir whatsapp-astrology-bot
cd whatsapp-astrology-bot
# Initialize npm
npm init -y
# Install dependencies
npm install express twilio @vedika-io/sdk body-parser dotenv
npm install -D nodemon typescript @types/node @types/express
Step 2: Environment Variables
# .env
TWILIO_ACCOUNT_SID=your_twilio_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_WHATSAPP_NUMBER=whatsapp:+14155238886
VEDIKA_API_KEY=your_vedika_api_key
PORT=3000
Step 3: Main Server File
// src/index.ts
import express from 'express';
import bodyParser from 'body-parser';
import { VedikaClient } from '@vedika-io/sdk';
import twilio from 'twilio';
import 'dotenv/config';
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
// Initialize clients
const vedika = new VedikaClient({
apiKey: process.env.VEDIKA_API_KEY!
});
const twilioClient = twilio(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_AUTH_TOKEN
);
// In-memory user session storage (use Redis in production)
const userSessions: Map<string, UserSession> = new Map();
interface UserSession {
birthDetails?: {
datetime: string;
latitude: number;
longitude: number;
timezone: string;
};
state: 'new' | 'awaiting_birth_details' | 'ready';
language: string;
}
// WhatsApp webhook endpoint
app.post('/webhook', async (req, res) => {
const { Body, From, ProfileName } = req.body;
const userPhone = From;
console.log(`Message from ${ProfileName} (${userPhone}): ${Body}`);
// Get or create user session
let session = userSessions.get(userPhone);
if (!session) {
session = { state: 'new', language: 'en' };
userSessions.set(userPhone, session);
}
// Process message and get response
const response = await processMessage(Body, session, ProfileName);
// Send response via Twilio
await sendWhatsAppMessage(userPhone, response);
res.status(200).send('OK');
});
async function processMessage(
message: string,
session: UserSession,
userName: string
): Promise<string> {
const lowerMessage = message.toLowerCase().trim();
// Handle new users
if (session.state === 'new') {
session.state = 'awaiting_birth_details';
return `🌟 Welcome to Cosmic Insights, ${userName}!
I'm your AI-powered astrology assistant. To give you personalized predictions, I need your birth details.
Please share in this format:
📅 Date: DD/MM/YYYY
⏰ Time: HH:MM AM/PM
📍 Place: City, Country
Example: 15/06/1990, 2:30 PM, New Delhi, India`;
}
// Handle birth details input
if (session.state === 'awaiting_birth_details') {
const birthDetails = parseBirthDetails(message);
if (birthDetails) {
session.birthDetails = birthDetails;
session.state = 'ready';
return `✅ Birth details saved!
You can now ask me anything:
🔮 "What's my daily horoscope?"
💼 "How's my career looking?"
❤️ "Am I compatible with [date]?"
📆 "Best time to start a business?"
Just type your question!`;
} else {
return `❌ I couldn't understand that format.
Please share like this:
15/06/1990, 2:30 PM, New Delhi, India`;
}
}
// Handle astrology queries
if (session.state === 'ready' && session.birthDetails) {
try {
const response = await vedika.query({
question: message,
birthDetails: session.birthDetails,
language: session.language
});
return `🌟 ${response.answer}
---
Ask another question or type "menu" for options.`;
} catch (error) {
console.error('Vedika API error:', error);
return `Sorry, I encountered an error. Please try again.`;
}
}
return `Type "start" to begin your astrology journey!`;
}
function parseBirthDetails(input: string): UserSession['birthDetails'] | null {
// Parse format: "15/06/1990, 2:30 PM, New Delhi, India"
const regex = /(\d{1,2})\/(\d{1,2})\/(\d{4}),?\s*(\d{1,2}):(\d{2})\s*(AM|PM),?\s*(.+)/i;
const match = input.match(regex);
if (!match) return null;
const [, day, month, year, hour, minute, period, place] = match;
// Convert to 24-hour format
let hour24 = parseInt(hour);
if (period.toUpperCase() === 'PM' && hour24 !== 12) hour24 += 12;
if (period.toUpperCase() === 'AM' && hour24 === 12) hour24 = 0;
// Get coordinates for place (use Google Geocoding API in production)
const coords = getCoordinates(place.trim());
return {
datetime: `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}T${String(hour24).padStart(2, '0')}:${minute}:00+05:30`,
latitude: coords.lat,
longitude: coords.lng,
timezone: coords.timezone
};
}
function getCoordinates(place: string) {
// Simplified - use Google Geocoding API in production
const cities: Record<string, { lat: number; lng: number; timezone: string }> = {
'new delhi': { lat: 28.6139, lng: 77.2090, timezone: 'Asia/Kolkata' },
'mumbai': { lat: 19.0760, lng: 72.8777, timezone: 'Asia/Kolkata' },
'bangalore': { lat: 12.9716, lng: 77.5946, timezone: 'Asia/Kolkata' },
'chennai': { lat: 13.0827, lng: 80.2707, timezone: 'Asia/Kolkata' },
};
const normalized = place.toLowerCase().replace(', india', '').trim();
return cities[normalized] || cities['new delhi'];
}
async function sendWhatsAppMessage(to: string, body: string) {
await twilioClient.messages.create({
from: process.env.TWILIO_WHATSAPP_NUMBER,
to: to,
body: body
});
}
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Setting Up Twilio WhatsApp
Step 1: Twilio Sandbox (Development)
- Go to Twilio Console → Messaging → Try it out → WhatsApp
- Join the sandbox by sending the code to the Twilio number
- Configure webhook URL:
https://your-ngrok-url/webhook
Step 2: Production Setup
- Apply for WhatsApp Business API via Twilio
- Submit your business for verification
- Create message templates for proactive messaging
Advanced Features
Language Detection and Response
// Detect language from user message
function detectLanguage(message: string): string {
// Simple detection based on script
if (/[\u0900-\u097F]/.test(message)) return 'hi'; // Hindi
if (/[\u0B80-\u0BFF]/.test(message)) return 'ta'; // Tamil
if (/[\u0C00-\u0C7F]/.test(message)) return 'te'; // Telugu
return 'en'; // Default English
}
// In processMessage function:
session.language = detectLanguage(message);
Compatibility Matching
// Handle compatibility queries
if (lowerMessage.includes('compatible') || lowerMessage.includes('match')) {
// Extract partner's birth date from message
const partnerDate = extractDate(message);
if (partnerDate) {
const response = await vedika.query({
question: `How compatible am I with someone born on ${partnerDate}? Include Guna score.`,
birthDetails: session.birthDetails
});
return `💕 Compatibility Analysis:\n\n${response.answer}`;
}
}
Daily Horoscope Broadcasts
// Schedule daily horoscope at 6 AM
import cron from 'node-cron';
cron.schedule('0 6 * * *', async () => {
// Get all subscribed users
const subscribers = await getSubscribers();
for (const user of subscribers) {
if (user.birthDetails) {
const horoscope = await vedika.query({
question: "What should I focus on today? Give a brief daily horoscope.",
birthDetails: user.birthDetails,
language: user.language
});
await sendWhatsAppMessage(user.phone, `🌅 Good Morning!
Your Daily Horoscope:
${horoscope.answer}
Have a great day! ✨`);
}
}
});
Deployment
Deploy to Railway/Render
# Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["node", "dist/index.js"]
Monetization Ideas
- Free tier: 3 questions per day
- Premium: Unlimited questions (₹99/month via UPI)
- Reports: Detailed Kundali PDF (₹199 one-time)
- Consultations: Connect with live astrologers
Build Your WhatsApp Astrology Bot
Get started with Vedika API - 10 free queries to test your bot.
Get Your API KeyConclusion
Building a WhatsApp astrology bot is straightforward with Twilio and Vedika API. The combination gives you:
- Instant reach - 2+ billion WhatsApp users
- Natural conversations - AI understands natural language
- Personalization - Real astrological calculations
- Multilingual - Support 22 languages automatically
Next steps:
- Get your Vedika API key at vedika.io/dashboard
- Set up Twilio WhatsApp sandbox
- Clone our starter template
- Deploy and start acquiring users!
About Vedika Intelligence: We provide the only B2B astrology API with AI-powered conversational capabilities, perfect for WhatsApp bots, Telegram bots, and chat applications.