TUTORIAL NODE.JS

Build a Telegram Horoscope Bot with Vedika API

Create a Telegram bot that delivers daily horoscopes, generates kundali charts, and provides AI-powered astrological insights.

December 2025 12 min read Beginner friendly

šŸ¤– What You'll Build

Bot Commands

  • /horoscope aries - Daily horoscope
  • /kundali - Generate birth chart
  • /match leo virgo - Compatibility
  • /panchang - Today's calendar
  • /predict - AI prediction

Features

  • āœ… Inline keyboard buttons
  • āœ… User session management
  • āœ… Multi-step conversations
  • āœ… Formatted responses with emoji
1

Create Telegram Bot with BotFather

Get your bot token from Telegram

  1. 1. Open Telegram and search for @BotFather
  2. 2. Send /newbot
  3. 3. Choose a name: Astro Guru Bot
  4. 4. Choose username: astroguru_vedika_bot
  5. 5. Copy the bot token (looks like: 123456789:ABCdef...)
2

Project Setup

Initialize Node.js project

# Create project
mkdir telegram-astro-bot && cd telegram-astro-bot

# Initialize
npm init -y

# Install dependencies
npm install node-telegram-bot-api axios dotenv

Create .env file

# .env
TELEGRAM_BOT_TOKEN=your_bot_token_here
VEDIKA_API_KEY=your_vedika_api_key_here
3

Build the Bot

Create main bot file with all commands

// index.js
require('dotenv').config();
const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');

const bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, { polling: true });
const VEDIKA_API = 'https://vedika-api-854222120654.us-central1.run.app';
const VEDIKA_KEY = process.env.VEDIKA_API_KEY;

// Zodiac signs for keyboard
const ZODIAC_SIGNS = [
  ['ā™ˆ Aries', '♉ Taurus', 'ā™Š Gemini'],
  ['♋ Cancer', 'ā™Œ Leo', 'ā™ Virgo'],
  ['ā™Ž Libra', 'ā™ Scorpio', '♐ Sagittarius'],
  ['♑ Capricorn', 'ā™’ Aquarius', '♓ Pisces']
];

// /start command
bot.onText(/\/start/, (msg) => {
  const chatId = msg.chat.id;
  const firstName = msg.from.first_name;

  bot.sendMessage(chatId, `
šŸ”® *Welcome to Astro Guru Bot, ${firstName}!*

I can help you with:
/horoscope - Daily horoscope by zodiac
/kundali - Generate your birth chart
/match - Check compatibility
/panchang - Today's Hindu calendar
/predict - AI-powered prediction

Choose a zodiac sign to get started:
  `, {
    parse_mode: 'Markdown',
    reply_markup: {
      inline_keyboard: ZODIAC_SIGNS.map(row =>
        row.map(sign => ({
          text: sign,
          callback_data: `horoscope_${sign.split(' ')[1].toLowerCase()}`
        }))
      )
    }
  });
});

// /horoscope command
bot.onText(/\/horoscope(.*)/, async (msg, match) => {
  const chatId = msg.chat.id;
  const sign = match[1]?.trim().toLowerCase();

  if (!sign) {
    // Show zodiac selection keyboard
    bot.sendMessage(chatId, 'šŸ”® *Select your zodiac sign:*', {
      parse_mode: 'Markdown',
      reply_markup: {
        inline_keyboard: ZODIAC_SIGNS.map(row =>
          row.map(s => ({
            text: s,
            callback_data: `horoscope_${s.split(' ')[1].toLowerCase()}`
          }))
        )
      }
    });
    return;
  }

  await sendHoroscope(chatId, sign);
});

// Handle callback queries (button clicks)
bot.on('callback_query', async (query) => {
  const chatId = query.message.chat.id;
  const data = query.data;

  if (data.startsWith('horoscope_')) {
    const sign = data.replace('horoscope_', '');
    await bot.answerCallbackQuery(query.id, { text: `Loading ${sign}...` });
    await sendHoroscope(chatId, sign);
  }
});

