Skip to content

Livematches in play

Demo: Matchboard, opens in a new tab

Tutorial

Build a Discord bot for live football scores

This guide builds a Discord bot for live football scores in about 110 lines of Node.js. It needs no bot account and no Discord library: a channel webhook receives a message for each kick-off and goal in the leagues you follow, and the polling stays inside the Free plan's daily quota.

  • Free plan key
  • 20 min
  • Node.js
  • Discord webhooks
  • Updated

What you will build

A small Node.js process that asks for the football matches in play once a minute, compares each score with the one it saw last, and posts the differences to a Discord channel:

Messages in the channel (example)
Kick-off: Hull City 0 - 0 Brighton & Hove Albion (Premier League)
**Goal!** Hull City 1 - 0 Brighton & Hove Albion (Premier League, 1st half)
Score corrected: Hull City 0 - 0 Brighton & Hove Albion (Premier League)

Discord channel webhooks make this simple. A webhook is a secret URL that posts into one channel when you send it JSON, so you do not register an application, hold a bot token or keep a gateway connection open. The trade-off: a webhook can only talk, not listen, so there are no slash commands. For a scores feed that is all you need.

1. Create the channel webhook

  1. In Discord, open the settings of the channel that should get the scores (Edit Channel). You need the Manage Webhooks permission on the server.
  2. Go to Integrations, then Webhooks, and choose New Webhook. Give it a name and an avatar; they appear as the sender of every message.
  3. Choose Copy Webhook URL.

Treat that URL like a password: anyone who has it can post in your channel. Keep it in an environment variable next to your API key, which you get from your dashboard after you sign up:

Terminal
export DATASPORTSAPI_API_KEY="sk_live_…"
export DISCORD_WEBHOOK_URL="https://discord.com/api/webhooks/…"

Test the webhook before writing any code. Discord's Execute Webhook endpoint takes a JSON body whose content is the message text, up to 2,000 characters, and answers 204 No Content on success:

Terminal
curl -H "Content-Type: application/json" \
  -d '{"content": "Score bot connected"}' "$DISCORD_WEBHOOK_URL"

2. Read the live scores

GET /v2/livescores?sport=football returns every football match in play, across all competitions, in one call. A match, trimmed to the fields the bot reads:

Response (trimmed)
{
  "data": [
    {
      "id": 1065088,
      "status": { "type": "inprogress", "description": "1st half" },
      "league": { "id": 860530, "name": "Kupa e Shqiperise", "category": "Albania" },
      "home": { "name": "Flamurtari FC" },
      "away": { "name": "Butrinti Sarandë" },
      "homeScore": { "current": 1 },
      "awayScore": { "current": 0 }
    }
  ],
  "meta": { "sport": "football", "count": 120 }
}

On a busy afternoon that list holds over a hundred matches, most of them from leagues your server does not care about. The bot keeps the ones whose league.id is in a set you choose. Some ids to start with: Premier League 195828, LaLiga 4408, Serie A 195910, Bundesliga 195937, Ligue 1 195793, Champions League 4409. For any other competition, GET /v2/search?q=…&type=league finds the id.

3. The bot

Save this as bot.mjs. It uses only what ships with Node.js 18 or later (fetch and AbortSignal.timeout), so there is nothing to install:

bot.mjs
// bot.mjs: run with  node bot.mjs  (Node.js 18 or later)
const KEY = process.env.DATASPORTSAPI_API_KEY;
const HOOK = process.env.DISCORD_WEBHOOK_URL;
if (!KEY || !HOOK) {
  console.error("Set DATASPORTSAPI_API_KEY and DISCORD_WEBHOOK_URL first.");
  process.exit(1);
}

const API = "https://api.datasportsapi.com/v2/livescores?sport=football";
// League ids to follow; leave the set empty to follow every league.
const LEAGUES = new Set([195828, 4408, 4409]); // Premier League, LaLiga, Champions League
const LIVE_EVERY = 60_000; // while a followed match is in play
const IDLE_EVERY = 300_000; // while none is

const last = new Map(); // fixture id -> { score: "1-0", seen: time of the last poll that listed it }
let firstPoll = true;

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function liveMatches() {
  const res = await fetch(API, {
    headers: { Authorization: `Bearer ${KEY}` },
    signal: AbortSignal.timeout(15_000),
  });
  if (res.status === 429) {
    const body = await res.json().catch(() => ({}));
    const err = new Error(`API 429 ${body.error?.code ?? ""}`.trim());
    err.retryAfter = Number(res.headers.get("retry-after")) || 60;
    throw err;
  }
  if (!res.ok) throw new Error(`API answered ${res.status}`);
  const { data } = await res.json();
  return data.filter((m) => LEAGUES.size === 0 || LEAGUES.has(m.league.id));
}

const goals = (score) => score.split("-").reduce((sum, n) => sum + Number(n), 0);

function changes(matches) {
  const lines = [];
  const now = Date.now();
  for (const m of matches) {
    const score = `${m.homeScore.current ?? 0}-${m.awayScore.current ?? 0}`;
    const before = last.get(m.id)?.score;
    last.set(m.id, { score, seen: now });
    // Only a change is news: the same score seen again (the next poll, or a match
    // that drops off the list and comes back) is never posted twice.
    if (firstPoll || score === before) continue;
    const board = `${m.home.name} ${score.replace("-", " - ")} ${m.away.name}`;
    if (before === undefined && score === "0-0") lines.push(`Kick-off: ${board} (${m.league.name})`);
    else if (before === undefined) lines.push(`Under way: ${board} (${m.league.name}, ${m.status.description})`);
    else if (goals(score) < goals(before)) lines.push(`Score corrected: ${board} (${m.league.name})`);
    else lines.push(`**Goal!** ${board} (${m.league.name}, ${m.status.description})`);
  }
  // Forget matches not listed for three hours: they are over.
  for (const [id, v] of last) if (now - v.seen > 3 * 3600_000) last.delete(id);
  firstPoll = false;
  return lines;
}

