← Integrations

Backend · JavaScript

A Slack slash command for today's panchang

A team spread across Mumbai and London can ask Slack for today's panchang in either city. The command handler checks that the request really came from Slack, answers immediately, and posts the result a moment later through the response_url Slack hands it.

Updated

How this page was checked: The handler ran on Node 24 against the in-memory API, called with form-encoded slash-command requests signed with HMAC-SHA256 and a test signing secret, exactly as Slack signs them. A local server stood in for response_url and received both follow-up messages shown. Slack itself was not contacted.

How a slash command arrives

  • Form-encoded, not JSON. The body is application/x-www-form-urlencoded: command, text (whatever followed the command), user_id, response_url and more.
  • Signed. X-Slack-Signature is v0= plus the hex HMAC-SHA256 of v0:{timestamp}:{raw body} under your app's signing secret; X-Slack-Request-Timestamp is the timestamp. Slack's guidance is to reject anything more than five minutes old, which stops a captured request being replayed later.
  • Three seconds. Slack shows the user an error if your endpoint has not answered by then. The answer can be a placeholder; the real message goes to response_url, which Slack accepts for a while after the command (up to five posts within 30 minutes).

The handler

The city list carries IANA zone names. The local date and UTC offset are worked out from the zone at request time, so London is sent tz_offset_minutes: 0 in December and 60 in summer without a table of dates. The panchang itself comes from POST /v1/panchang, whose times are UTC instants; they are shown in each city's own clock:

slack.mjs

js
// slack.mjs - a Slack slash command: /panchang <city>, at POST /slack/panchang
import { createHmac, timingSafeEqual } from "node:crypto";

const ASTRONODE = process.env.ASTRONODE_BASE_URL ?? "https://api.astronode.dev";
const CITIES = {
  mumbai: { name: "Mumbai", zone: "Asia/Kolkata", lat: 19.076, lng: 72.8777 },
  bengaluru: { name: "Bengaluru", zone: "Asia/Kolkata", lat: 12.9716, lng: 77.5946 },
  london: { name: "London", zone: "Europe/London", lat: 51.5074, lng: -0.1278 },
  "new york": { name: "New York", zone: "America/New_York", lat: 40.7128, lng: -74.006 },
};

function verifySlack(raw, headers, secret, nowSec = Date.now() / 1000) {
  const ts = headers.get("x-slack-request-timestamp") ?? "";
  if (Math.abs(nowSec - Number(ts)) > 300) return false; // older than 5 minutes: a replay
  const mine = Buffer.from("v0=" + createHmac("sha256", secret).update(`v0:${ts}:${raw}`).digest("hex"));
  const theirs = Buffer.from(headers.get("x-slack-signature") ?? "");
  return mine.length === theirs.length && timingSafeEqual(mine, theirs);
}