// Send horoscope helper
async function sendHoroscope(chatId, sign) {
  try {
    bot.sendChatAction(chatId, 'typing');

    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;
    const emoji = getZodiacEmoji(sign);

    const message = `
${emoji} *${sign.toUpperCase()} - Today's Horoscope*

${data.prediction || data.horoscope || 'The stars are aligning in your favor today!'}

🌟 *Lucky Number:* ${data.lucky_number || Math.floor(Math.random() * 9) + 1}
šŸŽØ *Lucky Color:* ${data.lucky_color || 'Blue'}
šŸ’° *Career:* ${data.career || 'Focus on priorities'}
ā¤ļø *Love:* ${data.love || 'Express your feelings'}

_Powered by Vedika API_
    `;

    bot.sendMessage(chatId, message, {
      parse_mode: 'Markdown',
      reply_markup: {
        inline_keyboard: [
          [{ text: 'šŸ”„ Check Another Sign', callback_data: 'show_signs' }],
          [{ text: 'šŸ’‘ Compatibility Check', callback_data: 'show_match' }]
        ]
      }
    });
  } catch (error) {
    console.error('Horoscope error:', error.message);
    bot.sendMessage(chatId, 'āŒ Sorry, couldn\'t fetch horoscope. Try again!');
  }
}

// /kundali command
bot.onText(/\/kundali/, (msg) => {
  const chatId = msg.chat.id;

  bot.sendMessage(chatId, `
šŸ“œ *Generate Your Birth Chart (Kundali)*

Please send your birth details in this format:
\`YYYY-MM-DD HH:MM City\`

Example:
\`1990-05-15 10:30 Mumbai\`
  `, { parse_mode: 'Markdown' });

  // Listen for next message
  bot.once('message', async (reply) => {
    if (reply.chat.id !== chatId) return;

    const parts = reply.text.split(' ');
    if (parts.length < 3) {
      bot.sendMessage(chatId, 'āŒ Invalid format. Use: YYYY-MM-DD HH:MM City');
      return;
    }

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

    try {
      bot.sendChatAction(chatId, 'typing');

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

      const data = response.data;

      const message = `
šŸ“œ *Your Birth Chart (Kundali)*

šŸ“… Birth: ${date} at ${time}
šŸ“ Place: ${place}

šŸŒ™ *Moon Sign:* ${data.moon_sign || 'Calculating...'}
ā˜€ļø *Sun Sign:* ${data.sun_sign || 'Calculating...'}
ā¬†ļø *Ascendant:* ${data.ascendant || 'Calculating...'}
🌟 *Nakshatra:* ${data.nakshatra || 'Calculating...'}

*Planetary Positions:*
${formatPlanets(data.planets)}

_Generated by Vedika API_
      `;

      bot.sendMessage(chatId, message, { parse_mode: 'Markdown' });
    } catch (error) {
      console.error('Kundali error:', error.message);
      bot.sendMessage(chatId, 'āŒ Error generating kundali. Check format!');
    }
  });
});

// /match command
bot.onText(/\/match(.*)/, async (msg, match) => {
  const chatId = msg.chat.id;
  const args = match[1]?.trim().split(' ').filter(Boolean);

  if (!args || args.length < 2) {
    bot.sendMessage(chatId, `
šŸ’‘ *Compatibility Check*

Send two zodiac signs:
\`/match aries leo\`
\`/match cancer pisces\`
    `, { parse_mode: 'Markdown' });
    return;
  }

  const [sign1, sign2] = args;

  try {
    bot.sendChatAction(chatId, 'typing');

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

    const data = response.data;
    const score = data.compatibility_score || data.score || Math.floor(Math.random() * 30) + 60;
    const hearts = 'ā¤ļø'.repeat(Math.round(score / 20));

    const message = `
šŸ’‘ *${sign1.toUpperCase()} + ${sign2.toUpperCase()}*

${hearts} *${score}% Compatible*

${data.summary || data.analysis || 'These signs can create beautiful harmony together with understanding.'}

*Strengths:*
āœ… ${data.strengths?.slice(0, 3).join('\nāœ… ') || 'Good communication\nEmotional support\nShared values'}

*Challenges:*
āš ļø ${data.challenges?.slice(0, 2).join('\nāš ļø ') || 'Different approaches\nNeed for patience'}

*Tip:* ${data.advice || 'Focus on understanding each other\'s needs.'}

_Powered by Vedika API_
    `;

    bot.sendMessage(chatId, message, { parse_mode: 'Markdown' });
  } catch (error) {
    console.error('Match error:', error.message);
    bot.sendMessage(chatId, 'āŒ Error checking compatibility. Try again!');
  }
});

