# An Alexa skill on Lambda: horoscope by sign and today's panchang

> "Alexa, ask Star Calendar for the horoscope for Leo." A custom skill turns that into a JSON request to a Lambda function, which calls AstroNode and returns a sentence to speak. The handler is short; the details that matter are the slot, the time limit and checking who sent the request.

Source: https://astronode.dev/integrations/alexa · Updated: 2026-12-05

**How this page was verified:** The Lambda handler ran on Node 24 against the in-memory API, invoked directly with Alexa-shaped request envelopes written by hand (launch, two intents with matched and unmatched slots, session end, and a request for another skill). Neither Alexa nor AWS Lambda was involved, and the interaction model was not uploaded to a skill.

## The interaction model

Two intents: one with a `sign` slot, one with none. The slot uses a custom type with synonyms, so "the lion" resolves to `Leo` - and the canonical value is exactly what the horoscope endpoint expects, capital letter included:

Interaction model excerpt (Alexa developer console → JSON Editor; not uploaded in our run):

```json
{
  "interactionModel": {
    "languageModel": {
      "invocationName": "star calendar",
      "intents": [
        { "name": "HoroscopeIntent",
          "slots": [{ "name": "sign", "type": "ZODIAC_SIGN" }],
          "samples": ["horoscope for {sign}", "what does today hold for {sign}", "{sign} horoscope"] },
        { "name": "PanchangIntent", "slots": [],
          "samples": ["what is today's panchang", "today's tithi", "panchang for today"] },
        { "name": "AMAZON.HelpIntent", "samples": [] },
        { "name": "AMAZON.StopIntent", "samples": [] },
        { "name": "AMAZON.CancelIntent", "samples": [] }
      ],
      "types": [
        { "name": "ZODIAC_SIGN", "values": [
          { "name": { "value": "Leo", "synonyms": ["the lion"] } },
          { "name": { "value": "Sagittarius", "synonyms": ["the archer"] } },
          { "name": { "value": "Aries" } }
        ] }
      ]
    }
  }
}
```

List all twelve signs in `ZODIAC_SIGN`; three are shown. Alexa returns both what it heard (`slot.value`) and the resolved canonical value - always read the resolved one.

## The Lambda handler

index.mjs

