A WhatsApp Cloud API webhook in plain Node: someone texts a city and gets today's panchang for it in the city's own time - tithi with its end time, nakshatra, yoga, karana, sunrise, sunset and Rahu Kaal - or texts a sign and gets today's horoscope.
unzip whatsapp-panchang-bot.zip && cd whatsapp-panchang-bot
cp .env.example .env # AstroNode key + WhatsApp token, phone number id, verify token, app secret
npm run dev # then expose the port over HTTPS and set it as the webhook
Files (20)
.env.example1 KB
.gitignore1 KB
README.md6 KB
package.json1 KB
src/astronode.js3 KB
src/bot.js4 KB
src/cities.js3 KB
src/config.js1 KB
src/horoscope.js2 KB
src/index.js2 KB
src/panchang.js3 KB
src/server.js3 KB
src/time.js2 KB
src/webhook.js2 KB
src/whatsapp.js2 KB
test/bot.test.js15 KB
test/fixtures/error-validation.json1 KB
test/fixtures/horoscope-daily-leo.json1 KB
test/fixtures/inauspicious-delhi.json1 KB
test/fixtures/panchang-delhi.json1 KB
src/bot.js
javascript
/**
* What a user texted -> what the bot replies. No HTTP here, so it is easy
* to test with stubs.
*/
import { AstroNodeError } from "./astronode.js";
import { CITIES, findCity } from "./cities.js";
import { formatHoroscope, normalizeSign, SIGNS, utcDate } from "./horoscope.js";
import { formatPanchang } from "./panchang.js";
export const SORRY = "Sorry, I couldn't fetch that right now. Please try again in a few minutes.";
export const HELP = [
"Namaste! Text me:",
"• a city name, e.g. *Mumbai*, for today's panchang there",
"• *panchang* for your last city",
"• *horoscope leo* for today's horoscope",
"",
`Cities: ${CITIES.map((c) => c.name).join(", ")}`,
].join("\n");
/**
* @param {string | undefined} text
* @returns {{ kind: "panchang", city: import("./cities.js").City | null, unknown?: string }
* | { kind: "horoscope", sign: string | null }
* | { kind: "help" }}
*/
export const parseMessage = (text) => {
const t = (text ?? "").trim().replace(/\s+/g, " ");
const lower = t.toLowerCase();
const m = /^(horoscope|rashifal)\b\s*(.*)$/.exec(lower);
if (m) return { kind: "horoscope", sign: normalizeSign(m[2]) };
if (normalizeSign(lower)) return { kind: "horoscope", sign: normalizeSign(lower) };
const p = /^panchang(?:am)?\b\s*(?:for|in)?\s*(.*)$/.exec(lower);
if (p) {
if (!p[1]) return { kind: "panchang", city: null };
const city = findCity(p[1]);
return city ? { kind: "panchang", city } : { kind: "panchang", city: null, unknown: t.slice(t.length - p[1].length) };
}
const city = findCity(lower);
if (city) return { kind: "panchang", city };
return { kind: "help" };
};
/** @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 {{
* panchangs: ReturnType<typeof import("./panchang.js").createPanchangCache>,
* horoscopes: ReturnType<typeof import("./horoscope.js").createHoroscopeCache>,
* defaultCity: import("./cities.js").City,
* now?: () => Date,
* }} deps
*/
export const createBot = ({ panchangs, horoscopes, defaultCity, now = () => new Date() }) => {
// Each sender's last city, so "panchang" alone works. In memory only:
// it resets on restart, which is harmless (falls back to defaultCity).
/** @type {Map<string, string>} */
const lastCity = new Map();
/**
* @param {string} from sender's WhatsApp ID (phone number)
* @param {string | undefined} text
* @returns {Promise<string>}
*/
const reply = async (from, text) => {
const msg = parseMessage(text);
if (msg.kind === "help") return HELP;
try {
if (msg.kind === "horoscope") {
if (!msg.sign) return `Which sign? e.g. *horoscope leo*\nSigns: ${SIGNS.join(", ")}`;
return formatHoroscope(await horoscopes.get(msg.sign, utcDate(now())));
}
if (msg.unknown) return `I don't know "${msg.unknown}" yet.\nCities: ${CITIES.map((c) => c.name).join(", ")}`;
const city = msg.city ?? (lastCity.has(from) ? findCity(lastCity.get(from)) : null) ?? defaultCity;
lastCity.delete(from);
lastCity.set(from, city.slug);
if (lastCity.size > 10_000) lastCity.delete(lastCity.keys().next().value);
const { panchang, inauspicious } = await panchangs.get(city);
return formatPanchang(city, panchang, inauspicious);
} catch (err) {
logApiError(err);
return SORRY;
}
};
return { reply };
};
src/webhook.js
javascript
/**
* WhatsApp Cloud API webhook pieces: the GET verification handshake, the
* X-Hub-Signature-256 check, and pulling text messages out of a payload.
* https://developers.facebook.com/docs/graph-api/webhooks/getting-started
*/
import { createHmac, timingSafeEqual } from "node:crypto";
/**
* GET /webhook?hub.mode=subscribe&hub.verify_token=...&hub.challenge=...
* Meta expects the challenge echoed back as plain text with 200.
* @param {URLSearchParams} query
* @param {string} verifyToken
* @returns {{ status: number, body: string }}
*/
export const verifyHandshake = (query, verifyToken) => {
const mode = query.get("hub.mode");
const token = query.get("hub.verify_token") ?? "";
const challenge = query.get("hub.challenge") ?? "";
if (mode === "subscribe" && safeEqual(token, verifyToken)) return { status: 200, body: challenge };
return { status: 403, body: "Forbidden" };
};
/** Constant-time string compare (different lengths are simply unequal). */
const safeEqual = (a, b) => {
const x = Buffer.from(a);
const y = Buffer.from(b);
return x.length === y.length && timingSafeEqual(x, y);
};
/**
* Meta signs the exact request bytes with your app secret:
* X-Hub-Signature-256: sha256=<hex HMAC-SHA256(appSecret, rawBody)>
* Verify against the raw body, before JSON.parse.
* @param {Buffer | string} rawBody
* @param {string | undefined} header
* @param {string} appSecret
*/
export const verifySignature = (rawBody, header, appSecret) => {
if (!header || !header.startsWith("sha256=")) return false;
const expected = createHmac("sha256", appSecret).update(rawBody).digest("hex");
return safeEqual(header.slice("sha256=".length), expected);
};
/**
* All inbound text messages in a webhook payload. Status updates (sent,
* delivered, read) and non-text messages are skipped.
* @param {any} payload
* @returns {Array<{ id: string, from: string, text: string, phoneNumberId: string | undefined }>}
*/
export const extractTextMessages = (payload) => {
const out = [];
if (payload?.object !== "whatsapp_business_account") return out;
for (const entry of payload.entry ?? []) {
for (const change of entry.changes ?? []) {
const value = change.value ?? {};
for (const m of value.messages ?? []) {
if (m.type === "text" && typeof m.text?.body === "string") {
out.push({ id: m.id, from: m.from, text: m.text.body, phoneNumberId: value.metadata?.phone_number_id });
}
}
}
}
return out;
};
src/panchang.js
javascript
/**
* Today's panchang for a city: two API calls (panchang + inauspicious),
* cached per city per local day, and formatted for WhatsApp.
*/
import { formatTime, localDate, noonOffsetMinutes } from "./time.js";
/** @typedef {import("./cities.js").City} City */
/**
* The request body both endpoints take.
* @param {City} city @param {string} date YYYY-MM-DD (local to the city)
*/
export const placeBody = (city, date) => ({
date,
tz_offset_minutes: noonOffsetMinutes(date, city.zone),
lat: city.lat,
lng: city.lng,
});
/**
* @param {{
* client: { panchang: (b: any) => Promise<any>, inauspicious: (b: any) => Promise<any> },
* now?: () => Date,
* }} deps
*/
export const createPanchangCache = ({ client, now = () => new Date() }) => {
/** @type {Map<string, Promise<{ panchang: any, inauspicious: any }>>} */
const entries = new Map();
return {
/**
* @param {City} city
* @returns {Promise<{ date: string, panchang: any, inauspicious: any }>}
*/
async get(city) {
const date = localDate(city.zone, now());
const key = `${city.slug}|${date}`;
// Each city has its own "today"; drop entries for any other day of it.
for (const k of entries.keys()) if (k.startsWith(`${city.slug}|`) && k !== key) entries.delete(k);
let p = entries.get(key);
if (!p) {
const body = placeBody(city, date);
p = Promise.all([
client.panchang(body),
// Rahu Kaal needs the Hobby plan. On Free (403 PLAN_REQUIRED) still
// send the rest of the panchang instead of failing the whole reply.
client.inauspicious(body).catch((err) => {
if (err?.code !== "PLAN_REQUIRED") throw err;
console.warn(`[astronode] ${err.message} - Rahu Kaal left out (needs the Hobby plan)`);
return { planRequired: true };
}),
]).then(([panchang, inauspicious]) => ({ panchang, inauspicious }));
entries.set(key, p);
p.catch(() => entries.delete(key));
}
return { date, ...(await p) };
},
get size() {
return entries.size;
},
};
};
/**
* @param {City} city
* @param {any} p data from POST /v1/panchang
* @param {any} bad data from POST /v1/muhurta/inauspicious
*/
export const formatPanchang = (city, p, bad) => {
const t = (iso) => formatTime(iso, city.zone, p.date);
const [y, m, d] = p.date.split("-").map(Number);
const day = new Intl.DateTimeFormat("en-GB", { timeZone: "UTC", weekday: "long", day: "numeric", month: "short", year: "numeric" }).format(
new Date(Date.UTC(y, m - 1, d)),
);
const rk = bad?.rahu_kaal;
return [
`*Panchang - ${city.name}*`,
`${day} (${p.vara.name})`,
"",
`*Tithi:* ${p.tithi.paksha} ${p.tithi.name}, until ${t(p.tithi.end)}`,
`*Nakshatra:* ${p.nakshatra.name}`,
`*Yoga:* ${p.yoga.name}`,
`*Karana:* ${p.karana.name}`,
`*Sunrise:* ${t(p.sunrise)}`,
`*Sunset:* ${t(p.sunset)}`,
...(bad?.planRequired ? [] : [`*Rahu Kaal:* ${rk ? `${t(rk.start)} - ${t(rk.end)}` : "not applicable today"}`]),
"",
`_Times in ${city.zone}_`,
].join("\n");
};
What it does
Understands a city name (20 built in, with aliases such as Bombay and NYC), panchang (the user's last city), panchang for <city>, and horoscope <sign> or a bare sign.
Works out each city's UTC offset at local noon, so daylight saving and offsets such as Kathmandu's +5:45 come out right, and shows every time in the city's own zone.
Caches the panchang per city per local day, calling the two endpoints in parallel.
Verifies X-Hub-Signature-256 on the raw body with a constant-time compare, answers Meta's verification handshake, replies 200 at once and ignores retried message ids.
With a Free key, POST /v1/muhurta/inauspicious answers PLAN_REQUIRED; the bot then sends the panchang without the Rahu Kaal line instead of failing.
Endpoints and plan
API calls the template makes
Endpoint
Used for
Plan
POST /v1/panchang
Tithi, nakshatra, yoga, karana, sunrise, sunset
Free
POST /v1/muhurta/inauspicious
Rahu Kaal
Hobby
GET /v1/horoscope/daily/{sign}
Today's horoscope for a sign
Free
It needs a Hobby key or above: at least one endpoint it calls is not on the Free plan. See pricing.
Where things live
File
What it holds
src/bot.js
Parses each message and picks the reply
src/webhook.js
Handshake, signature check, extracting text messages
src/panchang.js
The per-city-per-day cache and the message format
src/time.js
Local date, offset at local noon, time formatting
src/cities.js
The built-in city list - extend it or swap in a geocoder
src/whatsapp.js
Sends replies through the Graph API
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.
Meta needs a public HTTPS webhook URL. While developing, a tunnel such as cloudflared or ngrok in front of the local port works.
Runs on any Node host that accepts HTTPS - a VPS behind a reverse proxy, or a web service on a platform such as Render or Fly.
Keep the app secret set: without it the signature check cannot run.
Questions
Does the WhatsApp bot work on the Free plan?
Partly. The panchang and horoscope endpoints are on Free; Rahu Kaal needs Hobby. With a Free key the bot sends the panchang without the Rahu Kaal line.
Can users ask for any city?
The template knows 20 cities with aliases. Add more to src/cities.js, or replace the lookup with a geocoder that returns coordinates and an IANA zone.
Why is the panchang computed per city and not per user?
The panchang depends only on the place and the local day, so every user asking for Delhi today shares one cached answer.