TUTORIAL NODE.JS

Build a WhatsApp Astrology Bot with Vedika API

Create a WhatsApp bot that delivers horoscopes, generates kundali, and provides compatibility readings to millions of users.

December 2025 15 min read Beginner friendly

📱 What You'll Build

Bot Features

  • ✅ Daily/Weekly/Monthly horoscopes
  • ✅ Birth chart (Kundali) generation
  • ✅ Compatibility matching
  • ✅ Panchang & muhurat lookup
  • ✅ AI-powered predictions

Tech Stack

  • 🔧 Node.js + Express
  • 📲 Twilio WhatsApp API
  • 🔮 Vedika Astrology API
  • ☁️ Deployed on Vercel/Railway

Prerequisites

  • Node.js 18+ installed
  • Free Vedika API account (1000 free calls/month)
  • Free Twilio account
  • Basic JavaScript knowledge
1

Get Your API Keys

Set up Vedika and Twilio accounts

Vedika API Key

  1. 1. Go to vedika.io/console
  2. 2. Sign up with Google or email
  3. 3. Copy your API key from the dashboard
💡 Free tier includes 1,000 API calls/month - enough for testing!

Twilio WhatsApp Sandbox

  1. 1. Create account at twilio.com
  2. 2. Go to Messaging → Try it Out → WhatsApp
  3. 3. Follow instructions to connect your phone to sandbox
  4. 4. Copy your Account SID and Auth Token
2

Project Setup

Initialize Node.js project and install dependencies

# Create project directory
mkdir whatsapp-astro-bot && cd whatsapp-astro-bot

# Initialize npm project
npm init -y

# Install dependencies
npm install express twilio axios dotenv

Create .env file

# .env
VEDIKA_API_KEY=your_vedika_api_key_here
TWILIO_ACCOUNT_SID=your_twilio_sid
TWILIO_AUTH_TOKEN=your_twilio_token
TWILIO_WHATSAPP_NUMBER=whatsapp:+14155238886
3

Build the Webhook Server

Create Express server to handle WhatsApp messages

// index.js
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const twilio = require('twilio');

const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

const VEDIKA_API = 'https://vedika-api-854222120654.us-central1.run.app';
const VEDIKA_KEY = process.env.VEDIKA_API_KEY;

// Twilio client
const twilioClient = twilio(
  process.env.TWILIO_ACCOUNT_SID,
  process.env.TWILIO_AUTH_TOKEN
);

// WhatsApp webhook endpoint
app.post('/webhook', async (req, res) => {
  const incomingMsg = req.body.Body.toLowerCase().trim();
  const from = req.body.From;

  let responseText = '';

  try {
    // Parse user command
    if (incomingMsg.startsWith('horoscope')) {
      responseText = await getHoroscope(incomingMsg);
    } else if (incomingMsg.startsWith('kundali')) {
      responseText = await getKundali(incomingMsg);
    } else if (incomingMsg.startsWith('match')) {
      responseText = await getCompatibility(incomingMsg);
    } else if (incomingMsg === 'panchang') {
      responseText = await getPanchang();
    } else {
      responseText = getHelpMenu();
    }
  } catch (error) {
    console.error('Error:', error.message);
    responseText = '🔮 Sorry, something went wrong. Please try again.';
  }

  // Send WhatsApp response
  await twilioClient.messages.create({
    body: responseText,
    from: process.env.TWILIO_WHATSAPP_NUMBER,
    to: from
  });

  res.status(200).send('OK');
});

// Help menu
function getHelpMenu() {
  return `🔮 *Astro Bot Menu*

📿 *horoscope [sign]*
   Example: horoscope aries

📜 *kundali [date] [time] [place]*
   Example: kundali 1990-05-15 10:30 Delhi

💑 *match [sign1] [sign2]*
   Example: match aries leo

🗓️ *panchang*
   Today's Hindu calendar

Type any command to get started!`;
}

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`🚀 WhatsApp Astro Bot running on port ${PORT}`);
});
4

Integrate Vedika API Endpoints

Add functions to fetch horoscopes, kundali, and compatibility

// Add these functions to index.js

// Get daily horoscope
async function getHoroscope(message) {
  const parts = message.split(' ');
  const sign = parts[1] || 'aries';

  const response = await axios.post(
    `${VEDIKA_API}/v1/horoscope/daily`,
    {
      zodiac_sign: sign,
      date: new Date().toISOString().split('T')[0]
    },
    {
      headers: {
        'Authorization': `Bearer ${VEDIKA_KEY}`,
        'Content-Type': 'application/json'
      }
    }
  );

  const data = response.data;
  return `♈ *${sign.toUpperCase()} - Today's Horoscope*

${data.prediction || data.horoscope}

🌟 Lucky Number: ${data.lucky_number || 'N/A'}
🎨 Lucky Color: ${data.lucky_color || 'N/A'}

_Powered by Vedika API_`;
}

