Cricket Score Alert Telegram Bot using EspnCricinfo

Hi Everyone, Last week I tried to build a project as a part of Crio #IBelieveinDoing. The idea of this project is to implement a functionality that features regular updates of a cricket match on a Telegram group.

Vishnu Kant Shukla
3 min readMar 30, 2021

The primary goal of the project is to build the score alerts functionality from scratch using python.

In this project, we will be going to learn

  1. REST
  2. HTTP
  3. telegram bot using python

Now Let’s dive into the Project step-wise.

Prototyping Score Alerts

  1. We are going to explore the “https://www.espncricinfo.com/".
  2. Select a scoreboard of a match and inspect the element to figure out the correct API.
  3. Check out the response of the API.

Fetching the Live scores and Parsing Data

Once you figure out the correct API, now it's time to start writing code using Python.

  1. Use the API from the “Cricinfo” website and fetch the live scores of a match.
  2. Parse the data to extract meaningful data such as balls, wickets, Target score, etc.

Sending Notification Using Telegram Bot

Set Up Your Bot Profile

  • Search for the @botfather in Telegram.
  • Start your conversation by pressing the Start button.
  • Create the bot by running /newbot command.
  • Enter the Display Name and User Name for the bot.
  • BotFather will send you a message with the token (keep your access token securely).

You can use this link for a better understanding of setting a bot “ https://www.codementor.io/@karandeepbatra/part-1-how-to-create-a-telegram-bot-in-python-in-under-10-minutes-19yfdv4wrq”.

Coding Your Bot

  • Import Library and initialize bot and dispatcher.
from aiogram import Bot, Dispatcher, executor, typesAPI_TOKEN = 'bot api'# Configure logginglogging.basicConfig(level=logging.INFO)# Initialize bot and dispatcherbot = Bot(token=API_TOKEN)dp = Dispatcher(bot)
  • Write functions to send and receive alerts based on user choice.
# In first function User can get live matches information just by sending /start command.@dp.message_handler(commands=['start', 'help'])async def send_welcome(message: types.Message):"""This handler will be called when user sends `/start` or `/help` command"""await message.reply("Hi,\n I am cricket score Bot. I will update you on the live score of todays game.")if matches_detail:await message.reply(matches_detail_str)else:await message.reply('No Live coverage going on!! \n-----BYE----')# In second method user has to choose on which match he wants to receive alerts.@dp.message_handler()async def echo(message: types.Message):await message.reply(message.text)if len(message.text) in [5,6] and matches_detail_str.find(message.text.lower())!=-1:a=int(message.text[-1])cache=[]while True:url=f"https://hs-consumer-api.espncricinfo.com/v1/pages/match/details?seriesId={matches_detail[a-1][2]}&matchId={matches_detail[a-1][0]}&latest=true"r=requests.get(url).json()if r['recentBallCommentary']:recent_ball=r['recentBallCommentary']['ballComments'][0]four='Four Runs ' if recent_ball['isFour'] else ''six='SIX Runs ' if recent_ball['isSix'] else ''wicket='OUT ' if recent_ball['isWicket'] else ''if recent_ball['oversActual'] not in cache:if cache:cache.pop(0)cache.append(recent_ball['oversActual'])if four or six or wicket:runs= '' if four or six or wicket else str(recent_ball['totalRuns'])+' Runs'recent=str(recent_ball['oversActual'])+' '+recent_ball['title']+', '+four+six+wicket+runsawait bot.send_message(chat_id,recent)if str(recent_ball['oversActual']).find('.6')!=-1:batsman_info=batsman_data(r)bowler_info=bowler_data(r)output='batting=> '+' || '.join(batsman_info) +'\n'+'bowling=> '+' || '.join(bowler_info)await bot.send_message(chat_id,output)time.sleep(30)wait_time(40)else:wait_time(30)else:await message.reply('No Live commentary available for this match')
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)

Now, your Bot is ready to send the alerts of an ongoing match whenever there will be Four, Six, or on any wicket.

For a complete source code check my Github repository: https://github.com/shukl08vk/Cricket-Score-Alert-on-Telegram.

--

--