A Telegram bot in plain Node: a user picks their zodiac sign, asks for today's horoscope whenever they like, and gets it pushed once a day. A thousand Leo subscribers still cost one API call a day.
unzip telegram-horoscope-bot.zip && cd telegram-horoscope-bot
cp .env.example .env # ASTRONODE_API_KEY and TELEGRAM_BOT_TOKEN from @BotFather
npm run dev # long polling, no public URL needed
Files (14)
.env.example1 KB
.gitignore1 KB
README.md4 KB
package.json1 KB
src/astronode.js2 KB
src/bot.js5 KB
src/config.js1 KB
src/horoscope.js2 KB
src/index.js2 KB
src/store.js2 KB
src/telegram.js2 KB
test/bot.test.js10 KB
test/fixtures/error-validation.json1 KB
test/fixtures/horoscope-daily-leo.json1 KB
src/bot.js
javascript
/**
* The bot's logic, free of I/O wiring so it can be tested with stubs:
* command parsing, replies, and the daily push.
*/
import { AstroNodeError } from "./astronode.js";
import { formatHoroscope, normalizeSign, SIGNS, utcDate } from "./horoscope.js";
export const SORRY = "Sorry, I couldn't fetch the horoscope right now. Please try again in a few minutes.";
const SIGN_LIST = SIGNS.join(", ");
export const HELP = [
"I send a short daily horoscope.",
"",
"/sign <sign> - subscribe this chat, e.g. /sign leo",
"/today - today's horoscope for your sign",
"/stop - unsubscribe",
"",
`Signs: ${SIGN_LIST}`,
].join("\n");
/**
* "/sign@MyBot Leo" -> { command: "sign", args: "Leo" }. Non-commands -> null.
* @param {string | undefined} text
* @returns {{ command: string, args: string } | null}
*/
export const parseCommand = (text) => {
const m = /^\/([a-z_]+)(?:@\w+)?(?:\s+([\s\S]*))?$/i.exec((text ?? "").trim());
if (!m) return null;
return { command: m[1].toLowerCase(), args: (m[2] ?? "").trim() };
};
/** @param {unknown} err */
const logApiError = (err) => {
if (err instanceof AstroNodeError) {
console.error(`[astronode] ${err.path ?? ""} status=${err.status ?? "-"} code=${err.code ?? "-"} request_id=${err.requestId ?? "-"}: ${err.message}`);
} else {
console.error("[astronode]", err);
}
};
/**
* @param {{
* store: Awaited<ReturnType<typeof import("./store.js").createStore>>,
* horoscopes: ReturnType<typeof import("./horoscope.js").createHoroscopeCache>,
* send: (chatId: string | number, text: string) => Promise<unknown>,
* now?: () => Date,
* }} deps
*/
export const createBot = ({ store, horoscopes, send, now = () => new Date() }) => {
/** @param {string} sign */
const horoscopeText = async (sign) => {
try {
return formatHoroscope(await horoscopes.get(sign, utcDate(now())));
} catch (err) {
logApiError(err);
return SORRY;
}
};
/**
* Reply text for one incoming message, or null to stay silent.
* @param {string | number} chatId @param {string | undefined} text
* @returns {Promise<string | null>}
*/
const reply = async (chatId, text) => {
const cmd = parseCommand(text);
if (!cmd) return null; // plain chatter in groups: ignore
switch (cmd.command) {
case "start":
case "help":
return HELP;
case "sign": {
const sign = normalizeSign(cmd.args);
if (!sign) return `Tell me which sign, e.g. /sign leo\nSigns: ${SIGN_LIST}`;
await store.subscribe(chatId, sign);
return `Subscribed to ${sign}. You'll get it every day; /today shows it now, /stop unsubscribes.`;
}
case "today": {
const sign = normalizeSign(cmd.args) ?? store.getSign(chatId);
if (!sign) return "Pick a sign first, e.g. /sign leo";
return horoscopeText(sign);
}
case "stop":
return (await store.unsubscribe(chatId))
? "Unsubscribed. Send /sign <sign> any time to come back."
: "You weren't subscribed.";
default:
return null;
}
};
/**
* Telegram update -> reply sent. Returns the reply text (handy in tests).
* @param {any} update
*/
const handleUpdate = async (update) => {
const msg = update?.message;
if (!msg?.chat?.id || typeof msg.text !== "string") return null;
const text = await reply(msg.chat.id, msg.text);
if (text) await send(msg.chat.id, text);
return text;
};
/**
* Send today's horoscope to every subscribed chat, once per UTC day, at or
* after `pushHourUtc`. Safe to call every minute; restarts do not resend
* because the push date is persisted.
* @param {number} pushHourUtc
* @param {{ onBlocked?: (chatId: string) => void }} [opts]
* @returns {Promise<{ sent: number, failed: number } | null>} null when nothing was due
*/
const pushDaily = async (pushHourUtc, opts = {}) => {
const t = now();
const today = utcDate(t);
if (t.getUTCHours() < pushHourUtc || store.lastPushDate() === today) return null;
await store.setLastPushDate(today);
let sent = 0;
let failed = 0;
for (const [chatId, sign] of store.subscriptions()) {
// One API call per sign, thanks to the cache.
let text;
try {
text = formatHoroscope(await horoscopes.get(sign, today));
} catch (err) {
// Do not push an apology to every subscriber; log it and skip.
logApiError(err);
failed++;
continue;
}
try {
await send(chatId, text);
sent++;
} catch (err) {
failed++;
// 403: the user blocked the bot or left the group. Stop sending.
if (/** @type {any} */ (err).code === 403) {
await store.unsubscribe(chatId);
opts.onBlocked?.(chatId);
} else {
console.error(`[telegram] push to ${chatId} failed:`, err instanceof Error ? err.message : err);
}
}
// Stay well under Telegram's ~30 messages/second broadcast limit.
await new Promise((r) => setTimeout(r, 40));
}
return { sent, failed };
};
return { reply, handleUpdate, pushDaily };
};
src/horoscope.js
javascript
/**
* Zodiac signs, a per-sign-per-day horoscope cache, and message formatting.
*/
export const SIGNS = [
"Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
"Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces",
];
const SYMBOLS = {
Aries: "♈", Taurus: "♉", Gemini: "♊", Cancer: "♋", Leo: "♌", Virgo: "♍",
Libra: "♎", Scorpio: "♏", Sagittarius: "♐", Capricorn: "♑", Aquarius: "♒", Pisces: "♓",
};
/**
* "leo", " LEO ", "♌" -> "Leo". Returns null for anything else.
* @param {string | undefined} input
* @returns {string | null}
*/
export const normalizeSign = (input) => {
if (!input) return null;
const s = input.trim().toLowerCase();
for (const sign of SIGNS) {
if (sign.toLowerCase() === s || SYMBOLS[sign] === s) return sign;
}
return null;
};
/** Today's date (YYYY-MM-DD) in UTC. */
export const utcDate = (now = new Date()) => now.toISOString().slice(0, 10);
/**
* One API call per sign per day, however many chats ask. Concurrent asks
* share the in-flight request; a failed call is not cached.
* @param {{ fetchHoroscope: (sign: string, date: string) => Promise<any> }} deps
*/
export const createHoroscopeCache = ({ fetchHoroscope }) => {
/** @type {Map<string, Promise<any>>} */
const entries = new Map();
return {
/** @param {string} sign @param {string} date */
get(sign, date) {
// Drop other days so the map never grows past 12 entries.
for (const key of entries.keys()) if (!key.endsWith(`|${date}`)) entries.delete(key);
const key = `${sign}|${date}`;
let p = entries.get(key);
if (!p) {
p = fetchHoroscope(sign, date);
entries.set(key, p);
p.catch(() => entries.delete(key));
}
return p;
},
get size() {
return entries.size;
},
};
};
/**
* Plain-text Telegram message (no parse_mode, so nothing needs escaping).
* @param {{ sign: string, date: string, weekday: string, summary: string, focus_areas: string[], cautions: string[] }} h
*/
export const formatHoroscope = (h) => {
const lines = [`${SYMBOLS[h.sign] ?? ""} ${h.sign} - ${h.weekday}, ${h.date}`.trim(), "", h.summary];
if (h.focus_areas?.length) lines.push("", "Focus on:", ...h.focus_areas.map((x) => `• ${x}`));
if (h.cautions?.length) lines.push("", "Watch out for:", ...h.cautions.map((x) => `• ${x}`));
return lines.join("\n");
};
What it does
Commands: /start, /sign <sign> to subscribe (any spelling or case), /today, and /stop.
Pushes today's horoscope to every subscriber once a UTC day at PUSH_HOUR_UTC; a bot that was down at that hour catches up on start, and never sends twice.
Caches one horoscope per sign per day and shares in-flight requests, so the cost is at most twelve calls a day whatever the audience.
Unsubscribes a chat when Telegram says the user blocked the bot. If the API fails during a push, that sign is skipped and logged rather than sending apologies.
Uses long polling, so it needs no public URL - only an always-on process.
Endpoints and plan
API calls the template makes
Endpoint
Used for
Plan
GET /v1/horoscope/daily/{sign}
Today's horoscope for a sign (?date=YYYY-MM-DD)
Free
Everything it calls is on the Free plan, so a Free test key runs the whole template.
Where things live
File
What it holds
src/bot.js
Command parsing, the four commands, the daily push
src/horoscope.js
Sign normalisation, the per-sign-per-day cache, message formatting
src/astronode.js
The API client; turns the error envelope into an AstroNodeError
src/store.js
Subscriptions in a JSON file, written atomically
src/telegram.js
getUpdates, sendMessage, deleteWebhook
Keys and deployment
The API key is read from the server's environment and sent as Authorization: Bearer <key>; it never reaches a browser or an app bundle.
npm run check runs the tests against API responses recorded in test/fixtures/ - no key and no network, so it can run in your CI.
Any always-on Node host: a small VPS with systemd or pm2, or a worker on a platform such as Railway, Render or Fly - no HTTP port needed.
Put SUBSCRIPTIONS_FILE on a persistent volume; on an ephemeral filesystem the subscriptions vanish on every deploy.
For serverless, switch to Telegram's setWebhook, call bot.handleUpdate() from your handler and bot.pushDaily() from a scheduled job.
Questions
How many API calls does the Telegram horoscope bot make?
At most one per zodiac sign per day - twelve - because each day's horoscope is cached per sign and shared by every subscriber.
Can the bot send horoscopes in Hindi?
The endpoint takes language=hi; the template sends English. Pass language in src/horoscope.js and keep a language per subscriber to offer both.
Does it need a server with a public URL?
No. It uses long polling, so any always-on process works. A webhook variant is described in the README for serverless hosts.