```js
// index.mjs - AWS Lambda handler for an Alexa custom skill (Node.js runtime, ES module)
const ASTRONODE = process.env.ASTRONODE_BASE_URL ?? "https://api.astronode.dev";
const SKILL_ID = process.env.ALEXA_SKILL_ID; // amzn1.ask.skill.…
const HOME = { name: "Mumbai", zone: "Asia/Kolkata", tz_offset_minutes: 330, lat: 19.076, lng: 72.8777 };

const say = (text, end = true) => ({
  version: "1.0",
  response: { outputSpeech: { type: "PlainText", text }, shouldEndSession: end },
});

const api = async (path, init) => {
  const res = await fetch(ASTRONODE + path, {
    ...init,
    headers: { Authorization: `Bearer ${process.env.ASTRONODE_API_KEY}`, "Content-Type": "application/json" },
    signal: AbortSignal.timeout(4000), // Alexa gives the whole skill about 8 seconds
  });
  if (!res.ok) throw new Error(`${path} ${res.status}`);
  return (await res.json()).data;
};

// The slot's resolved canonical value, not what was heard: "lion" or "leo" both -> "Leo".
const resolved = (slot) =>
  slot?.resolutions?.resolutionsPerAuthority?.find((a) => a.status.code === "ER_SUCCESS_MATCH")?.values[0].value.name;

const localDate = (ms) => new Intl.DateTimeFormat("en-CA", { timeZone: HOME.zone }).format(ms);
const spokenTime = (iso, today) => {
  const t = new Intl.DateTimeFormat("en-US", { timeZone: HOME.zone, hour: "numeric", minute: "2-digit" }).format(Date.parse(iso));
  return localDate(Date.parse(iso)) > today ? `${t} tomorrow` : t;
};

export const handler = async (event) => {
  // Lambda's Alexa trigger checks the skill ID when you set one; check it here as well.
  const appId = event.context?.System?.application?.applicationId ?? event.session?.application?.applicationId;
  if (appId !== SKILL_ID) throw new Error("request is not for this skill");

  const { request } = event;
  if (request.type === "LaunchRequest") return say("Ask for your horoscope by sign, or for today's panchang.", false);
  if (request.type === "SessionEndedRequest") return {}; // no speech allowed here
  if (request.type !== "IntentRequest") return say("Sorry, I can't help with that.");

  const intent = request.intent.name;
  const today = localDate(Date.now()); // the listener's day, not the server's UTC day
  try {
    if (intent === "HoroscopeIntent") {
      const sign = resolved(request.intent.slots?.sign);
      if (!sign) return say("Which sign? For example, Leo or Pisces.", false);
      const h = await api(`/v1/horoscope/daily/${sign}?date=${today}`);
      return say(`${sign}. ${h.summary} Focus on ${h.focus_areas.slice(0, 2).join(" and ").toLowerCase()}.`);
    }
    if (intent === "PanchangIntent") {
      const { tz_offset_minutes, lat, lng } = HOME;
      const p = await api("/v1/panchang", { method: "POST", body: JSON.stringify({ date: today, tz_offset_minutes, lat, lng }) });
      return say(`Today in ${HOME.name} it is ${p.tithi.paksha} ${p.tithi.name}, until ${spokenTime(p.tithi.end, today)}. ` +
        `The nakshatra is ${p.nakshatra.name}. The sun rises at ${spokenTime(p.sunrise, today)} and sets at ${spokenTime(p.sunset, today)}.`);
    }
    if (intent === "AMAZON.HelpIntent") return say("Say: horoscope for Leo. Or: what is today's panchang.", false);
    if (intent === "AMAZON.StopIntent" || intent === "AMAZON.CancelIntent") return say("Goodbye.");
    return say("Sorry, I don't know that one.");
  } catch {
    return say("The astrology service is not answering right now. Please try again later.");
  }
};
```

- **The listener's day, not UTC.** Both calls pass the date in the skill's home zone. Without `date`, the horoscope endpoint uses the UTC day, which in India is still yesterday until 05:30.
- **Times are converted, then spoken.** The API returns UTC instants; the handler formats them in `Asia/Kolkata` and says "tomorrow" when a tithi ends after midnight, which a listener cannot see on a screen.
- **Plain text speech.** `PlainText` avoids SSML escaping. If you switch to SSML, escape `&`, `<` and `>` in anything that came from the API.
- **A fixed home city.** A device's location needs the user's permission and a separate Alexa API call; a fixed city or one stored per user is simpler. For a zone with daylight saving, derive the offset per date as the Slack page does.

## What Alexa would say

The handler was invoked with envelopes shaped like Alexa's - `context.System.application.applicationId`, `request.type`, and for intents the slot with its `resolutions`:

test-alexa.mjs

```js
// Harness: Alexa-shaped request envelopes, built by hand. Alexa itself is not contacted.
process.env.ALEXA_SKILL_ID = "amzn1.ask.skill.00000000-test";
const { handler } = await import("./alexa.mjs");
const ev = (request, skill = process.env.ALEXA_SKILL_ID) => ({
  version: "1.0",
  session: { new: true, sessionId: "s1", application: { applicationId: skill }, user: { userId: "u1" } },
  context: { System: { application: { applicationId: skill } } },
  request: { requestId: "r1", timestamp: new Date().toISOString(), locale: "en-IN", ...request },
});
const slot = (heard, match) => ({ sign: { name: "sign", value: heard, resolutions: { resolutionsPerAuthority: [match
  ? { authority: "amzn1.er-authority.echo-sdk.x.ZODIAC_SIGN", status: { code: "ER_SUCCESS_MATCH" }, values: [{ value: { name: match, id: match.toUpperCase() } }] }
  : { authority: "amzn1.er-authority.echo-sdk.x.ZODIAC_SIGN", status: { code: "ER_SUCCESS_NO_MATCH" } }] } } });
const speech = (r) => (r.response?.outputSpeech?.text ?? "(no speech)") + (r.response?.shouldEndSession === false ? "  [session stays open]" : "");

console.log("launch      :", speech(await handler(ev({ type: "LaunchRequest" }))));
console.log("'the lion'  :", speech(await handler(ev({ type: "IntentRequest", intent: { name: "HoroscopeIntent", slots: slot("the lion", "Leo") } }))));
console.log("'banana'    :", speech(await handler(ev({ type: "IntentRequest", intent: { name: "HoroscopeIntent", slots: slot("banana", null) } }))));
console.log("panchang    :", speech(await handler(ev({ type: "IntentRequest", intent: { name: "PanchangIntent" } }))));
console.log("ended       :", JSON.stringify(await handler(ev({ type: "SessionEndedRequest", reason: "USER_INITIATED" }))));
try { await handler(ev({ type: "LaunchRequest" }, "amzn1.ask.skill.someone-else")); } catch (e) { console.log("other skill :", e.message); }
```

