How to Build a Discord Odds Bot for Line-Move Alerts (Webhooks + Node.js)
Relay PreciseAPI line-move webhooks into a Discord channel with Node.js. Signature checks, de-duplication, stale-alert filtering, embeds, batching and Discord rate limits.
A Discord channel is a convenient place to watch line movement: your team already has it open, it works on phones, and posting to it is one HTTP request. PreciseAPI already detects line moves and pushes them as signed webhooks. What's missing is a small Discord odds bot that receives them, checks they're genuine, and turns them into readable Discord messages.
This tutorial builds that relay, a Node.js Discord bot of about 150 lines. It holds no WebSocket and runs no detection logic: PreciseAPI decides when something moved, and your relay decides how it looks. The bot reports what changed in the data and nothing more.
How the Discord odds bot fits together
PreciseAPI alert rule ──(signed POST, line.moved)──▶ your relay ──(POST, embeds)──▶ Discord channel webhook
Three things need configuring:
- A Discord webhook for the channel. In the channel's settings, open Integrations, create a webhook and copy its URL. Anyone who has that URL can post to the channel, so store it as a secret.
- A PreciseAPI webhook endpoint pointing at your relay, created under Dashboard → Webhooks. The signing secret (
whsec_…) is displayed when you create the endpoint. - A line-move alert rule, created under Dashboard → Alerts. It defines what counts as a move and sends matches to that endpoint.
Why not post to Discord directly? Discord expects its own message format and won't check PreciseAPI's signature. A relay lets you verify requests, drop duplicates and design the layout.
What a line-move rule watches
A line_move rule fires when a main-market price moves by at least your threshold in cents, or when a spread or total line changes. Its parameters:
| Parameter | Values | Notes |
|---|---|---|
leagues | Any league id, e.g. nfl, nba | Empty means all leagues |
books | Any source id, e.g. pinnacle, draftkings | Empty means all sources |
markets | moneyline, spread, total | Full-game markets only, no player props |
min_cents | 1 to 1,000, default 20 | Ignored when the line itself changes |
Cents are measured continuously across even money: −110 to −130 is 20 cents, and −105 to +105 is 10. For any one rule, a given market fires at most once every 10 minutes. Each alert delivered costs 1 credit. If your balance is empty, the alert is skipped silently.
Every paid plan includes webhook odds alerts, from Edge (10 rules, 2 endpoints) up to Syndicate (500 rules, 25 endpoints). One relay can serve many rules, so one endpoint is enough here. Pricing has the full limits.
The payload you'll receive
Every delivery is a POST with a JSON body. It carries three headers: PreciseAPI-Event (the event type), PreciseAPI-Delivery (the delivery id) and PreciseAPI-Signature. A trimmed line.moved body looks like this:
{
"id": "evt_7Gq2KxW9mZpL4rT1vN8c",
"type": "line.moved",
"created": "2026-10-18T19:42:07.118Z",
"data": {
"rule": { "id": "ar_k2V9xQ7mL3pR8tZ1", "name": "NFL moves", "kind": "line_move" },
"event": { "id": "evt_0uuc6p2dsqa", "league": "nfl", "start_time": "2026-10-18T20:25:00.000Z", "status": "scheduled",
"home": { "id": "nfl_buf", "name": "Buffalo Bills" }, "away": { "id": "nfl_kc", "name": "Kansas City Chiefs" } },
"book": { "id": "draftkings", "name": "DraftKings" },
"market": { "id": "mkt_3xk9a0b1c2d", "key": "moneyline", "period": "full_game", "outcomes": [ "…" ], "suspended": false },
"move": { "outcome_id": "sel_1a2b3c4d5e6", "outcome": "Buffalo Bills", "from": -125, "to": -145, "cents": 20 },
"line": null
}
}
Watch out for three details:
- The top-level
ididentifies the delivery and is what you de-duplicate on. The game isdata.event.id. Both ids start withevt_, so be careful which one you store. marketis the complete market after the move, so you can show every side, not just the one that changed.- When a spread or total line changes,
lineholds{ from, to }, andmoveis usuallynull. Selection ids include the point, so a new line means new outcome ids with no earlier price to compare against. Your formatter has to handle either field beingnull.
The full schema is in the webhooks reference, and the data model explains the id prefixes.
Step 1: Verify and acknowledge
Set up the project with npm i express (the quickstart gets you a key). Node 18 or later is required for the built-in fetch. Everything below goes into relay.mjs.
The signature header has the form t=<unix seconds>,v1=<hex>, where v1 is the HMAC-SHA256 of "<t>.<raw body>" computed with your endpoint secret. Verify it against the raw bytes of the request. JSON that has been parsed and serialized again won't match.
import express from 'express';
import crypto from 'node:crypto';
const SECRET = process.env.PRECISEAPI_WEBHOOK_SECRET;
const DEFAULT_CHANNEL = process.env.DISCORD_WEBHOOK_URL;
const ROUTES = JSON.parse(process.env.DISCORD_ROUTES || '{}'); // optional: { "nfl": "https://discord.com/api/webhooks/..." }
const MAX_AGE_MS = Number(process.env.MAX_ALERT_AGE_SEC || 300) * 1000;
function verify(raw, header, secret, toleranceSec = 300) {
if (!header || !secret) return false;
const parts = {};
for (const kv of header.split(',')) {
const i = kv.indexOf('=');
if (i > 0) parts[kv.slice(0, i).trim()] = kv.slice(i + 1).trim();
}
const t = Number(parts.t);
if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > toleranceSec) return false; // replay window
const expected = crypto.createHmac('sha256', secret).update(`${t}.${raw}`).digest('hex');
const got = String(parts.v1 || '');
return got.length === expected.length && crypto.timingSafeEqual(Buffer.from(got), Buffer.from(expected));
}
const seen = new Map(); // delivery id -> first seen (ms), oldest first
function isDuplicate(id) {
const now = Date.now();
for (const [k, at] of seen) {
if (now - at < 86_400_000) break;
seen.delete(k);
}
if (seen.has(id)) return true;
seen.set(id, now);
return false;
}
const app = express();
app.post('/webhooks/preciseapi', express.raw({ type: 'application/json', limit: '256kb' }), (req, res) => {
const raw = req.body.toString('utf8');
if (!verify(raw, req.get('PreciseAPI-Signature'), SECRET)) return res.sendStatus(400);
res.sendStatus(200); // acknowledge first; Discord work happens after
let evt;
try {
evt = JSON.parse(raw);
} catch {
return;
}
if (isDuplicate(evt.id)) return;
handle(evt).catch((err) => console.error('handle failed', evt.id, err));
});
app.listen(Number(process.env.PORT || 3000), () => console.log('relay listening'));
The relay answers before touching Discord. PreciseAPI expects a 2xx within 5 seconds and doesn't follow redirects. Failures are retried after 30 seconds, 2 minutes, 10 minutes, 1 hour and 6 hours, and 20 consecutive failures disable the endpoint and email the account owner. A slow Discord shouldn't cost you your endpoint.
Deliveries can arrive out of order or more than once, hence the de-duplication map. With several relay instances, move it to a shared store keyed on the delivery id.
Step 2: Drop stale alerts
Every retry is signed again with a fresh timestamp, so a retry passes the five-minute replay check even if the original move happened hours earlier. Use the payload's created field to decide whether an alert is still worth posting:
async function handle(evt) {
if (evt.type === 'test.ping') {
return enqueue(DEFAULT_CHANNEL, { title: 'PreciseAPI connected', description: evt.data.message, color: 0x5865f2 });
}
if (evt.type !== 'line.moved') return; // tolerate future event types
const age = Date.now() - Date.parse(evt.created);
if (age > MAX_AGE_MS) return console.warn(`skipping ${evt.id}: ${Math.round(age / 1000)}s old`);
const channel = ROUTES[evt.data.event.league] || DEFAULT_CHANNEL;
enqueue(channel, toEmbed(evt));
}
Five minutes suits pre-game markets; go lower for in-play rules. ROUTES sends each league to its own channel, with everything else going to the default webhook.
Step 3: Format the embed
An embed with a title, fields, footer and timestamp makes a compact card. The colour reflects whether the moved outcome's implied probability rose or fell, and Discord's <t:…:R> syntax renders the start time relative to each reader.
const signed = (n) => (n > 0 ? `+${n}` : `${n}`);
const implied = (a) => (a < 0 ? -a / (-a + 100) : 100 / (a + 100));
const LABEL = { moneyline: 'Moneyline', spread: 'Spread', total: 'Total' };
function toEmbed({ id, created, data }) {
const { rule, event, book, market, move, line } = data;
const fields = [];
const shorter = move && implied(move.to) > implied(move.from);
if (move) {
fields.push({ name: move.outcome, value: `${signed(move.from)} → ${signed(move.to)} (${move.cents}¢, ${shorter ? 'shortened' : 'drifted'})`, inline: true });
}
if (line) fields.push({ name: 'Line', value: `${line.from} → ${line.to}`, inline: true });
fields.push({
name: `Now at ${book.name}`,
value: market.outcomes.map((o) => `${o.name} ${o.point !== undefined ? `${signed(o.point)} ` : ''}${signed(o.price)}`).join('\n'),
});
fields.push({ name: 'Starts', value: `<t:${Math.floor(Date.parse(event.start_time) / 1000)}:R>`, inline: true });
return {
title: `${book.name} · ${LABEL[market.key] || market.key} moved`,
description: `**${event.away.name} @ ${event.home.name}** · ${event.league.toUpperCase()} · ${event.status}`,
color: line ? 0xf1c40f : shorter ? 0xe67e22 : 0x3498db,
fields,
footer: { text: `${rule.name} · ${id}` },
timestamp: created,
};
}
The delivery id in the footer ties each message to its row in the dashboard's delivery log. Webhook prices are American; convert them here if your channel prefers decimal (see the odds formats guide).
Step 4: Batch, rate-limit and retry Discord
Discord rate-limits webhooks and answers 429 with a retry_after in seconds. Moves arrive in bursts, so the relay keeps one queue per channel and packs up to 10 embeds, Discord's per-message maximum, into each post:
const queues = new Map(); // channel url -> { items, busy }
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function enqueue(url, embed) {
if (!url) return;
let q = queues.get(url);
if (!q) queues.set(url, (q = { items: [], busy: false }));
q.items.push(embed);
if (q.items.length > 500) q.items.splice(0, q.items.length - 500); // bounded during a Discord outage
if (!q.busy) drain(url, q);
}
async function drain(url, q) {
q.busy = true;
await sleep(750); // short window so a burst shares one message
let failures = 0;
while (q.items.length) {
const batch = q.items.slice(0, 10);
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'Line Moves', embeds: batch, allowed_mentions: { parse: [] } }),
});
if (res.status === 429) {
const body = await res.json().catch(() => ({}));
await sleep((Number(body.retry_after ?? res.headers.get('retry-after')) || 2) * 1000 + 100);
continue; // same batch again
}
if (res.status >= 500) throw new Error(`discord ${res.status}`);
if (!res.ok) console.error('discord rejected batch', res.status, await res.text()); // 4xx: drop, don't loop
q.items.splice(0, batch.length);
failures = 0;
} catch (err) {
failures++;
console.warn(`discord send failed (${err.message}), attempt ${failures}`);
if (failures >= 5) q.items.splice(0, batch.length); // give up on this batch
await sleep(Math.min(30_000, 1000 * 2 ** failures));
}
}
q.busy = false;
}
allowed_mentions: { parse: [] } keeps any text that looks like @everyone from pinging the server. Other 4xx responses mean a malformed embed that retrying won't fix, so that batch is logged and dropped.
Step 5: Test it end to end
Test locally first: take the payload above with a fresh id and created, sign it the way verify checks it, and POST it to localhost:3000/webhooks/preciseapi. A second identical post should be ignored, and a tampered body should get 400.
Then deploy behind a public HTTPS URL (endpoints must use HTTPS and can't target private networks), register it under Dashboard → Webhooks and click "Send test". A signed test.ping should land in Discord while the dashboard shows the response code and latency. Then attach an alert rule, and the Discord odds bot is live.
Extending the bot
- Cross-book context. Call
/v1/events/{id}/oddswith the alert's market key andperiods=full_gameto show what other books quote. It costs 2 credits, so cache per event for 30 seconds or so. - Breadth. One book moving is one data point. To report moves many books make together, aggregate alerts or run a detector on the stream, as in detecting steam moves.
- Props and periods. Alert rules cover full-game main markets. For props or first-half lines, subscribe to those keys on the WebSocket stream with a client like the one in the Node.js streaming tutorial.
The odds API for Discord bots page covers Discord odds alerts as a product feature, the line movement API covers the history behind each move, and the line movement entry is a good primer for channel members.
Frequently asked questions
Can I point a PreciseAPI webhook straight at a Discord webhook URL?
Not usefully. Discord expects content or embeds, while PreciseAPI sends a signed event envelope. The relay translates between them and adds verification, de-duplication and rate-limit handling.
How many credits does the Discord odds bot use?
One credit per delivered alert. Because a market fires at most once per 10 minutes per rule, a rule watching 14 games, one market and three books (42 markets) is capped at 252 alerts an hour. Enrichment calls cost 2 credits each.
Why did the same alert arrive twice?
Delivery is at-least-once: a slow response or a network error can trigger a retry of something you already processed. De-duplicate on the top-level id, also sent as PreciseAPI-Delivery.
Can I get alerts for player props?
Not through alert rules, which watch full-game moneyline, spread and total markets. To track props, stream player_* market keys over the WebSocket, which is available on Syndicate, and apply your own threshold logic.
Does the bot tell people what to bet?
No. It reports observed price and line changes. PreciseAPI is a data API and provides no picks or advice.