Every sports Discord server eventually asks the same question: “What matches are on today?”
In this tutorial we’ll build a Discord bot with a single, polished slash command:
/fixtures sport:cricket date:2026-11-21
It returns a clean embed of matches grouped by competition. We’ll cover:
Registering slash commands with dropdown choices for 13 sports
Calling a sports API safely from Node.js
A small TTL cache so busy servers don’t burn your quota
Rate-limit and error handling with friendly messages
Ideas for adding goal alerts with webhooks
The data comes from the Orbistats API, which covers 13 sports under one schema, so one command handles every sport.
Prerequisites
Node.js 20+ (built-in fetch)
A Discord account and a server where you can add bots
An Orbistats API key via Request Access. You can also test requests in the sandbox.
Step 1: Create the Discord Application
Open the Discord Developer Portal and click New Application.
Under Bot, click Reset Token and copy it.
Copy the Application ID from the General Information page.
Under OAuth2 → URL Generator, tick bot and applications.commands, then open the generated URL to invite the bot to your test server.
Copy your server’s ID (enable Developer Mode, then right-click the server).
Step 2: Project Setup
bash
mkdir sports-discord-bot && cd sports-discord-bot
npm init -y
npm install discord.js dotenv
In package.json add "type": "module". Create .env:
bash
DISCORD_TOKEN=your_bot_token
DISCORD_CLIENT_ID=your_application_id
DISCORD_GUILD_ID=your_test_server_id
ORBISTATS_API_KEY=your_orbistats_key
Add .env to .gitignore immediately.
Step 3: Define the Sports List Once
Create sports.js. The value is the sport segment of the API path. Football and cricket are used in Orbistats’ public examples. Confirm the others in the API reference.
js
export const SPORTS = [
{ name: "⚽ Football", value: "football" },
{ name: "🏀 Basketball", value: "basketball" },
{ name: "🏈 American Football", value: "american-football" },
{ name: "🏏 Cricket", value: "cricket" },
{ name: "🎾 Tennis", value: "tennis" },
{ name: "⚾ Baseball", value: "baseball" },
{ name: "🎮 Esports", value: "esports" },
{ name: "🥊 Combat Sports", value: "combat-sports" },
{ name: "🏐 Volleyball", value: "volleyball" },
{ name: "🤾 Handball", value: "handball" },
{ name: "🏒 Ice Hockey", value: "ice-hockey" },
{ name: "⛳ Golf", value: "golf" },
{ name: "🏇 Horse Racing", value: "horse-racing" },
];
Discord allows up to 25 choices per option, so 13 sports fit comfortably.
Step 4: The API Client with a TTL Cache
Create orbistats.js:
js
const BASE_URL = "https://api.orbistats.com/v1";
const TTL_MS = 60_000;
const cache = new Map();
export class RateLimitedError extends Error {}
export async function getFixtures({ sport, date, perPage = 50 }) {
const cacheKey = ${sport}:${date}:${perPage};
const hit = cache.get(cacheKey);
if (hit && hit.expires > Date.now()) return hit.value;
const url = new URL(${BASE_URL}/${sport}/fixtures);
url.searchParams.set("date", date);
url.searchParams.set("per_page", String(perPage));
const res = await fetch(url, {
headers: {
Authorization: Bearer ${process.env.ORBISTATS_API_KEY},
Accept: "application/json",
},
signal: AbortSignal.timeout(8000),
});
if (res.status === 429) throw new RateLimitedError("rate limited");
if (!res.ok) throw new Error(Upstream HTTP ${res.status});
const json = await res.json(); // { data, meta, pagination }
cache.set(cacheKey, { value: json, expires: Date.now() + TTL_MS });
return json;
}
Why cache? In a popular server, twenty people may run /fixtures sport:football within a minute. With a 60-second cache that’s one upstream request instead of twenty.
Step 5: Register the Slash Command
Create deploy-commands.js:
js
import "dotenv/config";
import { REST, Routes, SlashCommandBuilder } from "discord.js";
import { SPORTS } from "./sports.js";
const command = new SlashCommandBuilder()
.setName("fixtures")
.setDescription("Show fixtures for a sport and date")
.addStringOption((o) =>
o.setName("sport").setDescription("Which sport?").setRequired(true).addChoices(...SPORTS)
)
.addStringOption((o) =>
o.setName("date").setDescription("YYYY-MM-DD (defaults to today, UTC)")
);
const rest = new REST({ version: "10" }).setToken(process.env.DISCORD_TOKEN);
await rest.put(
Routes.applicationGuildCommands(process.env.DISCORD_CLIENT_ID, process.env.DISCORD_GUILD_ID),
{ body: [command.toJSON()] }
);
console.log("✅ Slash command registered");
Run it once:
bash
node deploy-commands.js
Guild commands update instantly, which is ideal while developing. Switch to Routes.applicationCommands(clientId) for global deployment later (propagation can take a while).
Step 6: The Bot Itself
Create index.js:
js
import "dotenv/config";
import { Client, EmbedBuilder, Events, GatewayIntentBits } from "discord.js";
import { getFixtures, RateLimitedError } from "./orbistats.js";
import { SPORTS } from "./sports.js";
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
function sportLabel(value) {
return SPORTS.find((s) => s.value === value)?.name ?? value;
}
function formatKickoff(iso) {
const ms = Date.parse(iso);
if (Number.isNaN(ms)) return iso ?? "TBA";
return <t:${Math.floor(ms / 1000)}:t>; // Discord renders in each user's timezone
}
function buildEmbed({ sport, date, json }) {
const fixtures = json.data ?? [];
const embed = new EmbedBuilder()
.setTitle(${sportLabel(sport)} fixtures · ${date})
.setColor(0x1db954)
.setFooter({ text: "Data: Orbistats" })
.setTimestamp();
if (fixtures.length === 0) {
return embed.setDescription("No fixtures found for this date.");
}
const byCompetition = {};
for (const f of fixtures) (byCompetition[f.competition ?? "Other"] ||= []).push(f);
let description = "";
for (const [competition, items] of Object.entries(byCompetition)) {
const block =
**${competition}**\n +
items.map((f) => ${formatKickoff(f.kickoff)} — ${f.home_team} vs ${f.away_team}).join("\n") +
"\n\n";
if (description.length + block.length > 3800) {
description += "…and more. Narrow by date to see the rest.";
break;
}
description += block;
}
return embed.setDescription(description.trim());
}
client.once(Events.ClientReady, (c) => console.log(Logged in as ${c.user.tag}));
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand() || interaction.commandName !== "fixtures") return;
const sport = interaction.options.getString("sport", true);
const date = interaction.options.getString("date") ?? new Date().toISOString().slice(0, 10);
if (!DATE_RE.test(date)) {
return interaction.reply({ content: "Please use the format YYYY-MM-DD.", ephemeral: true });
}
await interaction.deferReply(); // we have 15 minutes instead of 3 seconds
try {
const json = await getFixtures({ sport, date });
await interaction.editReply({ embeds: [buildEmbed({ sport, date, json })] });
} catch (err) {
console.error(err.message); // never log the API key
const message =
err instanceof RateLimitedError
? "⏳ The data provider is busy. Try again in a minute."
: "⚠️ Couldn't load fixtures right now. Please try again later.";
await interaction.editReply({ content: message });
}
});
client.login(process.env.DISCORD_TOKEN);
Run it:
bash
node index.js
In Discord type /fixtures, choose a sport and watch the embed appear.
Why These Design Choices Matter
deferReply() Discord requires a response within 3 seconds. API calls can be slower, so defer first, then edit the reply.
Discord timestamps () Every user sees kickoff in their own timezone. No timezone maths and no confused fans.
Embed size limits Embed descriptions max out at 4096 characters. We stop at roughly 3800 and add a “…and more” line instead of crashing.
Friendly errors Users don’t need to see HTTP 429. They need to know when to retry.
Step 7: Keep the Bot Running
For quick hosting use any Node-friendly platform. A minimal Dockerfile:
dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
CMD ["node", "index.js"]
Pass secrets as environment variables on the host, never inside the image.
Level-Up Ideas
Goal and result alerts. Instead of polling, receive pushed events through webhooks and post to a channel via a Discord webhook. See also the Live Scores API.
Per-server favourite sport. Store a default sport per guild so /fixtures needs no arguments.
Autocomplete for competitions. Use competition_id filters and Discord’s autocomplete interactions.
Live command. Add /live that reads the live endpoint and refreshes one message every 30 seconds.
Odds helper. Combine fixtures with an odds-conversion command, using ideas from Python Odds Converter: Decimal, American & Fractional Odds.
Multi-Sport for Free
Because Orbistats exposes cricket, tennis, basketball, football and nine more sports through a consistent schema, the same buildEmbed function renders all of them. That’s the payoff of a unified API: one command, thirteen sports, zero per-sport code.
If you’d like a deeper Node.js walkthrough for a single sport, read Build a Cricket Fixtures Finder + Live Scoreboard in Node.js.
Production Checklist
[ ] Secrets in environment variables
[ ] 60-second cache (done) and a per-user cooldown if your server is large
[ ] Friendly handling of 401, 429 and 5xx (done)
[ ] Timeouts on every upstream call (done)
[ ] Review the data licensing terms before running a public bot
[ ] Compare plans on the pricing page so your access window matches your traffic
Resources
Orbistats API reference
Documentation
Orbistats Discord community
Get API access
Which sport should get its own custom embed next? Tell me below. 🏏🎾🏀
Top comments (0)