DEV Community

Games tech02
Games tech02

Posted on

I Built a Cricket Score Telegram Bot in Python —Here's How (Free API)

A step-by-step walkthrough of building a live cricket score Telegram bot using Python, python-telegram-bot, and a free cricket API — including code you can copy-paste today.

Why I Built This

A few weeks ago, during a tight IPL run-chase, I got tired of alt-tabbing between my code editor and a cricket score website every two minutes. Being a developer, my solution to "annoying repetitive task" is almost always "automate it." So I decided to build a Telegram bot that pings me live scores on demand — and honestly, it took less time than writing this article.

In this post, I'll walk you through exactly how I built it: from wiring up a Telegram bot to fetching live scores, formatting them nicely, and deploying something you can start using today. All you need is Python, a free Telegram bot token, and a cricket data API.

Let's get into it.

What We're Building

A Telegram bot that responds to simple commands like:

/score — shows all live matches right now
/scorecard — full scorecard for a specific match

Nothing fancy on the frontend — Telegram chat is the UI. All the real work happens in a small Python script.

Step 1: Create Your Telegram Bot

Open Telegram, search for BotFather, and send /newbot. Follow the prompts to name your bot. BotFather will hand you a token that looks like:

123456789:AAHn3s7sdlkj2938fslkdjf_example

Save that somewhere safe — you'll need it in your Python script.

Step 2: Get a Cricket Data API Key

You obviously need a reliable source of live match data. I tried scraping a couple of score websites first (please don't do this — it's fragile and breaks the moment the site changes its HTML). Instead, I ended up using CricLive API (cricketliveapi.com), mainly because it has a genuinely free tier — 500 calls a day, no credit card required — which is more than enough for a personal bot that a handful of friends use.

Head to cricketliveapi.com/register, grab your API key, and keep it handy. You'll use it as a bearer token in your requests.

Step 3: Install Dependencies
bash
pip install python-telegram-bot requests

We're using python-telegram-bot (v20+, which is async) and the good old requests library for API calls.

Step 4: Fetch Live Scores

Let's start with a simple function that hits the live scores endpoint:

python
import requests

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://cricketliveapi.com/

HEADERS = {
"Authorization": f"Bearer {API_KEY}"
}

def get_live_scores():
response = requests.get(f"{BASE_URL}live-scores", headers=HEADERS)
response.raise_for_status()
return response.json()

Response times from CricLive API were consistently under 200ms in my testing (their servers are based in India, which helps a lot if most of your audience — like mine — is following IPL or domestic matches). That matters when you're formatting and sending a Telegram message in near real-time; nobody wants a "live" score bot that feels laggy.

Step 5: Format the Response for Telegram

Raw JSON isn't fun to read in a chat window, so let's format it nicely:

python
def format_live_scores(data):
matches = data.get("matches", [])
if not matches:
return "No live matches right now 🏏"

lines = []
for match in matches:
    lines.append(
        f"🏏 *{match['team1']} vs {match['team2']}*\n"
        f"{match['status']}\n"
        f"Score: {match['score']}\n"
        f"Match ID: `{match['id']}`\n"
    )
return "\n".join(lines)
Enter fullscreen mode Exit fullscreen mode

That Match ID is important — we'll use it later to fetch the full scorecard.

Step 6: Wire It Up to Telegram

Now let's connect this to actual bot commands:

python
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes

TELEGRAM_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"

async def score_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
data = get_live_scores()
message = format_live_scores(data)
await update.message.reply_text(message, parse_mode="Markdown")

async def scorecard_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not context.args:
await update.message.reply_text("Usage: /scorecard ")
return

match_id = context.args[0]
response = requests.get(
    f"{BASE_URL}match/{match_id}/scorecard", headers=HEADERS
)
data = response.json()

innings_text = ""
for innings in data.get("innings", []):
    innings_text += f"\n*{innings['team']}*: {innings['total']}\n"

await update.message.reply_text(
    innings_text or "Scorecard not available yet.", parse_mode="Markdown"
)
Enter fullscreen mode Exit fullscreen mode

app = ApplicationBuilder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("score", score_command))
app.add_handler(CommandHandler("scorecard", scorecard_command))

app.run_polling()

Run this script (python bot.py), open Telegram, and message your bot /score. If everything's wired correctly, you'll get a live-updating list of matches straight in your chat.

Step 7: Bonus — Auto-Refresh Every Few Minutes

If you want the bot to push updates automatically instead of waiting for a /score command, you can use python-telegram-bot's job queue:

python
async def auto_update(context: ContextTypes.DEFAULT_TYPE):
data = get_live_scores()
message = format_live_scores(data)
await context.bot.send_message(chat_id=YOUR_CHAT_ID, text=message, parse_mode="Markdown")

app.job_queue.run_repeating(auto_update, interval=120, first=10)

This pings your chat every 2 minutes with fresh scores. Just be mindful of your API rate limit — on the free CricLive API tier that's 500 calls/day, which works out to roughly one call every 3 minutes if it's running 24/7. For a bot only active during match hours, this is comfortably within budget.

A Few Things I Learned Along the Way
Cache aggressively. Live scores don't need to be fetched more than once every 30-60 seconds even during a fast T20 chase. Don't burn API calls unnecessarily.
Handle "no live match" gracefully. Most of the day, there's nothing live — your bot should say that clearly instead of throwing an error.
Match IDs are your friend. Once you have them from /live-scores, you can plug them straight into the scorecard and fantasy endpoints without extra lookups.
Rate limits sneak up on you. If you're testing a lot during development, you'll chew through your daily quota fast — plan your testing accordingly.
What's Next

Once you have live scores flowing, it's a small step to extend this bot further:

Add /fantasy/points/{id} to post live fantasy points during Dream11-style contests with friends
Add /fantasy/playing-xi/{id} to notify your group chat the moment playing XIs are announced (usually 30-60 minutes before the toss)
Deploy it on a free-tier server (Railway, Render, or a small VPS) so it runs even when your laptop's closed

I've genuinely kept mine running for a full IPL season now, and it's saved me more browser tabs than I can count.

Wrapping Up

Building a live score bot is a great weekend project if you want something practical to show off — and it's a nice intro to working with real-time sports data APIs in general. The hardest part isn't the Python code, it's finding a data source that's reliable and doesn't require a credit card just to try it out.

Top comments (0)