guides
Telegram odds bot: sportsbook price moves and /best from the WebSocket
A Telegram odds bot sends price moves to a chat and answers questions about prices. In a 3-minute run on NBA, NHL and college basketball, the one below read 2,848 pre-game price changes at US sportsbooks and sent 12 alert messages. It is a single Node script with no packages. It listens on the PricedOdds WebSocket for moneyline, spread and total prices and sends a message when a pre-game price moves 2 or more points of implied probability. When you type /best and a team, it replies with the best price for each side of that team's next game.
What do I need to build a Telegram odds bot?
- A PricedOdds API key on a plan with WebSocket access (All-Access, or the WebSocket add-on; see pricing).
- A Telegram bot token. Telegram's BotFather instructions say to use the
/newbotcommand, after which "@BotFather will ask you for a name and username, then generate an authentication token for your new bot." Keep the token out of your code and your repository, like the API key. - The id of the chat the bot should use. Send any message to your new bot, then open
https://api.telegram.org/bot<token>/getUpdates: thechat.idof that message is the id. - Node 22 or later, which has
WebSocketandfetchbuilt in. We ran the script on Node 24.22.1 without installing anything.
How is it different from the Discord bot and the alerts script?
The Discord odds alert bot polls GET /v1/changes every 30 seconds and only posts. The odds alerts script waits for several books to move together, adds prices above the fair price and prints to the terminal. This bot listens on the WebSocket, keeps only licensed US sportsbooks and games that have not started, groups the moves of each game into one message, and answers a command in the chat.
How does the bot work?
- It reads the book list from
GET /v1/books, which needs no key, and keeps the books of typesportsbookthat are notreference_only. - It opens
wss://api.pricedodds.com/v1/stream, sends the key in anauthmessage and, onready, subscribes to the leagues with moneyline, spread and total and those books only. - The
snapshotframes give each game's teams, league, start time and status.scoreframes update the status, so a game that starts stops sending alerts: in-play prices follow the score. - For each
priceframe it turnsamericanandprev_americaninto implied probability and keeps full-game moves of 2 points or more. - Every 10 seconds it sends what it found as one message: one block per game and, per book and market, the largest move and how many other prices moved with it. Books often move a whole ladder of alternate spreads at once, and this keeps that to one line.
- Each price at each book alerts once every 10 minutes; the rest are counted as muted.
- In parallel it asks Telegram for new messages with
getUpdatesand answers/best <team>fromGET /v1/bestwithbooksset to the same sportsbooks. It answers only the chat inTELEGRAM_CHAT_ID, so a stranger who finds the bot cannot spend your API requests.
If the WebSocket drops, it reconnects and sends resume with the last seq. It does not retry on close codes 4001, 4002 and 4003, which mean the key, the billing or the plan needs fixing.
What does Telegram allow?
We read the Telegram Bot API and its FAQ on limits on November 25, 2026. The bot follows them like this:
- Requests. Each call is a
POSTwith a JSON body tohttps://api.telegram.org/bot<token>/<method>. Every answer has anokfield; on an error it haserror_codeanddescription. - Length.
sendMessagetakes text of "1-4096 characters after entities parsing". The bot splits a long batch by line before that limit. - Formatting. With
parse_modeset toHTML, "All <, > and & symbols that are not a part of a tag or an HTML entity must be replaced" with entities. Team names such as Texas A&M would break a message without that, so the script escapes every name. - Rate. The FAQ says: "In a single chat, avoid sending more than one message per second." The bot waits at least one second between messages. In a group the FAQ sets 20 messages per minute, so raise
BATCH_SECONDSif you post to a group. - Flood control. A 429 answer carries
parameters.retry_after, "the number of seconds left to wait before the request can be repeated". The bot waits that long and sends again. - Updates.
getUpdatesis long polling and "will not work if an outgoing webhook is set up", so the bot needs no public URL. Delete any webhook first if you set one up earlier.
What is the code?
// telegram-odds-bot.mjs: a Telegram bot that sends sportsbook price moves from the PricedOdds WebSocket to one chat
// and answers "/best <team>" with the best moneyline, spread and total. Node 22 or later, no packages.
// Usage: PRICEDODDS_API_KEY=... TELEGRAM_BOT_TOKEN=... TELEGRAM_CHAT_ID=... node telegram-odds-bot.mjs
const KEY = process.env.PRICEDODDS_API_KEY;
const BASE = "https://api.pricedodds.com/v1";
const TG = `${process.env.TELEGRAM_API ?? "https://api.telegram.org"}/bot${process.env.TELEGRAM_BOT_TOKEN}`;
const CHAT = String(process.env.TELEGRAM_CHAT_ID); // the only chat the bot posts to and answers
const LEAGUES = (process.env.LEAGUES ?? "nba,nhl,ncaab").split(",");
const MARKETS = ["moneyline", "spread", "total"];
const MIN_POINTS = Number(process.env.MIN_POINTS ?? 2); // a move of this many points of implied probability or more
const BATCH_SECONDS = 10; // moves found in 10 seconds go out as one message
const COOLDOWN_MINUTES = 10; // one alert per selection and book in this time
const SECONDS = Number(process.env.SECONDS ?? Infinity);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const implied = (am) => (am > 0 ? 100 / (am + 100) : -am / (-am + 100));
const fmt = (am) => (am > 0 ? `+${am}` : `${am}`);
const esc = (s) => String(s).replace(/[&<>]/g, (c) => ({ "&": "&", "<": "<", ">": ">" })[c]); // Telegram HTML mode
const n = { changes: 0, moves: 0, muted: 0, sent: 0, retries: 0, commands: 0, ignored: 0 };
async function api(path, auth = true) {
const res = await fetch(BASE + path, auth ? { headers: { Authorization: `Bearer ${KEY}` } } : {});
if (!res.ok) throw new Error(`${path}: HTTP ${res.status}`);
return res.json();
}
// Telegram Bot API: POST JSON to /bot<token>/<method>. On 429, wait parameters.retry_after seconds and send again.
async function tg(method, body) {
for (;;) {
const res = await fetch(`${TG}/${method}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
const out = await res.json();
if (out.ok) return out.result;
if (out.error_code !== 429) throw new Error(`Telegram ${method}: ${out.error_code} ${out.description}`);
n.retries++;
await sleep((out.parameters?.retry_after ?? 1) * 1000);
}
}
// One message per second at most in this chat, and no message over 4,096 characters: long lists are split by line.
let lastSend = 0;
async function send(lines) {
let msg = "";
const parts = [];
for (const line of lines) {
if (msg && msg.length + line.length + 1 > 4096) { parts.push(msg); msg = ""; }
msg += (msg ? "\n" : "") + line;
}
if (msg) parts.push(msg);
for (const text of parts) {
await sleep(Math.max(0, lastSend + 1000 - Date.now()));
await tg("sendMessage", { chat_id: CHAT, text, parse_mode: "HTML", link_preview_options: { is_disabled: true } });
lastSend = Date.now();
n.sent++;
}
}
// Licensed US sportsbooks only; the book list needs no key.
const bookList = (await api("/books", false)).data;
const NAME = Object.fromEntries(bookList.map((b) => [b.id, b.name]));
const BOOKS = bookList.filter((b) => b.type === "sportsbook" && !b.reference_only).map((b) => b.id);
const events = new Map(); // event_id -> { league, away, home, status, startsAt }
const lastAlert = new Map();
let pending = new Map(); // `${event_id}|${book}|${market}` -> moves in this batch (a book often moves every alternate line at once)
function onPrice({ event_id, book, changes }) {
const e = events.get(event_id);
if (!e || e.status !== "scheduled") return; // pre-game only: in-play prices follow the score
for (const c of changes) {
if (c.period !== "game" || c.american == null || c.prev_american == null) continue;
n.changes++;
const move = (implied(c.american) - implied(c.prev_american)) * 100;
if (Math.abs(move) < MIN_POINTS) continue;
const key = `${c.selection_id}|${book}`;
if (Date.now() - (lastAlert.get(key) ?? -Infinity) < COOLDOWN_MINUTES * 60000) { n.muted++; continue; }
lastAlert.set(key, Date.now());
n.moves++;
const k = `${event_id}|${book}|${c.market}`;
pending.set(k, [...(pending.get(k) ?? []), { ...c, move }]);
}
}
// One block per game; per book and market, the largest move and how many other lines moved with it.
function render(batch) {
const games = new Map();
for (const [k, list] of batch) {
const [event_id, book] = k.split("|");
const e = events.get(event_id);
const c = list.reduce((a, b) => (Math.abs(b.move) > Math.abs(a.move) ? b : a));
const side = c.side === "home" ? e.home : c.side === "away" ? e.away : c.side;
const line = c.line == null ? "" : ` ${c.market === "spread" && c.line > 0 ? "+" : ""}${c.line}`;
const more = list.length > 1 ? ` and ${list.length - 1} more ${c.market} prices` : "";
const text = `${esc(NAME[book] ?? book)} ${c.market} ${esc(side)}${line}: ${fmt(c.prev_american)} → <b>${fmt(c.american)}</b> (${c.move > 0 ? "+" : ""}${c.move.toFixed(1)} pts)${more}`;
games.set(event_id, [...(games.get(event_id) ?? [`<b>${esc(e.away)} @ ${esc(e.home)}</b>`]), text]);
}
return [...games.values()].flat();
}
// WebSocket: auth, then subscribe to the leagues, game markets and sportsbooks; resume with the last seq after a drop.
let lastSeq = 0, stopping = false, ws;
function connect(resumed = false) {
ws = new WebSocket("wss://api.pricedodds.com/v1/stream");
ws.addEventListener("open", () => ws.send(JSON.stringify({ type: "auth", key: KEY })));
ws.addEventListener("message", (msg) => {
const f = JSON.parse(msg.data);
if (f.seq) lastSeq = Math.max(lastSeq, f.seq);
const filters = { leagues: LEAGUES, markets: MARKETS, books: BOOKS };
if (f.type === "ready") ws.send(JSON.stringify(resumed ? { type: "resume", since_seq: lastSeq, ...filters } : { type: "subscribe", ...filters }));
if (f.type === "snapshot") for (const { event: e } of f.data) events.set(e.id, { league: e.league.id, away: e.away.name, home: e.home.name, status: e.status, startsAt: e.startsAt });
if ((f.type === "score" || f.type === "event") && events.has(f.data?.id ?? f.data?.event_id) && f.data.status) events.get(f.data.id ?? f.data.event_id).status = f.data.status;
if (f.type === "price") onPrice(f.data);
if (f.type === "error") console.error(f);
});
ws.addEventListener("close", (e) => {
if (stopping || [4001, 4002, 4003].includes(e.code)) return; // key, billing or plan: fix the account first
setTimeout(() => connect(true), 2000);
});
}
connect();
// "/best <team>": best price per side at the sportsbooks from GET /v1/best, for the next game of that team.
async function best(query) {
const q = query.trim().toLowerCase();
const games = [...events.entries()].filter(([, e]) => q.length >= 3 && `${e.away} ${e.home}`.toLowerCase().includes(q) && e.status !== "final")
.sort((a, b) => a[1].startsAt.localeCompare(b[1].startsAt));
if (!games.length) return [`No game found for "${esc(query.trim())}". Try part of a team name, such as /best celtics.`];
const out = [];
for (const [id, e] of games.slice(0, 1)) {
const rows = [];
let cursor = "";
do { // GET /v1/best pages with a next cursor
const page = await api(`/best?league=${e.league}&market=moneyline@game,spread@game,total@game&books=${BOOKS.join(",")}${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
rows.push(...page.data.filter((r) => r.event_id === id));
cursor = page.next;
} while (cursor);
out.push(`<b>${esc(e.away)} @ ${esc(e.home)}</b>${e.status === "live" ? " (live)" : ""}`);
for (const r of rows) for (const s of r.selections) {
if (!s.best) continue;
const side = s.side === "home" ? e.home : s.side === "away" ? e.away : s.side;
const line = s.line == null ? "" : ` ${r.market === "spread" && s.line > 0 ? "+" : ""}${s.line}`;
out.push(`${r.market} ${esc(side)}${line}: <b>${fmt(s.best.american)}</b> ${esc(NAME[s.best.book] ?? s.best.book)}`);
}
if (!rows.length) out.push("No sportsbook prices right now.");
}
return out;
}
// Commands by long polling with getUpdates (it does not work while a webhook is set for the bot).
let offset = 0;
async function commands() {
while (!stopping) {
const updates = await tg("getUpdates", { offset, timeout: 25, allowed_updates: ["message"] });
for (const u of updates) {
offset = u.update_id + 1;
const m = u.message;
if (!m?.text) continue;
if (String(m.chat.id) !== CHAT) { n.ignored++; continue; } // a stranger who finds the bot gets nothing
n.commands++;
const [cmd, ...rest] = m.text.split(" ");
if (cmd.startsWith("/best")) await send(await best(rest.join(" ")));
else await send([`Moves of ${MIN_POINTS}+ points at US sportsbooks, pre-game, ${LEAGUES.join(", ")}.`, "/best <team> shows the best moneyline, spread and total."]);
}
}
}
commands();
const timer = setInterval(async () => {
if (!pending.size) return;
const batch = pending; pending = new Map();
await send(render(batch));
}, BATCH_SECONDS * 1000);
if (Number.isFinite(SECONDS)) setTimeout(async () => {
stopping = true;
clearInterval(timer);
ws.close();
if (pending.size) await send(render(pending));
console.log(`summary: ${n.changes} pre-game price changes, ${n.moves} moves of ${MIN_POINTS}+ points, ${n.muted} muted by the cooldown, ${n.commands} commands, ${n.ignored} from other chats ignored, ${n.sent} messages sent, ${n.retries} retries after 429`);
process.exit(0);
}, SECONDS * 1000);Run it with PRICEDODDS_API_KEY=$PRICEDODDS_API_KEY TELEGRAM_BOT_TOKEN=... TELEGRAM_CHAT_ID=... node telegram-odds-bot.mjs. It runs until you stop it; SECONDS stops it after that many seconds and prints a summary. TELEGRAM_API points it at another Bot API server, such as a self-hosted one; we used it for the test below.
What did a real run return?
We ran the bot on November 25, 2026, 18:44 UTC, about 2 p.m. Eastern, with SECONDS=180 and the default settings, against live prices. On the PricedOdds side everything was real: the book list, the WebSocket and GET /v1/best. In 180 seconds it read 2,848 pre-game price changes at the sportsbooks; 180 moved 2 points or more, 55 more were held back by the cooldown, and the moves went out in 12 messages.
The reply to /best 76ers, as the chat shows it:
Miami Heat @ Philadelphia 76ers
moneyline Philadelphia 76ers: -115 Circa Sports
moneyline Miami Heat: +101 DraftKings
spread Philadelphia 76ers -1.5: -105 Hard Rock Bet
spread Miami Heat +1.5: -106 FanDuel
total over 237.5: -110 DraftKings
total under 237.5: -102 FanDuelThe first alert message:
UC Davis Aggies @ Omaha Mavericks
Caesars Sportsbook spread Omaha Mavericks +2.5: +110 → +120 (-2.2 pts)
Saint Peter's Peacocks @ Columbia Lions
BetRivers spread Saint Peter's Peacocks +14.5: -120 → -141 (+4.0 pts) and 3 more spread prices
Hard Rock Bet spread Saint Peter's Peacocks +17.5: -200 → -240 (+3.9 pts) and 20 more spread prices
Arkansas Pine Bluff Golden Lions @ South Dakota Coyotes
Caesars Sportsbook total under 148.5: +100 → +110 (-2.4 pts) and 3 more total pricesThese are prices of one afternoon, shown as an example and not as current prices. A move of a few points on an alternate spread far from the main line is common and says little on its own; the "more ... prices" count shows when a book moved a whole ladder.
What we did not test. We did not send anything to a real Telegram chat. TELEGRAM_API pointed to a small local server that answers the way the Bot API documentation describes: the first sendMessage got HTTP 429 with retry_after 1, and the bot waited and sent it again; the other 14 calls got ok, all JSON with parse_mode HTML. Its getUpdates returned /best 76ers from the bot's chat, the same command from another chat, and /start. The bot answered the two from its own chat, ignored the other one, and moved offset past each update. The longest message had 791 characters, no message used a tag other than <b> or an unescaped & or <, and no two messages went out less than a second apart. So the API side ran for real, and the Telegram side ran against a stand-in.
How do I change what the bot sends?
MIN_POINTS: the size of a move, in points of implied probability. The implied probability calculator shows what a price is worth in those points.LEAGUES: any league id from the coverage page. The WebSocket subscription builder writes the subscribe message for other leagues, books or markets.- Books: replace
BOOKSwith the ids you bet at, such as["draftkings", "fanduel"], so both the alerts and/bestuse only those. - Player props: add their market keys from the market key finder to
MARKETSand the name from theplayerobject of each change to the message. - More commands:
getUpdatesgives you every message sent to the bot, so a/muteor/thresholdcommand is a few more lines incommands().
What are the limits of a Telegram odds bot?
Prices move in seconds, so check the price at the book before you act on a message. A move says that a book changed its price, not why. The bot keeps nothing after it stops: to look back at moves, record them, as in odds history in SQLite. Telegram's limits apply per bot, so one bot posting to many chats has to pace itself across all of them. Nothing here is betting advice.
FAQ
Do I need a server with a public URL for a Telegram bot?
No. This bot asks Telegram for new messages with getUpdates long polling, so it runs from any machine that can make outgoing requests. A webhook needs a public HTTPS URL, and the two ways cannot be used at the same time.
Can the bot post to a group or a channel?
Yes. Set TELEGRAM_CHAT_ID to the id of the group, or to the channel's @username. In a group, Telegram allows 20 messages per minute, so raise BATCH_SECONDS.
Can other people use my bot?
Anyone can find a bot by its username, but this one answers only the chat in TELEGRAM_CHAT_ID and ignores the rest. In our test it ignored the command from the other chat.
Where do I start?
Create the bot, find your chat id and run the script with SECONDS=180 on one league before you leave it running. The fields are in the docs and the books and leagues are on the coverage page. Every plan starts with a 3-day free trial with a $1 card verification that is refunded immediately. The plan you pick at signup is charged from day 4 unless you cancel before the trial ends. See pricing or create an account.