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.
Open Telegram and search for
@BotFather -
2.
Send
/newbot -
3.
Choose a name:
Astro Guru Bot -
4.
Choose username:
astroguru_vedika_bot -
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. Push code to GitHub
- 2. Create account at render.com
- 3. Create new "Background Worker"
- 4. Connect GitHub repo
- 5. Add environment variables
- 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.