# A Discord /horoscope command on an interactions endpoint

> A Discord slash command does not need a bot process holding a gateway connection. Discord can POST each interaction to an HTTPS endpoint you own; you verify the signature, answer within three seconds, and that is the whole bot.

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

**How this page was verified:** The endpoint ran on Node 24 against the in-memory API, called with interactions signed by a real Ed25519 key pair generated for the test in place of Discord's. Both reply paths ran: the immediate reply, and the deferred one, whose follow-up went to a local server standing in for Discord's webhook API. Discord itself was not contacted and the command registration request was not sent.

## Register the command once

Slash commands are declared to Discord, not discovered. One `PUT` to the application's commands sets the full list. Give `sign` a fixed set of choices whose values are exactly what the API expects: [`GET /v1/horoscope/daily/{sign}`](https://astronode.dev/capabilities/western/horoscope-daily-sign) takes capitalised English names, and `leo` is a `400 VALIDATION_ERROR`. With choices, Discord cannot send anything else.

`PUT https://discord.com/api/v10/applications/{APPLICATION_ID}/commands` with `Authorization: Bot <token>` (not sent in our run):

```json
[
  {
    "name": "horoscope",
    "description": "Today's horoscope for a sun sign",
    "options": [
      {
        "name": "sign",
        "description": "Your sun sign",
        "type": 3,
        "required": true,
        "choices": [
          { "name": "Aries", "value": "Aries" }, { "name": "Taurus", "value": "Taurus" },
          { "name": "Gemini", "value": "Gemini" }, { "name": "Cancer", "value": "Cancer" },
          { "name": "Leo", "value": "Leo" }, { "name": "Virgo", "value": "Virgo" },
          { "name": "Libra", "value": "Libra" }, { "name": "Scorpio", "value": "Scorpio" },
          { "name": "Sagittarius", "value": "Sagittarius" }, { "name": "Capricorn", "value": "Capricorn" },
          { "name": "Aquarius", "value": "Aquarius" }, { "name": "Pisces", "value": "Pisces" }
        ]
      }
    ]
  }
]
```

Then set the endpoint's public URL as the **Interactions Endpoint URL** in the Developer Portal. Discord saves it only if the endpoint answers its signed `PING` with `{"type": 1}`, and it also sends requests with bad signatures to make sure you reject them - so the verification below is not optional.

## The endpoint

A web-standard handler (`Request` in, `Response` out), so it mounts in a Node server, a Next.js route or a serverless function. Discord gives the application's public key as 64 hex characters; `node:crypto` verifies Ed25519 natively once the raw key is wrapped in its SPKI header - no `tweetnacl` or `discord-interactions` package needed:

discord.mjs

```js
// discord.mjs - a Discord interactions endpoint: POST /discord/interactions
import { createPublicKey, verify } from "node:crypto";

const ASTRONODE = process.env.ASTRONODE_BASE_URL ?? "https://api.astronode.dev";
const DISCORD = process.env.DISCORD_API ?? "https://discord.com/api/v10";
// The application's public key, as the Developer Portal shows it: 64 hex characters.
// Node wants a SPKI key, which for Ed25519 is a fixed 12-byte header + the 32 raw bytes.
const PUBLIC_KEY = createPublicKey({
  key: Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), Buffer.from(process.env.DISCORD_PUBLIC_KEY, "hex")]),
  format: "der",
  type: "spki",
});
const ACK_BUDGET_MS = Number(process.env.ACK_BUDGET_MS ?? 2000); // Discord allows 3 s for the first response

const cache = new Map(); // "Leo:2026-12-05" -> text; one call per sign per day, shared by every server

async function horoscope(sign) {
  const date = new Date().toISOString().slice(0, 10); // the API's day is the UTC day
  const key = `${sign}:${date}`;
  if (!cache.has(key)) {
    const res = await fetch(`${ASTRONODE}/v1/horoscope/daily/${sign}?date=${date}`, {
      headers: { Authorization: `Bearer ${process.env.ASTRONODE_API_KEY}` },
    });
    if (!res.ok) throw new Error(`horoscope ${res.status}`);
    const { data } = await res.json();
    cache.set(key, `**${data.sign}, ${data.weekday} ${data.date}**\n${data.summary}\nFocus: ${data.focus_areas.join(", ")}`);
  }
  return cache.get(key);
}

export async function handleDiscord(request, { waitUntil = (p) => p } = {}) {
  const raw = await request.text(); // verify the exact bytes Discord signed, before JSON.parse
  const sig = request.headers.get("x-signature-ed25519") ?? "";
  const ts = request.headers.get("x-signature-timestamp") ?? "";
  const ok = /^[0-9a-f]{128}$/i.test(sig) && verify(null, Buffer.from(ts + raw), PUBLIC_KEY, Buffer.from(sig, "hex"));
  if (!ok) return new Response("invalid request signature", { status: 401 });

  const interaction = JSON.parse(raw);
  if (interaction.type === 1) return Response.json({ type: 1 }); // PING when you save the URL

  if (interaction.type === 2 && interaction.data.name === "horoscope") {
    const sign = interaction.data.options.find((o) => o.name === "sign").value; // a fixed choice: "Leo"
    const work = horoscope(sign);
    const timer = new Promise((r) => setTimeout(r, ACK_BUDGET_MS, "slow"));
    const first = await Promise.race([work.catch(() => "failed"), timer]);
    if (first !== "slow") {
      const content = first === "failed" ? "The horoscope service did not answer. Try again in a minute." : first;
      return Response.json({ type: 4, data: { content } }); // CHANNEL_MESSAGE_WITH_SOURCE
    }
    // Too slow for 3 s: acknowledge now ("thinking..."), then edit the original message.
    waitUntil(work.catch(() => "The horoscope service did not answer. Try again in a minute.").then(
      (content) => fetch(`${DISCORD}/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
        method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify({ content }),
      }),
    ));
    return Response.json({ type: 5 }); // DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE
  }
  return Response.json({ type: 4, data: { content: "Unknown command" } });
}
```

- **One call per sign per day.** The cache key is sign plus the UTC date, the day the endpoint uses, so a thousand servers asking for Leo cost one call. The daily horoscope is on the Free plan.
- **Three seconds, then defer.** If the API has not answered in two seconds, the handler replies `type: 5` (Discord shows "thinking…") and edits that message when the text arrives. `waitUntil` keeps the edit alive after the response is sent; on a long-running server it can simply let the promise run.
- **Failures are messages, not errors.** A thrown error would leave the user with "The application did not respond". Both paths turn an API failure into a sentence.

## Test it without Discord

Generate an Ed25519 key pair, give the handler the public half in Discord's format and sign requests with the private half exactly as Discord does - over the timestamp followed by the raw body:

test-discord.mjs

```js
// Harness: a real Ed25519 key pair stands in for Discord's; requests are signed like Discord signs them.
import { generateKeyPairSync, sign } from "node:crypto";
import { createServer } from "node:http";
const { publicKey, privateKey } = generateKeyPairSync("ed25519");
process.env.DISCORD_PUBLIC_KEY = publicKey.export({ format: "der", type: "spki" }).subarray(12).toString("hex");
const patches = [];
const fake = createServer((req, res) => { let b = ""; req.on("data", (c) => (b += c)); req.on("end", () => { patches.push([req.method, req.url, b]); res.end("{}"); }); }).listen(4473);
process.env.DISCORD_API = "http://127.0.0.1:4473/api/v10";
const { handleDiscord } = await import("./discord.mjs");

