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.
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
- REST
- HTTP
- telegram bot using python
Now Let’s dive into the Project step-wise.
Prototyping Score Alerts
- We are going to explore the “https://www.espncricinfo.com/".
- Select a scoreboard of a match and inspect the element to figure out the correct API.
- 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.
- Use the API from the “Cricinfo” website and fetch the live scores of a match.
- 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
- Install AIOGRAM framework for Telegram BOT API (https://pypi.org/project/aiogram/).
- 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.
Ten articles before and after
Get Telegram Group Members with Python and Telethon – Telegram Group
Creating a Telegram bot with python – Telegram Group
RSA with telegram bot using Python – Telegram Group
PyCryptoBot with Telegram. I received a feature request in the… – Telegram Group
Je vais booster vos abonnés/ventes grâce à une grosse promotion sur Telegram – Telegram Group
Improved node setup and monitoring for the validator of the Agoric testnet – Telegram Group
Telegram Bot in JAVA| by Naveen Kumar M N – Telegram Group
data-rh=”true”>Airdrop 20 WYD ($50) – ALVIN LAGONERO – Medium – Telegram Group
Como criar um Bot no Telegram com NodeJS – Telegram Group
.Net Core Console Uygulması İle Telegram Botu Geliştirmek – Telegram Group