// Generate Kundali (Birth Chart)
async function getKundali(message) {
  // Parse: kundali 1990-05-15 10:30 Delhi
  const parts = message.split(' ');
  if (parts.length < 4) {
    return '❌ Format: kundali YYYY-MM-DD HH:MM City\nExample: kundali 1990-05-15 10:30 Delhi';
  }

  const [_, date, time, ...placeParts] = parts;
  const place = placeParts.join(' ');

  const response = await axios.post(
    `${VEDIKA_API}/v1/kundali/basic`,
    {
      date: date,
      time: time,
      place: place,
      timezone: 'Asia/Kolkata'
    },
    {
      headers: {
        'Authorization': `Bearer ${VEDIKA_KEY}`,
        'Content-Type': 'application/json'
      }
    }
  );

  const data = response.data;
  const planets = data.planets || [];

  let planetList = planets.slice(0, 5).map(p =>
    `${p.name}: ${p.sign} ${p.degree}°`
  ).join('\n');

  return `📜 *Your Kundali*

🌙 Moon Sign: ${data.moon_sign || 'N/A'}
☀️ Sun Sign: ${data.sun_sign || 'N/A'}
⬆️ Ascendant: ${data.ascendant || 'N/A'}

*Planetary Positions:*
${planetList}

🔮 Nakshatra: ${data.nakshatra || 'N/A'}

_Generated by Vedika API_`;
}

// Compatibility matching
async function getCompatibility(message) {
  const parts = message.split(' ');
  if (parts.length < 3) {
    return '❌ Format: match sign1 sign2\nExample: match aries leo';
  }

  const [_, sign1, sign2] = parts;

  const response = await axios.post(
    `${VEDIKA_API}/v1/compatibility/zodiac`,
    {
      sign1: sign1,
      sign2: sign2
    },
    {
      headers: {
        'Authorization': `Bearer ${VEDIKA_KEY}`,
        'Content-Type': 'application/json'
      }
    }
  );

  const data = response.data;
  const score = data.compatibility_score || data.score || 75;

  // Generate hearts based on score
  const hearts = '❤️'.repeat(Math.round(score / 20));

  return `💑 *${sign1.toUpperCase()} + ${sign2.toUpperCase()}*

${hearts} ${score}% Compatible

${data.summary || data.analysis || 'These signs have interesting dynamics together!'}

*Strengths:*
${data.strengths?.join(', ') || 'Communication, Trust'}

*Challenges:*
${data.challenges?.join(', ') || 'Different approaches to life'}

_Powered by Vedika API_`;
}

// Today's Panchang
async function getPanchang() {
  const today = new Date().toISOString().split('T')[0];

  const response = await axios.post(
    `${VEDIKA_API}/v1/panchang/daily`,
    {
      date: today,
      place: 'New Delhi',
      timezone: 'Asia/Kolkata'
    },
    {
      headers: {
        'Authorization': `Bearer ${VEDIKA_KEY}`,
        'Content-Type': 'application/json'
      }
    }
  );

  const data = response.data;

  return `🗓️ *Today's Panchang*
${today}

🌙 Tithi: ${data.tithi || 'N/A'}
🌟 Nakshatra: ${data.nakshatra || 'N/A'}
📅 Day: ${data.day || new Date().toLocaleDateString('en-US', {weekday: 'long'})}

☀️ Sunrise: ${data.sunrise || '6:30 AM'}
🌅 Sunset: ${data.sunset || '5:45 PM'}

⚠️ Rahu Kaal: ${data.rahu_kaal || '10:30 AM - 12:00 PM'}
✅ Shubh Muhurat: ${data.shubh_muhurat || 'Morning hours'}

_Powered by Vedika API_`;
}
5

Deploy & Configure Webhook

Deploy to cloud and connect to Twilio

Deploy to Railway (Free)

# Install Railway CLI
npm install -g @railway/cli

# Login and deploy
railway login
railway init
railway up

# Get your public URL (e.g., https://your-app.railway.app)

Configure Twilio Webhook

  1. 1. Go to Twilio Console → Messaging → Settings
  2. 2. Find WhatsApp Sandbox Settings
  3. 3. Set webhook URL to: https://your-app.railway.app/webhook
  4. 4. Set method to POST
  5. 5. Save and test!

Test Your Bot

Send these messages to your WhatsApp bot:

horoscope aries
kundali 1990-05-15 10:30 Mumbai
match leo scorpio
panchang

Production Tips

Rate Limiting

Implement rate limiting to prevent abuse. Consider using Redis for distributed rate limiting.

Caching

Cache horoscope responses for a day - they don't change frequently. Saves API calls!

Error Handling

Always wrap API calls in try-catch and provide friendly error messages to users.

Analytics

Track which features are most used. Vedika dashboard shows your API usage.

Next Steps

  • Add AI predictions using Vedika's /v1/ai/predict endpoint
  • Implement user sessions to remember birth details
  • Add image generation for kundali charts
  • Apply for WhatsApp Business API for production number

Ready to Build?

Get your free Vedika API key and start building today. 1,000 free API calls every month.

Related Articles