// /panchang command
bot.onText(/\/panchang/, async (msg) => {
  const chatId = msg.chat.id;

  try {
    bot.sendChatAction(chatId, 'typing');

    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;

    const message = `
šŸ—“ļø *Today's Panchang*
${today}

šŸŒ™ *Tithi:* ${data.tithi || 'Shukla Paksha'}
🌟 *Nakshatra:* ${data.nakshatra || 'Rohini'}
šŸ“… *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'}
āœ… *Abhijit Muhurat:* ${data.abhijit_muhurat || '11:45 AM - 12:30 PM'}

šŸ”® *Today is good for:*
${data.auspicious_for?.join(', ') || 'Starting new ventures, travel, meetings'}

_Powered by Vedika API_
    `;

    bot.sendMessage(chatId, message, { parse_mode: 'Markdown' });
  } catch (error) {
    console.error('Panchang error:', error.message);
    bot.sendMessage(chatId, 'āŒ Error fetching panchang. Try again!');
  }
});

// Helper functions
function getZodiacEmoji(sign) {
  const emojis = {
    aries: 'ā™ˆ', taurus: '♉', gemini: 'ā™Š', cancer: '♋',
    leo: 'ā™Œ', virgo: 'ā™', libra: 'ā™Ž', scorpio: 'ā™',
    sagittarius: '♐', capricorn: '♑', aquarius: 'ā™’', pisces: '♓'
  };
  return emojis[sign.toLowerCase()] || 'šŸ”®';
}

function formatPlanets(planets) {
  if (!planets || !Array.isArray(planets)) {
    return '🪐 Sun in Leo\nšŸŒ™ Moon in Cancer\nā™‚ļø Mars in Aries';
  }
  return planets.slice(0, 5).map(p =>
    `${p.name}: ${p.sign} ${p.degree || ''}°`
  ).join('\n');
}

console.log('šŸš€ Astro Guru Bot is running!');
console.log('šŸ“± Add @your_bot_username on Telegram to test');
4

Run & Test

Start your bot and test commands

# Run the bot
node index.js

# You should see:
# šŸš€ Astro Guru Bot is running!

Test Commands

/start
/horoscope leo
/match aries cancer
/panchang
5

Deploy to Production

Keep your bot running 24/7

Option 1: Railway (Recommended)

# Deploy to Railway
npm install -g @railway/cli
railway login
railway init
railway up

Option 2: Render

  1. 1. Push code to GitHub
  2. 2. Create account at render.com
  3. 3. Create new "Background Worker"
  4. 4. Connect GitHub repo
  5. 5. Add environment variables
  6. 6. Deploy!

Advanced Features to Add

🧠 AI Predictions

Use Vedika's AI endpoint for personalized predictions based on birth chart.

šŸ“Š User Database

Store user birth details in MongoDB for quick lookups.

ā° Daily Notifications

Send automatic daily horoscopes using node-cron.

šŸ–¼ļø Chart Images

Generate visual kundali charts using canvas or puppeteer.

Start Building Today!

Get your free Vedika API key - 1,000 calls/month included.

Related Tutorials