// Local date and UTC offset in the city's zone (DST included), and local clock times.
const parts = (zone, ms) => Object.fromEntries(new Intl.DateTimeFormat("en-CA", {
  timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit", timeZoneName: "longOffset" })
  .formatToParts(ms).map((p) => [p.type, p.value]));
const offsetMinutes = (gmt) => { const m = /GMT([+-])(\d\d):(\d\d)/.exec(gmt); return m ? (m[1] === "-" ? -1 : 1) * (+m[2] * 60 + +m[3]) : 0; };
const clock = (zone, iso, day) => {
  const t = new Intl.DateTimeFormat("en-GB", { timeZone: zone, hour: "2-digit", minute: "2-digit" }).format(Date.parse(iso));
  const p = parts(zone, Date.parse(iso));
  return `${p.year}-${p.month}-${p.day}` === day ? t : `${t} on ${p.day}/${p.month}`; // tithis cross midnight
};

async function panchangFor(city) {
  const p = parts(city.zone, Date.now());
  const body = { date: `${p.year}-${p.month}-${p.day}`, tz_offset_minutes: offsetMinutes(p.timeZoneName), lat: city.lat, lng: city.lng };
  const res = await fetch(`${ASTRONODE}/v1/panchang`, {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.ASTRONODE_API_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`panchang ${res.status}`);
  const { data: d } = await res.json();
  return `*Panchang for ${city.name}, ${d.date}*\n` +
    `${d.vara.name} · ${d.tithi.paksha} ${d.tithi.name} until ${clock(city.zone, d.tithi.end, d.date)} · ${d.nakshatra.name} · ${d.yoga.name} yoga\n` +
    `Sunrise ${clock(city.zone, d.sunrise, d.date)} · Sunset ${clock(city.zone, d.sunset, d.date)} (${city.zone})`;
}

export async function handleSlack(request, { waitUntil }) {
  const raw = await request.text();
  if (!verifySlack(raw, request.headers, process.env.SLACK_SIGNING_SECRET)) {
    return new Response("bad signature", { status: 401 });
  }
  const form = new URLSearchParams(raw); // slash commands are form-encoded, not JSON
  const city = CITIES[(form.get("text") ?? "").trim().toLowerCase()];
  if (!city) {
    return Response.json({ response_type: "ephemeral", text: `Try one of: ${Object.values(CITIES).map((c) => c.name).join(", ")}` });
  }
  // Answer inside Slack's 3 seconds, then post the result to response_url when it is ready.
  waitUntil(panchangFor(city)
    .then((text) => ({ response_type: "in_channel", text }))
    .catch(() => ({ response_type: "ephemeral", text: "The panchang service did not answer. Try again shortly." }))
    .then((msg) => fetch(form.get("response_url"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(msg) })));
  return Response.json({ response_type: "ephemeral", text: `Looking up today's panchang for ${city.name}...` });
}

The signature check runs on the raw text before anything is parsed, and timingSafeEqual compares in constant time - after a length check, because it throws on buffers of different lengths. A city that is not in the list gets an ephemeral hint, seen only by the person who typed the command.

Run it against fake Slack requests

test-slack.mjs

js
// Harness: a test signing secret, requests signed exactly as Slack signs them, and a local
// server standing in for response_url. Slack itself is not contacted.
import { createHmac } from "node:crypto";
import { createServer } from "node:http";
process.env.SLACK_SIGNING_SECRET = "8f742231b10e8888abcd99yyyzzz85a5";
const posted = [];
const hook = createServer((req, res) => { let b = ""; req.on("data", (c) => (b += c)); req.on("end", () => { posted.push(JSON.parse(b)); res.end("ok"); }); }).listen(4474);
const { handleSlack } = await import("./slack.mjs");

const send = async (text, { age = 0, tamper = false } = {}) => {
  const raw = new URLSearchParams({ command: "/panchang", text, team_id: "T1", user_id: "U1",
    response_url: "http://127.0.0.1:4474/commands/T1/1/abc", trigger_id: "1.2.3" }).toString();
  const ts = String(Math.floor(Date.now() / 1000) - age);
  const sig = "v0=" + createHmac("sha256", process.env.SLACK_SIGNING_SECRET).update(`v0:${ts}:${raw}`).digest("hex");
  const req = new Request("http://bot.local/slack/panchang", { method: "POST", body: tamper ? raw.replace("Mumbai", "London") : raw,
    headers: { "content-type": "application/x-www-form-urlencoded", "x-slack-request-timestamp": ts, "x-slack-signature": sig } });
  const pending = [];
  const t0 = performance.now();
  const res = await handleSlack(req, { waitUntil: (p) => pending.push(p) });
  const ack = `${res.status} in ${Math.round(performance.now() - t0)} ms: ${await res.text()}`;
  await Promise.all(pending);
  return ack;
};
console.log("/panchang Mumbai  ->", await send("Mumbai"));
console.log("/panchang london  ->", await send("london"));
console.log("/panchang Paris   ->", await send("Paris"));
console.log("tampered          ->", await send("Mumbai", { tamper: true }));
console.log("6 minutes old     ->", await send("Mumbai", { age: 360 }));
for (const m of posted) console.log("\nresponse_url got:", JSON.stringify(m.response_type), "\n" + m.text);
hook.close();

Output (run on 5 Dec 2026):

text
/panchang Mumbai  -> 200 in 18 ms: {"response_type":"ephemeral","text":"Looking up today's panchang for Mumbai..."}
/panchang london  -> 200 in 1 ms: {"response_type":"ephemeral","text":"Looking up today's panchang for London..."}
/panchang Paris   -> 200 in 0 ms: {"response_type":"ephemeral","text":"Try one of: Mumbai, Bengaluru, London, New York"}
tampered          -> 401 in 0 ms: bad signature
6 minutes old     -> 401 in 0 ms: bad signature

response_url got: "in_channel" 
*Panchang for Mumbai, 2026-12-05*
Shanivara · Krishna Dwadashi until 00:52 on 06/12 · Chitra · Saubhagya yoga
Sunrise 06:57 · Sunset 18:00 (Asia/Kolkata)

response_url got: "in_channel" 
*Panchang for London, 2026-12-05*
Shanivara · Krishna Dwadashi until 19:22 · Swati · Shobhana yoga
Sunrise 07:49 · Sunset 15:52 (Europe/London)

The acknowledgements took 18 ms or less - the API call happens after them. The same tithi ends at the same instant in both cities: 19:22 in London is 00:52 the next day in Mumbai, which is why the handler adds the date when an end time falls on another day. Nakshatra and yoga differ between the cities because each is reported at that city's sunrise (panchang conventions).

The mistake that bites first: work after the response, on serverless

On a long-running Node server, a promise left running after you return the acknowledgement finishes normally. On serverless platforms the function may be frozen or stopped as soon as the response is sent, and the response_url post silently never happens - the user sees "Looking up…" and nothing else. Hand the promise to the platform's waitUntil (Vercel Functions and Cloudflare Workers both provide one), or put the job on a queue, which is why the handler takes waitUntil as a parameter rather than assuming a runtime. On AWS Lambda behind API Gateway, a queue is the dependable option.

The WhatsApp panchang bot template does the same panchang-per-city job for WhatsApp, with a larger city list and Rahu Kaal; the messaging bot use case covers bots that read the user's own chart.

Questions

Which AstroNode endpoints does the Slack example call?
1 endpoint: Panchang (POST /v1/panchang).
Was the Slack code on this page actually run?
The handler ran on Node 24 against the in-memory API, called with form-encoded slash-command requests signed with HMAC-SHA256 and a test signing secret, exactly as Slack signs them. A local server stood in for response_url and received both follow-up messages shown. Slack itself was not contacted.