The cheapest way to get a goal alert is to stop asking. A polling bot calls an API every few seconds, 24 hours a day, to learn that nothing changed. A webhook bot sits quietly until the data provider calls you.
In this tutorial we build a FastAPI service that receives sports webhooks and fans them out to Telegram and Discord. It handles the things that break real alert bots: duplicate deliveries, slow handlers, failed sends, rate limits and fake requests. You can test the entire thing without an API key, using a small script that fires sample events at your own server.
Disclosure: I work on Orbistats, the data source in this series. The pattern works with any provider that supports webhooks.
What we are building
text
Orbistats ──POST──▶ FastAPI receiver ──▶ dedupe (SQLite) ──▶ ┌─▶ Telegram
(webhook) /webhooks/orbistats ack in <1s └─▶ Discord
verify signature send in background
A receiver endpoint that verifies, filters and acknowledges instantly.
Idempotent delivery: the same event never alerts twice.
Two notifiers (Telegram and Discord) that fail independently.
A test sender so you can develop with zero external dependencies.
Polling math, for perspective. Polling every 10 seconds across 6 live hours is 2,160 requests a day to deliver maybe a few dozen events. A webhook bot makes zero requests to learn about those events.
Prerequisites
Python 3.10+ and a terminal.
A Telegram account and/or a Discord server where you can add a webhook.
An Orbistats account is optional until the last step. If you want to see real payloads first, use the sandbox. For how webhooks are registered and what events exist, read the Webhooks API docs.
Step 1: Project setup
bash
mkdir score-alerts && cd score-alerts
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
requirements.txt:
text
fastapi
uvicorn[standard]
httpx
python-dotenv
bash
pip install -r requirements.txt
Step 2: Get your Telegram and Discord credentials
Telegram (2 minutes):
Open @botfather, send /newbot, and copy the bot token.
Add the bot to your group, or make it an admin of your channel.
Send any message in that chat, then open https://api.telegram.org/bot/getUpdates and copy the chat.id value. Group and channel ids are usually negative numbers.
Discord (1 minute):
In your server: Server Settings → Integrations → Webhooks → New Webhook.
Pick a channel and click Copy Webhook URL.
Create .env and add it to .gitignore:
bash
TELEGRAM_BOT_TOKEN=123456:ABC...
TELEGRAM_CHAT_ID=-1001234567890
DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...
WEBHOOK_SECRET=change-me-long-random-string
WEBHOOK_SIGNATURE_HEADER=X-Signature
ALERT_TYPES=goal,red_card,full_time
SEEN_DB=seen.db
Treat the Discord webhook URL like a password. Anyone who has it can post to your channel.
Step 3: The event model (the only place we assume a payload shape)
Every provider names events differently, so we isolate that in one function. The rest of the app only ever sees our own Event. The match fields below follow the live-match example in the Orbistats docs (match_id, minute, home.name, home.score). The event envelope (type, id, data) is an assumption: match it to the Webhooks docs.
Create events.py:
python
import hashlib
import html
from dataclasses import dataclass
@dataclass(frozen=True)
class Event:
id: str | None
type: str
match_id: str
minute: int | None
home: str
away: str
home_score: int
away_score: int
player: str | None = None
def normalize_event(p: dict) -> Event | None:
"""Map the provider's webhook payload into our own Event.
ASSUMPTION: adjust field names to the real payload in the Webhooks docs."""
data = p.get("data", p)
match = data.get("match", data)
home = match.get("home") or {}
away = match.get("away") or {}
etype = str(p.get("type") or data.get("type") or "").lower().replace(" ", "_")
match_id = match.get("match_id") or data.get("match_id")
if not etype or not match_id:
return None # not an event we understand
minute = match.get("minute")
if minute is None:
minute = data.get("minute")
player = data.get("player")
if isinstance(player, dict):
player = player.get("name")
return Event(
id=p.get("id"),
type=etype,
match_id=str(match_id),
minute=int(minute) if minute is not None else None,
home=home.get("name", "Home"),
away=away.get("name", "Away"),
home_score=int(home.get("score") or 0),
away_score=int(away.get("score") or 0),
player=player,
)
def dedupe_key(e: Event) -> str:
"""Prefer the provider's event id; otherwise derive a stable key."""
if e.id:
return f"id:{e.id}"
raw = f"{e.match_id}|{e.type}|{e.minute}|{e.home_score}-{e.away_score}|{e.player}"
return "h:" + hashlib.sha256(raw.encode()).hexdigest()[:24]
EMOJI = {"goal": "⚽", "red_card": "🟥", "yellow_card": "🟨",
"half_time": "⏸️", "full_time": "🏁"}
def headline(e: Event) -> str:
icon = EMOJI.get(e.type, "📣")
minute = f" {e.minute}'" if e.minute is not None else ""
return f"{icon} {e.type.replace('_', ' ').upper()}{minute}"
def body(e: Event) -> str:
line = f"{e.home} {e.home_score} – {e.away_score} {e.away}"
return f"{line}\n{e.player}" if e.player else line
def to_discord_text(e: Event) -> str:
return f"{headline(e)}\n{body(e)}"
def to_telegram_html(e: Event) -> str:
# Telegram HTML mode breaks on raw < > &, so always escape API data
return f"{html.escape(headline(e))}\n{html.escape(body(e))}"
Why a derived dedupe key? If a provider does not send a unique event id, hashing the match, event type, minute and score still gives you a stable key, so retries do not become double alerts.
Step 4: Remember what we have already sent (SQLite)
Create store.py:
python
import os
import sqlite3
import time
_db = sqlite3.connect(os.getenv("SEEN_DB", "seen.db"), check_same_thread=False)
_db.execute("CREATE TABLE IF NOT EXISTS seen (key TEXT PRIMARY KEY, at INTEGER NOT NULL)")
_db.commit()
def first_time(key: str) -> bool:
"""True only the first time a key is seen (atomic claim)."""
cur = _db.execute("INSERT OR IGNORE INTO seen (key, at) VALUES (?, ?)",
(key, int(time.time())))
_db.commit()
return cur.rowcount == 1
def forget(key: str) -> None:
"""Release a key so a retry can alert again (used when every send failed)."""
_db.execute("DELETE FROM seen WHERE key = ?", (key,))
_db.commit()
INSERT OR IGNORE makes the check-and-claim a single atomic statement, so two simultaneous deliveries cannot both win. For a long-running service, delete rows older than a week now and then.
Step 5: The notifiers (Telegram and Discord)
Create notify.py:
python
import asyncio
import os
import httpx
TG_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
TG_CHAT = os.getenv("TELEGRAM_CHAT_ID")
DISCORD_URL = os.getenv("DISCORD_WEBHOOK_URL")
async def _post_json(client: httpx.AsyncClient, url: str, payload: dict, retries: int = 2):
"""POST with a polite retry when the service says 429 (rate limited)."""
for attempt in range(retries + 1):
r = await client.post(url, json=payload, timeout=10)
if r.status_code != 429:
r.raise_for_status()
return
wait = r.headers.get("Retry-After")
await asyncio.sleep(min(float(wait), 10) if wait else 2 ** attempt)
raise RuntimeError("rate limited after retries")
async def send_telegram(client: httpx.AsyncClient, html_text: str):
if not (TG_TOKEN and TG_CHAT):
return # channel not configured
await _post_json(
client,
f"https://api.telegram.org/bot{TG_TOKEN}/sendMessage",
{"chat_id": TG_CHAT, "text": html_text,
"parse_mode": "HTML", "disable_web_page_preview": True},
)
async def send_discord(client: httpx.AsyncClient, text: str):
if not DISCORD_URL:
return
await _post_json(
client,
DISCORD_URL,
# allowed_mentions: [] stops a malicious payload from pinging @everyone
{"content": text, "allowed_mentions": {"parse": []}},
)
Two details are worth copying. allowed_mentions means even if a team name or player field contained @everyone, Discord would not ping anyone. And each notifier returns quietly when it is not configured, so you can run with only one channel.
Step 6: The receiver
This is the heart of the bot. It follows one rule: verify, filter, dedupe, acknowledge, and only then do the slow work.
Create app.py:
python
import asyncio
import hashlib
import hmac
import json
import logging
import os
import httpx
from dotenv import load_dotenv
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request
load_dotenv()
from events import dedupe_key, normalize_event, to_discord_text, to_telegram_html # noqa: E402
from notify import send_discord, send_telegram # noqa: E402
from store import first_time, forget # noqa: E402
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("score-alerts")
SECRET = os.getenv("WEBHOOK_SECRET", "")
SIG_HEADER = os.getenv("WEBHOOK_SIGNATURE_HEADER", "X-Signature")
ALERT_TYPES = set(os.getenv("ALERT_TYPES", "goal,red_card,full_time").split(","))
app = FastAPI()
def verify(raw: bytes, header_value: str | None) -> bool:
"""Generic HMAC-SHA256 check. ASSUMPTION: match header name and scheme
to the signature method documented in the Webhooks API docs."""
if not SECRET:
return True # signature check disabled: development only!
if not header_value:
return False
expected = hmac.new(SECRET.encode(), raw, hashlib.sha256).hexdigest()
received = header_value.removeprefix("sha256=")
return hmac.compare_digest(expected, received) # constant-time compare
async def fan_out(event, key: str):
async with httpx.AsyncClient() as client:
results = await asyncio.gather(
send_telegram(client, to_telegram_html(event)),
send_discord(client, to_discord_text(event)),
return_exceptions=True, # one failing channel must not block the other
)
failures = [r for r in results if isinstance(r, Exception)]
for f in failures:
log.error("notify failed: %s", f)
if len(failures) == len(results):
forget(key) # nothing was delivered, so allow a provider retry to alert
@app.post("/webhooks/orbistats")
async def receive(request: Request, background: BackgroundTasks):
raw = await request.body() # signature is computed on the RAW bytes
if not verify(raw, request.headers.get(SIG_HEADER)):
raise HTTPException(status_code=401, detail="bad signature")
try:
payload = json.loads(raw)
except ValueError:
raise HTTPException(status_code=400, detail="invalid json")
event = normalize_event(payload)
if event is None or event.type not in ALERT_TYPES:
return {"ok": True, "ignored": True}
key = dedupe_key(event)
if not first_time(key):
return {"ok": True, "duplicate": True}
background.add_task(fan_out, event, key) # send AFTER we respond
return {"ok": True}
@app.get("/health")
def health():
return {"ok": True}
Why each line matters:
Raw body first. HMAC signatures are computed over the exact bytes sent. Parse JSON before verifying and you may re-serialize differently, and valid requests will fail.
compare_digest. A normal == can leak timing information.
200 immediately. Providers usually retry slow or failed deliveries. Doing the Telegram and Discord calls in a background task keeps your response time tiny, so retries are rare.
Dedupe still exists because retries and network hiccups can deliver the same event twice anyway.
forget() on total failure. If both channels failed, releasing the key means a later retry can still alert, instead of the event being silently lost.
For production volume, replace BackgroundTasks with a real queue (Redis with RQ, Celery, or a cloud queue) so alerts survive a process restart.
Step 7: Test it with no API key
Build against a fake sender first. Create send_test_event.py:
python
import hashlib
import hmac
import json
import os
import httpx
from dotenv import load_dotenv
load_dotenv()
URL = os.getenv("TARGET", "http://localhost:8000/webhooks/orbistats")
SECRET = os.getenv("WEBHOOK_SECRET", "")
HEADER = os.getenv("WEBHOOK_SIGNATURE_HEADER", "X-Signature")
def send(payload: dict):
raw = json.dumps(payload).encode()
headers = {"Content-Type": "application/json"}
if SECRET:
headers[HEADER] = hmac.new(SECRET.encode(), raw, hashlib.sha256).hexdigest()
r = httpx.post(URL, content=raw, headers=headers, timeout=10)
print(r.status_code, r.json())
goal = {
"id": "evt_1001",
"type": "goal",
"data": {
"match_id": "match_50231",
"minute": 73,
"home": {"name": "Manchester City", "score": 3},
"away": {"name": "Arsenal", "score": 1},
"player": "J. Doe",
},
}
send(goal) # should alert once
send(goal) # same id again: should be reported as a duplicate
send({"id": "evt_1002", "type": "substitution",
"data": {"match_id": "match_50231", "minute": 75,
"home": {"name": "Manchester City", "score": 3},
"away": {"name": "Arsenal", "score": 1}}}) # not in ALERT_TYPES: ignored
Run the server in one terminal:
bash
uvicorn app:app --port 8000 --env-file .env
Run the sender in another:
bash
python send_test_event.py
You should see three results: {"ok": true} (and a message in Telegram and Discord), then {"ok": true, "duplicate": true}, then {"ok": true, "ignored": true}. Try removing the signature header or changing the secret and confirm you get a 401.
Step 8: Go live with real webhooks
Expose your server over HTTPS. For local testing use a tunnel, such as ngrok http 8000 or a Cloudflare Tunnel, and copy the public URL. For real use, deploy to a small always-on host (a VPS, Fly.io or Railway).
Get your access. Request access. Your plan’s access time starts when you open the activation link, so do this only when your receiver is ready and your tunnel is up.
Register your URL at https://YOUR-PUBLIC-URL/webhooks/orbistats the way the Webhooks API docs describe, and confirm the event names and payload shape against normalize_event().
Match the signature scheme. Update WEBHOOK_SIGNATURE_HEADER and verify() to the documented method, and set WEBHOOK_SECRET to the secret you were given.
Watch the first live event arrive. Check the API reference and the Live Scores API page for field names.
A minimal Dockerfile for deployment:
dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY *.py .
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
bash
docker build -t score-alerts .
docker run -d --restart unless-stopped --env-file .env -p 8000:8000 \
-v $(pwd)/data:/app/data -e SEEN_DB=/app/data/seen.db score-alerts
Which channel should you use?
Telegram Discord
Setup Bot token + chat id One webhook URL
Best for Personal alerts, small groups, channels Communities and servers
Rich formatting HTML or MarkdownV2 Markdown and embeds
Watch out for Chat ids differ for users, groups and channels Webhook URL is a secret
Common problems
Symptom Likely cause Fix
Duplicate alerts Provider retried because the first response was slow, or no event id Respond instantly, keep the dedupe table, use the derived key
Telegram error can't parse entities Unescaped <, > or & in team or player names Always pass API text through html.escape
Telegram chat not found or 403 Bot not in the chat, or wrong id Add the bot (admin for channels), re-check getUpdates, remember group ids are negative
Discord 404 or 401 Webhook deleted or URL copied wrongly Recreate the webhook and update .env
Your endpoint returns 401 for real events Signature computed on re-serialized JSON, wrong secret, or wrong header name Verify on the raw body, and copy the header and scheme from the docs
Nothing arrives at all Public URL not reachable or not HTTPS Test /health from outside, check the tunnel, check the provider’s delivery logs
Alerts arrive late Slow handler or a sleeping free-tier host Acknowledge first, queue the sends, keep an instance warm
Surprise @everyone pings Raw API text posted as Discord content Keep allowed_mentions set to an empty parse list
Alert lost after a Telegram outage Event marked as seen before delivery failed Use forget() when every channel fails, or move to a queue with retries
Security checklist
Never commit .env, the Telegram token or the Discord webhook URL, and rotate them if they leak.
Always verify signatures in production. An unverified endpoint lets anyone spam your channels.
Escape everything from the payload before it goes into HTML or chat markdown.
Respond with 2xx only after the event is safely handled or queued, and never leak internal errors in the response body.
Where to go next
Prefer a persistent connection? Compare this with the push approach in I Built a Discord Bot That Alerts Live Score Updates Using WebSockets.
Want the live screen too? Pair these alerts with the scoreboard from Build a Live Football Scoreboard in 20 Minutes.
New to the API? Start with Sports APIs Explained, and see how alerts fit into a bigger app in Build a Multi-Sport Dashboard.
Add features: per-team subscriptions (/follow Arsenal), a quiet-hours setting, odds-movement alerts, or a daily summary from the Sports Data API.
Monitor it: check provider health on the status page, and review pricing before you plan longer-running production use.
Wrap-up
You built an alert bot that never polls, never double-alerts, replies fast, survives one channel failing, and rejects forged requests. Just as important, every assumption about the provider’s payload lives in two small functions, so adapting to the real docs is a ten-minute job.
If you want to try it on real events, request the free hour and run Step 8. Should the next post add per-user /follow subscriptions, or odds-movement alerts? Let me know in the comments.
Top comments (0)