Output (run on 5 Dec 2026):

```text
launch      : Ask for your horoscope by sign, or for today's panchang.  [session stays open]
'the lion'  : Leo. The Moon is in your house of home, roots and inner peace - it rules this house, so the pull inward is strong and worth honouring. Saturday is Saturn's day: slow, patient work pays, and shortcuts rarely do. Focus on home, mother, and the people you don't perform for and rest without guilt.
'banana'    : Which sign? For example, Leo or Pisces.  [session stays open]
panchang    : Today in Mumbai it is Krishna Dwadashi, until 12:52 AM tomorrow. The nakshatra is Chitra. The sun rises at 6:57 AM and sets at 6:00 PM.
ended       : {}
other skill : request is not for this skill
```

"banana" came back as `ER_SUCCESS_NO_MATCH` and the skill asked again with the session left open, instead of sending `banana` to the API. `SessionEndedRequest` gets an empty response: Alexa does not allow speech there.

## Verifying requests, and the timeout that bites first

- **On Lambda:** add the Alexa Skills Kit trigger with skill ID verification turned on, so Lambda refuses invocations for other skills. The handler checks `applicationId` as well, which is what the last line of the output shows.
- **On your own HTTPS endpoint** (no Lambda), you must verify each request yourself: the `SignatureCertChainUrl` and `Signature-256` headers (the certificate must come from Amazon's documented host and chain to a trusted root) and a request timestamp no more than 150 seconds old. That is not implemented here - use the verifier in Amazon's ASK SDK (`ask-sdk-express-adapter` for Express) rather than writing it.
- **The Lambda timeout.** A new function defaults to a 3-second timeout, while Alexa waits up to about 8 seconds for a skill. A cold start plus an API call can exceed 3 seconds, and the user hears a generic failure. Raise the function timeout to about 7 seconds and keep the `fetch` timeout below it (4 seconds above), so the catch branch gets to speak.
- **The key** goes in the function's environment variables (encrypted at rest) or AWS Secrets Manager, never in the interaction model or the skill's public assets.

Text bots for the same content: [Discord](https://astronode.dev/integrations/discord), [Slack](https://astronode.dev/integrations/slack), and the [Telegram](https://astronode.dev/templates/telegram-horoscope-bot) and [WhatsApp](https://astronode.dev/templates/whatsapp-panchang-bot) templates.

## Questions

**Which AstroNode endpoints does the Alexa example call?**

2 endpoints: Daily Sun Sign Horoscope (`GET /v1/horoscope/daily/:sign`); Panchang (`POST /v1/panchang`).

**Was the Alexa code on this page actually run?**

The Lambda handler ran on Node 24 against the in-memory API, invoked directly with Alexa-shaped request envelopes written by hand (launch, two intents with matched and unmatched slots, session end, and a request for another skill). Neither Alexa nor AWS Lambda was involved, and the interaction model was not uploaded to a skill.

## Endpoints

- [`GET /v1/horoscope/daily/:sign`](https://astronode.dev/capabilities/western/horoscope-daily-sign) - Daily Sun Sign Horoscope API
- [`POST /v1/panchang`](https://astronode.dev/capabilities/vedic/panchang) - Panchang API
