Build with StatpadBeginnerNFL
A fantasy football scoreboard for your Discord channel
A first project with the Statpad API. One small Node script scores a fantasy matchup from NFL box scores and keeps a single Discord message up to date through a channel webhook.
On Monday, November 9, 2026, the Bills beat the Vikings 23 to 6. This post's example league drafted from that one game. It has two teams, Bench Mob and Fourth and Long, with six players each. I drafted both rosters by reputation, the way two people would before kickoff.
Bench Mob led 29.28 to 18.60 at halftime. Fourth and Long won 44.34 to 43.66. Its running back, James Cook III, had 3.30 points at halftime and 16.70 at the final.
You'll build the script that kept that score. Most of it is one Node file. It reads Statpad box scores, turns each player's stats into PPR fantasy points and posts the matchup to a Discord channel. While games are on, it edits that same message once a minute.
You don't need a Discord bot, a bot token or the Discord developer portal. A channel webhook is enough. You also don't need a Statpad API key until the live-data step, because until then the script reads Statpad's public recording of this game.
The image at the top draws the message text the script sent at the final. It is not a Discord screenshot.
What you need
- Node.js 20.12 or later. Run
node --versionto check. - A Discord server where you can create webhooks. A test server of your own works best.
- The code. Download discord-fantasy-scoreboard.zip, unzip it and run
npm installin the folder. The only package it installs is@statpad/sdk.
Look at one player's stats
Statpad publishes a full recording of this game at statpad.dev/samples/nfl-bills-at-vikings. The files have the same shape as the API's answers, and anyone can download them.
boxscore.json has one row for each player who recorded a stat. This is Josh Allen's row:
{
"game_id": "01a1d60f-67be-7bdd-83f4-53286521d9bb",
"player_id": "01a1d60f-6a68-7e3c-b977-32d574ae17cf",
"stats": {
"fumbles": {
"lost": 1,
"fumbles": 1,
"recovered": 0
},
"passing": {
"att": 31,
"sacks": 4,
"yards": 234,
"rating": 87.3,
"touchdowns": 1,
"completions": 21,
"interceptions": 1,
"sack_yards_lost": 29,
"yards_per_attempt": 7.5
},
"rushing": {
"att": 6,
"yards": 15,
"longest": 7,
"touchdowns": 0,
"yards_per_attempt": 2.5
}
},
"team_id": "01a1d60f-67be-7bdf-ac2f-bcdeeac1da68",
"version": 46
}Stats come in groups such as passing and rushing, and a player only has the groups he recorded. The row has a player_id and a team_id but no name. Names are in roster.json, which lists the game's players.
Turn stats into points
Most fantasy leagues score something close to this table. PPR means a point per reception.
| Stat | Points |
|---|---|
| Passing yard | 0.04, so 1 for every 25 yards |
| Passing touchdown | 4 |
| Interception thrown | -2 |
| Rushing or receiving yard | 0.1 |
| Rushing or receiving touchdown | 6 |
| Reception | 1 |
| Fumble lost | -2 |
| Field goal | 3 |
| Extra point | 1 |
| Kick or punt return touchdown | 6 |
| Two-point conversion | Not scored. The box score doesn't count them. |
| Field goal distance | Not scored. The box score gives each kicker's longest field goal but not the distance of each one, so every field goal is worth 3. |
| Team defense | Not scored. It needs team stats, and this script reads player stats. |
scoring.mjs holds the same table as data, and one function walks through it:
// Points for each stat in a Statpad box score, using PPR rules, a point per reception.
// The box score has no two-point conversions, and it gives each kicker's longest field goal
// but not the distance of each one. Team defense needs team stats. So this table leaves all
// three out.
export const POINTS = {
passing: { yards: 0.04, touchdowns: 4, interceptions: -2 },
rushing: { yards: 0.1, touchdowns: 6 },
receiving: { receptions: 1, yards: 0.1, touchdowns: 6 },
fumbles: { lost: -2 },
kicking: { field_goals_made: 3, extra_points_made: 1 },
kick_returns: { touchdowns: 6 },
punt_returns: { touchdowns: 6 },
};
// stats is one player's `stats` object from the box score, such as
// { passing: { yards: 234, touchdowns: 1, ... }, rushing: { ... } }.
export function fantasyPoints(stats) {
let total = 0;
for (const [group, values] of Object.entries(POINTS)) {
for (const [stat, points] of Object.entries(values)) {
total += (stats[group]?.[stat] ?? 0) * points;
}
}
return Math.round(total * 100) / 100;
}Allen's row has no receiving group, so stats[group]?.[stat] gives undefined and ?? 0 turns it into 0. The last line rounds to two decimals. Without it, Cook's 16.7 comes out as 16.700000000000003, because JavaScript can't store 0.1 exactly.
Check the math with tests
Before you trust the numbers, test them against real stat lines. This test downloads the recorded box score and checks six players, including Ivan Pace Jr., who has only defensive stats and should score 0:
// Checks fantasyPoints against real stat lines from the recorded Bills at Vikings game.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fantasyPoints } from './scoring.mjs';
const SAMPLE = 'https://statpad.dev/samples/nfl-bills-at-vikings';
const [boxscore, roster] = await Promise.all(
['boxscore.json', 'roster.json'].map((file) => fetch(`${SAMPLE}/${file}`).then((res) => res.json())),
);
function statsFor(name) {
const player = roster.players.find((p) => p.full_name === name);
return boxscore.players.find((row) => row.player_id === player.id).stats;
}
const expected = [
['James Cook III', 16.7],
['Tyler Bass', 11],
['Josh Allen', 10.86],
['Justin Jefferson', 8.8],
['Carson Wentz', -2.76],
['Ivan Pace Jr.', 0],
];
for (const [name, points] of expected) {
test(`${name} scores ${points}`, () => {
assert.equal(fantasyPoints(statsFor(name)), points);
});
}
test('a player with no stats scores 0', () => {
assert.equal(fantasyPoints({}), 0);
});Run it with Node's built-in test runner, node --test scoring.test.mjs:
✔ James Cook III scores 16.7 (0.4542ms)
✔ Tyler Bass scores 11 (0.0733ms)
✔ Josh Allen scores 10.86 (0.0526ms)
✔ Justin Jefferson scores 8.8 (0.0443ms)
✔ Carson Wentz scores -2.76 (0.0464ms)
✔ Ivan Pace Jr. scores 0 (0.0364ms)
✔ a player with no stats scores 0 (0.0637ms)Carson Wentz really did score -2.76. His 81 passing yards were worth 3.24 points, and two interceptions and a lost fumble cost him 6.
See every player in the game
npm run players runs players.mjs, which joins the box score to the roster and prints everyone who scored:
BUF James Cook III 16.70
BUF Tyler Bass 11.00
BUF Josh Allen 10.86
BUF Khalil Shakir 9.80
BUF Keleki Latu 9.50
MIN Justin Jefferson 8.80
BUF Dawson Knox 7.70
MIN T.J. Hockenson 7.30
BUF DJ Moore 6.60
MIN Jordan Mason 6.20
MIN Will Reichard 6.00
BUF Dalton Kincaid 5.80
BUF Ty Johnson 5.70
MIN Jordan Addison 4.80
BUF Keon Coleman 4.70
MIN Aaron Jones Sr. 3.10
MIN Max Brosmer 2.32
BUF Jackson Hawes 1.80
MIN Myles Price 1.60
MIN DeeJay Dallas 1.20
BUF Ray Davis 0.20
BUF Kyle Allen -0.20
MIN Carson Wentz -2.76Use this list to spell names in your league file. Statpad writes "James Cook III" and "Aaron Jones Sr.", and the script matches names exactly.
Write the league file
league.json holds the league's name, the time window to look for games in and the two rosters:
{
"name": "Monday night showdown",
"from": "2026-11-09T12:00:00Z",
"to": "2026-11-10T12:00:00Z",
"teams": [
{
"name": "Bench Mob",
"players": [
{
"pos": "QB",
"name": "Josh Allen",
"team": "BUF"
},
{
"pos": "RB",
"name": "Aaron Jones Sr.",
"team": "MIN"
},
{
"pos": "WR",
"name": "Khalil Shakir",
"team": "BUF"
},
{
"pos": "WR",
"name": "DJ Moore",
"team": "BUF"
},
{
"pos": "TE",
"name": "T.J. Hockenson",
"team": "MIN"
},
{
"pos": "K",
"name": "Will Reichard",
"team": "MIN"
}
]
},
{
"name": "Fourth and Long",
"players": [
{
"pos": "QB",
"name": "Carson Wentz",
"team": "MIN"
},
{
"pos": "RB",
"name": "James Cook III",
"team": "BUF"
},
{
"pos": "WR",
"name": "Justin Jefferson",
"team": "MIN"
},
{
"pos": "WR",
"name": "Jordan Addison",
"team": "MIN"
},
{
"pos": "TE",
"name": "Dalton Kincaid",
"team": "BUF"
},
{
"pos": "K",
"name": "Tyler Bass",
"team": "BUF"
}
]
}
]
}team is the NFL team's short name, the same one the scoreboard prints. pos is only for display, because the box score doesn't say what position a player plays. from and to matter in the live-data step. They cover Monday night's game here.
If a name doesn't match, the script prints a hint. This is its output with "James Cook" in place of "James Cook III":
No stats for James Cook (BUF). Did you mean "James Cook III"?Make the scoreboard text
Discord can't show tables, but it shows code blocks in a fixed-width font. render builds the message as a bold title, a line with each game's score and a code block with the points, padded into columns:
function render(games, aliases, players) {
const lines = [`**${league.name}**`];
for (const game of games) {
const status = STATUS[game.status] ?? game.status;
lines.push(`${aliases.get(game.away_team_id)} ${game.away_score ?? 0}, ${aliases.get(game.home_team_id)} ${game.home_score ?? 0} · ${status}`);
}
lines.push('```');
for (const team of league.teams) {
const rows = team.players.map((spot) => {
const found = players.find((p) => p.name === spot.name && p.team === spot.team);
return { ...spot, points: found?.points ?? 0 };
});
const total = rows.reduce((sum, row) => sum + row.points, 0);
lines.push(`${team.name.padEnd(24)}${total.toFixed(2).padStart(7)}`);
for (const row of rows) lines.push(` ${row.pos.padEnd(3)}${row.name.padEnd(19)}${row.points.toFixed(2).padStart(7)}`);
lines.push('');
}
lines[lines.length - 1] = '```';
return lines.join('\n');
}Run npm start. With no API key and no webhook, it scores the recorded game and prints the message:
**Monday night showdown**
BUF 23, MIN 6 · final
```
Bench Mob 43.66
QB Josh Allen 10.86
RB Aaron Jones Sr. 3.10
WR Khalil Shakir 9.80
WR DJ Moore 6.60
TE T.J. Hockenson 7.30
K Will Reichard 6.00
Fourth and Long 44.34
QB Carson Wentz -2.76
RB James Cook III 16.70
WR Justin Jefferson 8.80
WR Jordan Addison 4.80
TE Dalton Kincaid 5.80
K Tyler Bass 11.00
```Post it to Discord
Create the webhook in Discord:
- Open the channel's settings with the gear icon next to its name.
- Choose Integrations, then Webhooks, then New Webhook.
- Click Copy Webhook URL.
Copy .env.example to .env and paste the URL after DISCORD_WEBHOOK_URL=:
# Copy this file to .env and fill in the values. .gitignore keeps .env out of git.
DISCORD_WEBHOOK_URL=
STATPAD_API_KEY=Anyone with the webhook URL can post to your channel, so treat it like a password. .gitignore already lists .env.
This function sends the message:
// The first run posts a message and saves its id. Later runs edit that message.
async function postOrEdit(content) {
const id = existsSync('message-id.txt') ? readFileSync('message-id.txt', 'utf8').trim() : '';
const res = await fetch(id ? `${WEBHOOK}/messages/${id}` : `${WEBHOOK}?wait=true`, {
method: id ? 'PATCH' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content }),
});
if (res.status === 429) {
const { retry_after } = await res.json();
console.log(`Discord asked the script to wait ${retry_after} seconds.`);
await sleep(retry_after * 1000);
return postOrEdit(content);
}
if (!res.ok) throw new Error(`Discord answered ${res.status}: ${await res.text()}`);
const message = await res.json();
if (!id) writeFileSync('message-id.txt', message.id);
console.log(`${id ? 'Edited' : 'Posted'} message ${message.id}`);
}The first run sends a POST to the webhook URL. Without ?wait=true, Discord answers with an empty 204 response, and the script would never learn the new message's id. With it, Discord returns the message, and the script saves its id in message-id.txt.
Every later run finds that file and sends a PATCH to /messages/{id} instead, which replaces the message's text. If you delete the message in Discord, delete message-id.txt too, or the edit fails with a 404.
If the script sends too much too fast, Discord answers 429 with a retry_after number of seconds. The function waits that long and sends the same request again.
Run npm start again, and the scoreboard appears in your channel.
Switch to live data
For live games, the script needs a Statpad API key. Create one on the Keys page of your Statpad account and add it to .env after STATPAD_API_KEY=. The Pro trial lasts 7 days and needs a card. When it ends it becomes Pro at $49 a month unless you cancel or pick another plan. The smallest, Developer, is $19 a month.
The key stays in .env on your computer, and only this script sends it. Never put it in a web page or a browser extension, where anyone can read it.
With a key, the script swaps the sample files for three calls through @statpad/sdk:
// The games between league.from and league.to, and the teams playing in them.
async function loadGames() {
if (!statpad) {
const sample = await getJson('game.json');
return { games: [sample.game], teams: [sample.away_team, sample.home_team] };
}
const { data } = await statpad.games.listGames({ path: { league: 'nfl' }, query: { from: league.from, to: league.to } });
return { games: data.data, teams: data.teams };
}
// One game's players with their names, teams and fantasy points.
async function loadPlayers(game, aliases) {
if (finished.has(game.id)) return finished.get(game.id);
let boxscore, roster;
if (statpad) {
const path = { league: 'nfl', game_id: game.id };
boxscore = (await statpad.statistics.getBoxScore({ path })).data;
roster = (await statpad.games.listGameRoster({ path, query: { limit: 500 } })).data;
} else {
[boxscore, roster] = await Promise.all([getJson('boxscore.json'), getJson('roster.json')]);
}
const names = new Map(roster.players.map((player) => [player.id, player.full_name]));
const players = boxscore.players.map((row) => ({
name: names.get(row.player_id),
team: aliases.get(row.team_id),
points: fantasyPoints(row.stats),
}));
if (OVER.includes(game.status)) finished.set(game.id, players);
return players;
}listGames returns the NFL games that start between from and to, plus a teams list that the script uses to turn team ids into short names like BUF. getBoxScore returns the same rows you saw in boxscore.json. listGameRoster returns the names, and limit: 500 is the largest page the API allows, so one request covers a whole game.
Before kickoff a game has no box score rows yet, so the script skips games that haven't started. Once a game is over, it keeps that game's players and stops asking for them.
Keep it updated
update is one pass. It loads the games, keeps the ones with a player from your league and scores everyone. If none of those games has started, it posts nothing, so the channel never sees a board of zeros. It only talks to Discord when the text has changed.
// One pass loads the games, scores the league and updates Discord. It returns the league's games.
async function update() {
const { games, teams } = await loadGames();
const aliases = new Map(teams.map((team) => [team.id, team.alias]));
const picked = new Set(league.teams.flatMap((team) => team.players.map((spot) => spot.team)));
const ours = games.filter((game) => picked.has(aliases.get(game.away_team_id)) || picked.has(aliases.get(game.home_team_id)));
const started = ours.filter((game) => !['scheduled', 'time_tbd'].includes(game.status));
if (started.length === 0) {
console.log('No game in league.json has started yet.');
return ours;
}
const players = [];
for (const game of started) players.push(...(await loadPlayers(game, aliases)));
for (const spot of league.teams.flatMap((team) => team.players)) {
if (players.some((p) => p.name === spot.name && p.team === spot.team)) continue;
const close = players.find((p) => p.team === spot.team && p.name.includes(spot.name.split(' ').at(-1)));
if (close) console.log(`No stats for ${spot.name} (${spot.team}). Did you mean "${close.name}"?`);
}
const content = render(ours, aliases, players);
if (content !== last) {
console.log(content);
if (WEBHOOK) await postOrEdit(content);
last = content;
}
return ours;
}The bottom of the file runs update on a timer:
let last = '';
while (true) {
let games;
try {
games = await update();
} catch (error) {
if (!statpad) throw error;
console.log(`This pass failed, so the script will try again in a minute. ${error.message}`);
await sleep(60_000);
continue;
}
if (!statpad || isDone(games, league.to)) break;
await sleep(60_000);
}Without a key it stops after one pass. With a key it waits 60 seconds and goes again. If a pass fails, for example because the network drops, the script prints the error, waits a minute and tries again. A failed pass skips the stop check, so one error can't end the run.
done.mjs decides when to stop. If you start the script on Sunday morning, the game list may not have your games yet, so an empty list means keep waiting until the to time in league.json. Once there are games, the script stops when every one of them is over, even if a game runs past to. "Over" is this example's choice of when to stop polling. Statpad can still correct stats after a game is final, and the script won't pick those corrections up.
// The statuses where this example stops polling a game. Statpad can still correct stats after
// `complete`, and a postponed game can be rescheduled, but the script doesn't wait for either.
export const OVER = ['complete', 'closed', 'cancelled', 'postponed'];
// Decides whether the live script can stop. It stops once every league game is over. With no
// league game listed yet, it keeps waiting until the league's `to` time has passed.
export function isDone(games, to, now = Date.now()) {
if (games.length === 0) return now > Date.parse(to);
return games.every((game) => OVER.includes(game.status));
}done.test.mjs checks it with the statuses this game went through, from an empty list to complete. npm test runs it with the scoring tests:
✔ keeps waiting while no league game is listed and to has not passed (0.4126ms)
✔ stops when no league game was ever listed and to has passed (0.07ms)
✔ waits through an empty list, then follows the game until it ends (0.3923ms)
✔ keeps following a game that runs past to (0.0596ms)
✔ stops when one game is over and the other was postponed (0.5703ms)This is the start of a test run, against the local stand-ins described below, where the game list was empty on the first pass and the roster request failed on the second:
No game in league.json has started yet.
This pass failed, so the script will try again in a minute. 503: Service UnavailableThe third pass found the game at halftime. Discord answered the first post with a 429, and the script waited and posted again:
Discord asked the script to wait 1.5 seconds.
Posted message mock-message-1These draw the two message bodies the script sent in a test of the live path. To test without waiting for a real game, I ran the script against two local stand-ins. One answered like the Statpad API and served this game's real stats as they stood at halftime, then at the final. The other stood in for Discord. It recorded what the script sent and answered with a made-up message id, mock-message-1. The script sent a POST for the first and a PATCH to the same message for the second. The test runs above used the same two stand-ins.
Each pass costs one request for the game list and two for each game in progress. This game ran 11,439 seconds, about 191 passes at one a minute, so following it costs about 573 requests. The Pro trial allows 25,000.
An edit doesn't create a new message, so it doesn't create a new notification either. Whether the first post notifies anyone depends on each person's notification settings for the channel.
Make it yours
- Add a bench. Give each team a
benchlist inleague.json, and print those players under a line without adding them to the total. - Show injuries.
statpad.leagueNews.listInjuries({ path: { league: 'nfl' } })returns the NFL's open injuries with their players, so you can mark a player who's listed. - Post big plays. Compare each player's points with the last pass. When someone gains 6 or more, send a separate message with a plain POST, and leave
message-id.txtalone so the scoreboard keeps its id. People with notifications on for the channel can hear about a new message. An edit creates no new message and no new notification. - Add a
/matchupslash command. That needs a real bot account from the Discord developer portal and a library like discord.js, so it's a good second project.
Run it
unzip discord-fantasy-scoreboard.zip -d discord-fantasy-scoreboard
cd discord-fantasy-scoreboard
npm install
npm test
npm startLimits
- Names have to match Statpad's spelling exactly, team included.
fromandtodon't move on their own. Change them each week.- Discord allows 2,000 characters in a message. This layout fits about eight teams of six.
- The script stops polling at the final, so it misses stat corrections Statpad makes later.
- Scoring leaves out two-point conversions, field goal distance and team defense, as the table says.
More from Build with Statpad
- Test that your live client gets a real game rightA six-test node:test file sends all 1,277 changes of a recorded NFL game through your change handler and checks what your app would show at the moments that break live clients.
- Ask Claude about an NFL game while it replays on your laptopA small Node server replays the recorded Bills at Vikings game on localhost. Point @statpad/mcp at it, ask Claude who has the ball, then move the game forward and watch the answer change when replay overturns a fumble.
- A shot map of Manchester United 4–4 Aston Villa in 125 lines of TypeScriptEvery shot in Statpad's Premier League play-by-play has pitch coordinates. This script turns one 8-goal draw into an SVG shot map and a score timeline, and covers the two coordinate traps.
- A live NFL scoreboard in SwiftUI, and the small server that holds the keyA Node server on @statpad/sdk holds the Statpad key and one stream subscription, and a SwiftUI app resumes from it by seq, tested against a recorded Bills at Vikings game.