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
Hi! I want to know my horoscope
Welcome to Cosmic Insights! I can help you with personalized astrology readings.
Please share your birth details:
- Date of Birth (DD/MM/YYYY)
- Time of Birth (HH:MM AM/PM)
- Place of Birth
15/06/1990, 2:30 PM, New Delhi
Great! I've recorded your birth details.
You can now ask me anything:
- "What's my daily horoscope?"
- "How's my career looking?"
- "Am I compatible with someone born on [date]?"
- "When is a good time to start a business?"
What are my career prospects this year?
Based on your birth chart, your 10th house lord Jupiter is currently transiting your 3rd house, indicating excellent opportunities in communication, writing, and short-distance travel related to work...
[Detailed personalized prediction continues]
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
mkdir whatsapp-astrology-bot
cd whatsapp-astrology-bot
npm init -y
npm install express twilio @vedika-io/sdk body-parser dotenv
npm install -D nodemon typescript @types/node @types/express
Step 2: Environment Variables
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
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 }));
const vedika = new VedikaClient({
apiKey: process.env.VEDIKA_API_KEY!
});
const twilioClient = twilio(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_AUTH_TOKEN
);
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;
}
app.post('/webhook', async (req, res) => {
const { Body, From, ProfileName } = req.body;
const userPhone = From;
console.log(`Message from ${ProfileName} (${userPhone}): ${Body}`);
let session = userSessions.get(userPhone);
if (!session) {
session = { state: 'new', language: 'en' };
userSessions.set(userPhone, session);
}
const response = await processMessage(Body, session, ProfileName);
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();
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`;
}
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`;
}
}
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 {
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;
let hour24 = parseInt(hour);
if (period.toUpperCase() === 'PM' && hour24 !== 12) hour24 += 12;
if (period.toUpperCase() === 'AM' && hour24 === 12) hour24 = 0;
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) {
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
function detectLanguage(message: string): string {
if (/[\u0900-\u097F]/.test(message)) return 'hi';
if (/[\u0B80-\u0BFF]/.test(message)) return 'ta';
if (/[\u0C00-\u0C7F]/.test(message)) return 'te';
return 'en';
}
session.language = detectLanguage(message);
Compatibility Matching
if (lowerMessage.includes('compatible') || lowerMessage.includes('match')) {
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
import cron from 'node-cron';
cron.schedule('0 6 * * *', async () => {
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! ✨`);
}
}
});
Common Gotchas
Before you deploy, watch out for these issues developers hit when building WhatsApp bots with Vedika API:
- Timezone format: Use UTC offset (+05:30), not IANA names (Asia/Kolkata). API validation will reject IANA names.
- Response time: AI queries take 8-15 seconds. Always set a webhook timeout above 20s or messages will fail silently.
- Session storage: In-memory Map works for dev, but production needs Redis or database. Sessions expire on server restart.
- Rate limiting: Twilio has strict rate limits. Cache horoscope responses per-sign per-day to avoid hitting API limits.
Deployment
Deploy to Railway/Render
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
Start Building Your WhatsApp Bot
Get your Vedika API key and test your integration with 10 free queries.
Get API Access
Conclusion
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 30 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 a B2B astrology API with AI-powered conversational capabilities for building WhatsApp bots, Telegram bots, and chat applications.