async function postToDiscord(content) {
  for (let attempt = 0; attempt < 3; attempt++) {
    const res = await fetch(HOOK, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      // allowed_mentions with an empty parse list: a team name can never ping anyone.
      body: JSON.stringify({ content, allowed_mentions: { parse: [] } }),
      signal: AbortSignal.timeout(10_000),
    });
    if (res.ok) return; // 204 No Content
    if (res.status === 404) {
      // The webhook was deleted: Discord asks clients to stop using it.
      console.error("Discord webhook not found; create a new one.");
      process.exit(1);
    }
    if (res.status === 429) {
      const body = await res.json().catch(() => ({}));
      const wait = Number(body.retry_after ?? res.headers.get("retry-after")) || 1;
      await sleep(wait * 1000 + 250);
      continue;
    }
    throw new Error(`Discord answered ${res.status}`);
  }
  throw new Error("Discord kept answering 429");
}

// Discord takes at most 2,000 characters per message: send the lines in chunks.
async function send(lines) {
  let chunk = "";
  for (const line of lines) {
    if (chunk && chunk.length + line.length + 1 > 2000) {
      await postToDiscord(chunk);
      chunk = "";
    }
    chunk += (chunk ? "\n" : "") + line;
  }
  if (chunk) await postToDiscord(chunk);
}

while (true) {
  let wait = IDLE_EVERY;
  try {
    const matches = await liveMatches();
    if (matches.length) wait = LIVE_EVERY;
    const lines = changes(matches);
    if (lines.length) await send(lines);
  } catch (err) {
    console.error(new Date().toISOString(), err.message);
    if (err.retryAfter) wait = Math.max(wait, err.retryAfter * 1000);
    else wait = LIVE_EVERY; // network trouble: try again in a minute
  }
  await sleep(wait);
}
Terminal
node bot.mjs

To keep it running after you close the terminal, start it under whatever supervises your other processes: a systemd unit, pm2, or a container with a restart policy. It holds its state in memory, so a restart costs nothing but one silent poll.

4. How it avoids duplicates and noise

  • Only changes are news. The bot remembers the last score per fixture id and posts only when the new one differs. A match seen again with the same score, on the next poll or after it briefly dropped off the list, produces nothing.
  • The first poll is silent. When the bot starts mid-afternoon, it records every score it finds and posts nothing, instead of announcing twenty matches at once.
  • Goals and corrections are told apart. If the total goes down, a goal was ruled out or the source corrected itself, and the message says so instead of calling it a goal.
  • One message per poll. All changes from one poll go out together, split into pieces under Discord's 2,000-character limit, which keeps the bot far below Discord's own rate limits.
  • No pings. allowed_mentions with an empty parse list stops any text, a team name included, from mentioning @everyone.
  • Matches that end are forgotten. A finished match leaves the live list; after three hours without seeing it, the bot drops it from memory.

One choice is deliberate: if the Discord post fails three times, those lines are lost rather than retried forever, because a goal announced twenty minutes late is worse than one missed. Errors on both sides go to the console with a timestamp.

5. Stay inside the limits

Two kinds of 429 can come back from the API, and the bot handles both the same way: it waits the number of seconds in Retry-After, then polls again. rate_limited means the minute's 10 calls are used, and the wait is a few seconds. quota_exceeded means the day's 1,000 are gone, and Retry-After then counts down to midnight UTC, when the quota refills. Discord's own 429 carries a retry_after field in seconds in its JSON body, and the bot waits that out before resending. A network error or timeout is logged and the bot tries again a minute later.

The daily quota is the real constraint. Here is what each polling pattern costs:

PollingRequests a dayFits the Free plan?
Every 60 s, all day1,440No: 440 over the daily 1,000
Every 90 s, all day960Yes, with 40 to spare
60 s while a followed match is live, 5 min otherwise (10 hours of play)768Yes
Every 60 s on Starter (120 a minute, 250,000 a month)1,440Yes: under 45,000 of the monthly 250,000

The code above does the third: LIVE_EVERY while a followed match is in play, IDLE_EVERY the rest of the time. The cost of the slow mode is that a kick-off can be noticed up to five minutes late, while goals during play are still caught within a minute. If you empty the LEAGUES set to follow every competition, something is live nearly around the clock, the bot never slows down and it needs 1,440 requests a day; set LIVE_EVERY to 90_000 in that case, or move to Starter. The limits page explains both quotas and their headers.

6. Skip the polling: webhooks on Business

Polling means a goal reaches Discord up to a minute after it happens, and every quiet minute still costs a request. On the Business plan the API sends the events itself: its webhooks POST a fixture.score or fixture.status event to your server the moment a score or a match state changes, for every live fixture your filters match, and the WebSocket stream delivers the same changes to a long-lived connection. Your handler then forwards each one to the Discord webhook, with no timer and no quota spent on empty polls. The real-time page shows both. Plans below Business have neither, which is why this guide polls.

Where to go next

  • Name the scorer: GET /v2/fixtures/{id}/events lists goals and cards with the player and the minute. Call it only when the score changes, so it costs one request per goal.
  • Post a full-time summary: when a followed match drops off the live list, one call to GET /v2/fixtures/{id} confirms the final status and score.
  • Cover more than football: change sport=football to basketball or ice-hockey; every sport answers in the same shape (live scores API).

More guides

Try it with your own key.

1,000 free requests a day during the beta. No card, no sales call.