Starter project
Discord sports bot in TypeScript with slash commands
This starter is a TypeScript discord.js bot with two slash commands, /standings and /scores, that answer from PuckAPI's NHL data. The command logic sits in a plain function that takes the API as an argument, so four unit tests run with a mocked interaction and no Discord token. Six small files.
What you will build
A Discord bot with two slash commands. /standings replies with the league table, or one division if you pick it from the dropdown. /scores replies with the results for a date, defaulting to today in Eastern Time. Both answers are short monospace tables, so they line up in Discord's code block formatting and stay well under the 2,000 character message limit.
Sample replies, produced by running the real handlers against the live PuckAPI with a mocked interaction:
/standings division:Central
1 MIN 48 pts 21-5-6 GD +38
6 COL 41 pts 19-7-3 GD +40
8 DAL 38 pts 18-9-2 GD +12
11 NSH 36 pts 15-8-6 GD +8
14 UTA 35 pts 16-13-3 GD -10
15 STL 33 pts 15-11-3 GD +5
17 WPG 33 pts 14-12-5 GD -5
26 CHI 26 pts 12-16-2 GD -36
/scores date:2026-12-05
2026-12-05
PHI 1-2 MIN
TBL 0-4 OTT
FLA 2-4 MTL
WPG 2-3 VGK
NJD 7-4 PIT
CBJ 2-1 NSHIn Discord the reply appears under the slash command as one message, with the date in bold above a gray code block. The first number in each standings row is the league rank, then points, then wins, regulation losses and overtime losses, then goal difference.
Prerequisites
- Node.js 20 or newer (the run below used Node 26).
- A PuckAPI key. Each
/standingscosts 2 credits and each/scorescosts 5. - A Discord application with a bot user, created in the Discord developer portal. You need its token, its application id and the id of a test server. Registering commands to one server shows up instantly, while global commands can take up to an hour.
Keep the token and the API key in environment variables. Never commit either one.
The project
discord-sports-bot/
package.json
tsconfig.json
src/
api.ts PuckAPI client and types
commands.ts command definitions, formatters, handler
bot.ts logs in and routes interactions
register.ts one-off script that registers the commands
commands.test.ts unit tests with a mocked interactionInstall the dependencies:
npm i discord.js
npm i -D typescript tsx @types/nodepackage.json
{
"name": "nhl-discord-bot",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"typecheck": "tsc --noEmit",
"test": "node --import tsx --test src/commands.test.ts",
"register": "tsx src/register.ts",
"start": "tsx src/bot.ts"
},
"dependencies": {
"discord.js": "^14.28.1"
},
"devDependencies": {
"@types/node": "^26.6.11",
"tsx": "^4.23.15",
"typescript": "^7.0.2"
}
}tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"allowImportingTsExtensions": true
},
"include": ["src"]
}src/api.ts
// PuckAPI client. The key is read from the environment and never sent to Discord.
const BASE = process.env.PUCKAPI_BASE ?? "https://mcp.puckapi.com/v1";
export type Standing = {
rank: number;
teamAbbrev: string;
teamName: string;
division: string;
points: number;
gamesPlayed: number;
wins: number;
losses: number;
otLosses: number;
goalDiff: number;
};
export type Game = {
id: string;
gameDate: string;
startTime: string;
homeTeam: string;
awayTeam: string;
homeScore: number | null;
awayScore: number | null;
gameState: string; // FUT, LIVE, FINAL, OFF
};
export type PuckApi = {
standings(division?: string): Promise<Standing[]>;
games(date: string): Promise<Game[]>;
};
async function call<T>(tool: string, params: Record<string, unknown>): Promise<T> {
const key = process.env.PUCKAPI_KEY;
if (!key) throw new Error("PUCKAPI_KEY is not set");
const res = await fetch(`${BASE}/${tool}`, {
method: "POST",
headers: { "x-api-key": key, "Content-Type": "application/json" },
body: JSON.stringify(params),
});
if (!res.ok) throw new Error(`PuckAPI ${res.status}`);
const body = (await res.json()) as { data?: T } & T;
return (body.data ?? body) as T;
}
export const puckApi: PuckApi = {
async standings(division) {
const r = await call<{ standings: Standing[] }>("get_standings", division ? { division } : {});
return r.standings;
},
async games(date) {
const r = await call<{ games: Game[] }>("get_games", { date });
return r.games;
},
};src/commands.ts
import { SlashCommandBuilder, type ChatInputCommandInteraction } from "discord.js";
import type { PuckApi, Game, Standing } from "./api.ts";
// Only the parts of an interaction the handlers use, so tests can pass a plain object.
export type Reply = Pick<ChatInputCommandInteraction, "deferReply" | "editReply"> & {
options: { getString(name: string): string | null };
};
export const definitions = [
new SlashCommandBuilder()
.setName("standings")
.setDescription("NHL standings")
.addStringOption((o) =>
o.setName("division").setDescription("Limit to one division").addChoices(
{ name: "Atlantic", value: "Atlantic" },
{ name: "Metropolitan", value: "Metropolitan" },
{ name: "Central", value: "Central" },
{ name: "Pacific", value: "Pacific" },
),
),
new SlashCommandBuilder()
.setName("scores")
.setDescription("NHL scores for a date")
.addStringOption((o) => o.setName("date").setDescription("YYYY-MM-DD, default today (Eastern)")),
].map((c) => c.toJSON());
export function todayEastern(now = new Date()): string {
return now.toLocaleDateString("en-CA", { timeZone: "America/New_York" });
}
export function formatStandings(rows: Standing[], limit = 16): string {
const lines = rows.slice(0, limit).map((s) =>
`${String(s.rank).padStart(2)} ${s.teamAbbrev.padEnd(4)} ${String(s.points).padStart(3)} pts ` +
`${s.wins}-${s.losses}-${s.otLosses} GD ${s.goalDiff >= 0 ? "+" : ""}${s.goalDiff}`);
return "```\n" + lines.join("\n") + "\n```";
}
export function formatScores(games: Game[], date: string): string {
if (games.length === 0) return `No games on ${date}.`;
const lines = games.map((g) => {
const played = g.homeScore !== null && g.awayScore !== null && g.gameState !== "FUT";
const score = played ? `${g.awayScore}-${g.homeScore}` : "vs";
const state = g.gameState === "LIVE" ? " (live)" : "";
return `${g.awayTeam.padEnd(4)} ${score.padStart(5)} ${g.homeTeam}${state}`;
});
return `**${date}**\n` + "```\n" + lines.join("\n") + "\n```";
}
export async function handle(name: string, i: Reply, api: PuckApi): Promise<void> {
await i.deferReply(); // Discord gives 3 seconds to answer; the API call can take longer
try {
if (name === "standings") {
const division = i.options.getString("division") ?? undefined;
const rows = await api.standings(division);
await i.editReply(formatStandings(rows));
} else if (name === "scores") {
const date = i.options.getString("date") ?? todayEastern();
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
await i.editReply("Use the date format YYYY-MM-DD.");
return;
}
await i.editReply(formatScores(await api.games(date), date));
} else {
await i.editReply("Unknown command.");
}
} catch {
await i.editReply("The data service did not answer. Try again in a minute.");
}
}src/bot.ts
import { Client, Events, GatewayIntentBits } from "discord.js";
import { handle } from "./commands.ts";
import { puckApi } from "./api.ts";
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.once(Events.ClientReady, (c) => console.log(`Logged in as ${c.user.tag}`));
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
await handle(interaction.commandName, interaction, puckApi);
});
await client.login(process.env.DISCORD_TOKEN);src/register.ts
// Run once (and again whenever you change a command definition).
import { REST, Routes } from "discord.js";
import { definitions } from "./commands.ts";
const rest = new REST().setToken(process.env.DISCORD_TOKEN!);
await rest.put(
Routes.applicationGuildCommands(process.env.DISCORD_APP_ID!, process.env.DISCORD_GUILD_ID!),
{ body: definitions },
);
console.log(`Registered ${definitions.length} commands`);src/commands.test.ts
import test from "node:test";
import assert from "node:assert/strict";
import { handle, type Reply } from "./commands.ts";
import type { PuckApi } from "./api.ts";
function fakeInteraction(opts: Record<string, string> = {}) {
const calls: string[] = [];
const i = {
options: { getString: (n: string) => opts[n] ?? null },
deferReply: async () => { calls.push("defer"); },
editReply: async (m: unknown) => { calls.push(String(m)); },
} as unknown as Reply;
return { i, calls };
}
const api: PuckApi = {
standings: async () => [
{ rank: 1, teamAbbrev: "MIN", teamName: "Minnesota Wild", division: "Central",
points: 48, gamesPlayed: 32, wins: 21, losses: 5, otLosses: 6, goalDiff: 38 },
],
games: async (date) => date === "2026-12-05"
? [{ id: "1", gameDate: date, startTime: "", homeTeam: "MIN", awayTeam: "PHI",
homeScore: 2, awayScore: 1, gameState: "OFF" }]
: [],
};
test("standings defers, then edits with a table", async () => {
const { i, calls } = fakeInteraction();
await handle("standings", i, api);
assert.equal(calls[0], "defer");
assert.match(calls[1], /MIN\s+48 pts 21-5-6 GD \+38/);
});
test("scores formats a played game", async () => {
const { i, calls } = fakeInteraction({ date: "2026-12-05" });
await handle("scores", i, api);
assert.match(calls[1], /PHI\s+1-2 MIN/);
});
test("scores rejects a bad date without calling the API", async () => {
const { i, calls } = fakeInteraction({ date: "tomorrow" });
await handle("scores", i, { ...api, games: async () => { throw new Error("should not run"); } });
assert.match(calls[1], /YYYY-MM-DD/);
});
test("an API failure becomes a friendly reply", async () => {
const { i, calls } = fakeInteraction();
await handle("standings", i, { ...api, standings: async () => { throw new Error("boom"); } });
assert.match(calls[1], /did not answer/);
});How to run it
export PUCKAPI_KEY="your-puckapi-key"
export DISCORD_TOKEN="your-bot-token"
export DISCORD_APP_ID="your-application-id"
export DISCORD_GUILD_ID="your-test-server-id"
npm run typecheck # tsc, no output means no errors
npm test # four unit tests, no token needed
npm run register # once, and again after changing a command
npm start # logs the bot inInvite the bot to your test server with the bot and applications.commands scopes from the developer portal, then type /standings or /scores.
How it works
Separating logic from Discord. The handler in commands.ts never touches a real Discord client. It takes two arguments: an object shaped like the small part of an interaction it uses (deferReply, editReply and options.getString), and a PuckApi object with two methods. In production those are the live interaction and the real client from api.ts. In tests they are plain objects. That one decision is what makes the logic testable without a token or a network call.
Defer, then edit. Discord closes an interaction if you do not respond within three seconds. The handler calls deferReply() first, which shows the "thinking" state and extends the window, and sends the real text with editReply() when the API answers. Every path after the defer, including errors and bad input, ends with an editReply, so a command never hangs in the thinking state.
Command definitions. SlashCommandBuilder from discord.js builds the JSON that Discord stores. The division option uses fixed choices, so users pick from a list and cannot mistype. The date option is free text, which is why the handler checks it against YYYY-MM-DD before spending credits on a call.
Registration. register.ts sends the definitions to Discord with a PUT to the guild commands route, which replaces the full set for that server. Run it once, and again whenever you change a name, description or option. Normal code changes to the handler do not need re-registration.
Formatting. The formatters pad columns to a fixed width and wrap the result in a code block, because Discord uses a proportional font outside code blocks. Standings are cut to the first 16 rows so a full-league answer cannot exceed the message limit. A game without a score shows vs, and a live game gets a (live) tag, based on the gameState field PuckAPI returns.
The API client. api.ts posts JSON to /v1/<tool> with the x-api-key header and unwraps the data envelope. get_standings accepts an optional division, and get_games accepts a single date. The bot runs on your server, so the key is never sent to Discord or to users.
Ways to extend it
- Add a team option. Add an autocomplete string option for team abbreviation and pass it to
get_gameswith a date range, so/scores team:BUFshows recent results. - Cache replies. Standings change once per game day. Keep the last response in memory for a few minutes and answer repeat commands from it, which cuts credit use in a busy server.
- Add a schedule command. Call
get_schedule(2 credits) for the next few days and format it like/scores. The response carries start times, so convert them to Eastern Time with the same helper. - Use embeds. Replace the code block with a Discord embed that has a field per division. It looks better but is harder to unit test, so keep the formatter returning data and let a thin function build the embed.
Limits and when not to use this
- Login is untested here. The unit tests and typecheck cover the logic. Wiring to Discord (intents, token, registration) is standard discord.js but was not run for this page, so test it in a private server first.
- Credits per command. Every
/scorescall costs 5 credits and every/standingscall 2. A busy server can add that up, so cache replies before you invite many people. - Not live scoring. The bot answers from the API's current data. It does not stream goals as they happen and is a poor fit for a live alert channel.
- Message limits. Replies must stay under 2,000 characters. A full day of games in a busy season fits, but a long list of teams will not, so keep the row caps.
- Hosting. This design uses the gateway connection, so it needs a process that stays running. It does not run in a serverless function that sleeps between requests. For that, Discord's HTTP interactions model needs a different entry point.
- Terms. Showing results to your community is fine. Reposting the raw data as a feed or dataset of its own is not. See the PuckAPI documentation for the full terms.
FAQ
Do I need a Discord token to test the command logic? No. The handlers take an interaction-shaped object and an API object, so the tests pass plain fakes. You only need a token for the last step, logging the bot in to a real server, which this page could not do.
Why call deferReply first? Discord requires an answer within three seconds. deferReply buys up to fifteen minutes, so a slow API call cannot make the command fail. The final text is then sent with editReply.
Can I switch this to NBA data? Yes. Replace api.ts with calls to DunkAPI's get_standings and list_games, keep the handlers and tests, and adjust the field names in the two formatters. The command layer does not care where the rows come from.
Get a free key Or download whole seasons as Parquet
Checked against the live API on 2026-12-06. Questions: hello@sportsdatahq.com.