const send = async (body, { tamper = false } = {}) => {
  const raw = JSON.stringify(body);
  const ts = String(Math.floor(Date.now() / 1000));
  const sig = sign(null, Buffer.from(ts + raw), privateKey).toString("hex");
  const req = new Request("http://bot.local/discord/interactions", {
    method: "POST",
    headers: { "x-signature-ed25519": sig, "x-signature-timestamp": ts, "content-type": "application/json" },
    body: tamper ? raw.replace("Leo", "Aries") : raw,
  });
  const pending = [];
  const res = await handleDiscord(req, { waitUntil: (p) => pending.push(p) });
  await Promise.all(pending);
  return `${res.status} ${await res.text()}`;
};
const cmd = { type: 2, application_id: "123", token: "tok", data: { name: "horoscope", options: [{ name: "sign", type: 3, value: "Leo" }] } };
console.log("PING           ->", await send({ type: 1 }));
console.log("/horoscope Leo ->", await send(cmd));
console.log("tampered body  ->", await send(cmd, { tamper: true }));
console.log("public key hex length:", process.env.DISCORD_PUBLIC_KEY.length);
console.log("follow-ups sent:", patches.map(([m, u, b]) => `${m} ${u} ${b.slice(0, 40)}...`));
fake.close();
```

Output:

```text
PING           -> 200 {"type":1}
/horoscope Leo -> 200 {"type":4,"data":{"content":"**Leo, Saturday 2026-12-05**\nThe 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.\nFocus: Home, mother, and the people you don't perform for, Rest without guilt, Fixing something domestic"}}
tampered body  -> 401 invalid request signature
public key hex length: 64
follow-ups sent: []
```

Output with `ACK_BUDGET_MS=0`, forcing the deferred path:

```text
PING           -> 200 {"type":1}
/horoscope Leo -> 200 {"type":5}
tampered body  -> 401 invalid request signature
public key hex length: 64
follow-ups sent: [
  'PATCH /api/v10/webhooks/123/tok/messages/@original {"content":"**Leo, Saturday 2026-12-05**...'
]
```

Changing one word of the signed body (`Leo` to `Aries`) made the signature fail, which is the property that stops anyone else from posting commands to your URL.

## The mistake that bites first: verifying parsed JSON

The signature covers the bytes Discord sent. If a framework parses the body first - `express.json()`, for instance - and you verify `JSON.stringify(req.body)`, the bytes differ (spacing, key order, escaped characters) and every request fails, including the `PING`, so the Developer Portal refuses to save your URL. Read the raw body (`request.text()` here, `express.raw({ type: "application/json" })` in Express), verify it, then parse.

For a bot that pushes a horoscope every morning rather than answering a command, see the [Telegram horoscope bot template](https://astronode.dev/templates/telegram-horoscope-bot); for bots that answer questions about the user's own chart, the [messaging bot use case](https://astronode.dev/use-cases/messaging-bot).

## Questions

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

1 endpoint: Daily Sun Sign Horoscope (`GET /v1/horoscope/daily/:sign`).

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

The endpoint ran on Node 24 against the in-memory API, called with interactions signed by a real Ed25519 key pair generated for the test in place of Discord's. Both reply paths ran: the immediate reply, and the deferred one, whose follow-up went to a local server standing in for Discord's webhook API. Discord itself was not contacted and the command registration request was not sent.

## Endpoints

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