Home » Python projects » Python bot to track vaccine slot and send notification on Telegram

Python bot to track vaccine slot and send notification on Telegram

Automate telegram with Python

After following all the steps mentioned here, you will be able to create a Python script (we are calling it a bot) that we fetch the data from the cowin portal using REST API, and if it finds any available slot then immediately trigger a customized message on the Telegram (a specified telegram group). This way, you will be worry-free from always visiting the cowin portal and perform a search to find the slot on a specific day at a certain Pincode. A complete and working python code is available below.


Table of Contents


Prerequisites

Description

Well, if you satisfy all the requirements mentioned in the prerequisites section then I congratulate you in advance because you will definitely build this notification system in couple of hours from now.

Let’s get started now!

First of all, check the version of Python installed on your system, you can do so by writing python in the command prompt and hit enter.

python

You will see a version number as shown below.

D:\aipython>python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Make sure you install all the dependencies like Requests and Pytz library

Create a bot in Telegram using botfather – By following the steps from video

Create a Group on Telegram – By Following the steps from video

You can use an existing Telegram app on Phone or you could download one for PC

Gear-up for CODING

Step 1: Importing necessary Module (Library) as shown below

import requests
from datetime import datetime, timedelta
import time
import pytz
from os import environ

Step 2: Listing down all the Constants in the code

Define all the constants
time_interval = 20  # (in seconds) Specify the frequency of code execution
PINCODE = "801503"
msg = "Blank"
tele_auth_token = environ['Tele_auth_tok'] # Authentication token provided by Telegram bot
tel_group_id = "Test_Telegram_group"      # Telegram group name
IST = pytz.timezone('Asia/Kolkata')           # Indian Standard Time - Timezone
slot_found =  False                                   # Intial slot found status
header = {'User-Agent': 'Chrome/84.0.4147.105 Safari/537.36'}

Step 3: Create a Function to update Date and time as well as send API request with updated parameters

def update_timestamp_send_Request(PINCODE):
     raw_TS = datetime.now(IST) + timedelta(days=1)      # Tomorrows date
     tomorrow_date = raw_TS.strftime("%d-%m-%Y")         # Formatted Tomorrow's date
     today_date = datetime.now(IST).strftime("%d-%m-%Y") #Current Date
     curr_time = (datetime.now().strftime("%H:%M:%S"))   #Current time
     request_link = f"https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={PINCODE}&date={tomorrow_date}"
     response = requests.get(request_link, headers = header)
     raw_JSON = response.json()
     return raw_JSON, today_date, curr_time

Step 4: Create a function to check the vaccination slot availability for age group 45 and above

def get_availability_45(age = 45):
     raw_JSON, today_date, curr_time = update_timestamp_send_Request(PINCODE)
     for cent in raw_JSON['centers']:
         for sess in cent["sessions"]:
             sess_date = sess['date']
             if sess["min_age_limit"] == age and sess["available_capacity"] > 0:
                 slot_found =  True
                 msg = f"""For age 45+ [Vaccine Available] at {PINCODE} on {sess_date}\n\tCenter : {cent["name"]}\n\tVaccine: {sess["vaccine"]}\n\tDose_1: {sess["available_capacity_dose1"]}\n\tDose_2: {sess["available_capacity_dose2"]}"""
                 send_msg_on_telegram(msg)
                 print (f"INFO:[{curr_time}] Vaccine Found for 45+ at {PINCODE}")
     else:
         slot_found =  False
         print (f"INFO: [{today_date}-{curr_time}] Vaccine NOT-Found for 45+ at {PINCODE}")

Step 5: Create another function to check the vaccination slot availability for age group between 18 and 44

def get_availability_18(age = 18):
     raw_JSON, today_date, curr_time = update_timestamp_send_Request(PINCODE)
     for cent in raw_JSON['centers']:
         for sess in cent["sessions"]:
             sess_date = sess['date']
             if sess["min_age_limit"] == age and sess["available_capacity"] > 0:
                 slot_found =  True
                 msg = f"""For age 18+ [Vaccine Available] at {PINCODE} on {sess_date}\n\tCenter : {cent["name"]}\n\tVaccine: {sess["vaccine"]}\n\tDose_1: {sess["available_capacity_dose1"]}\n\tDose_2: {sess["available_capacity_dose2"]}"""
                 send_msg_on_telegram(msg)
                 print (f"INFO: [{curr_time}] Vaccine Found for 18+ at {PINCODE}")
     else:
         slot_found =  False
         print (f"INFO: [{today_date}-{curr_time}] Vaccine NOT Found for 18+ at {PINCODE}")

Step 6: Create a function to send the custom message built by the corresponding function

def send_msg_on_telegram(msg):
     telegram_api_url = f"https://api.telegram.org/bot{tele_auth_token}/sendMessage?chat_id=@{tel_group_id}&text={msg}"
     tel_resp = requests.get(telegram_api_url)
 if tel_resp.status_code == 200:
     print ("Notification has been sent on Telegram") 
else:
     print ("Could not send Message")

Step 7 (Optional): Create a section to detect the local operation (means code is directly executed by this file) and make it run continuously

if name == "main":    
     while True:
         get_availability_45()
         get_availability_18()
         time.sleep(time_interval)

Complete project code

""" 
 Developer: aipython on [29-05-2021]
 website: www.aipython.in
 Sends Notifications on a Telegram channel , whenever the vaccine slot is available at the given PINCODE 
 """
 import requests
 from datetime import datetime, timedelta
 import time
 import pytz
 from os import environ
 Define all the constants
 time_interval = 20 # (in seconds) Specify the frequency of code execution
 PINCODE = "801503"
 msg = "Blank"
 tele_auth_token = environ['Tele_auth_tok'] # Authentication token provided by Telegram bot
 tel_group_id = "Test_Telegram_group"     # Telegram group name
 IST = pytz.timezone('Asia/Kolkata')        # Indian Standard Time - Timezone
 slot_found =  False                        # Intial slot found status
 header = {'User-Agent': 'Chrome/84.0.4147.105 Safari/537.36'}
 def update_timestamp_send_Request(PINCODE):
     raw_TS = datetime.now(IST) + timedelta(days=1)      # Tomorrows date
     tomorrow_date = raw_TS.strftime("%d-%m-%Y")         # Formatted Tomorrow's date
     today_date = datetime.now(IST).strftime("%d-%m-%Y") #Current Date
     curr_time = (datetime.now().strftime("%H:%M:%S"))   #Current time
     request_link = f"https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={PINCODE}&date={tomorrow_date}"
     response = requests.get(request_link, headers = header)
     raw_JSON = response.json()
     return raw_JSON, today_date, curr_time
 def get_availability_45(age = 45):
     raw_JSON, today_date, curr_time = update_timestamp_send_Request(PINCODE)
     for cent in raw_JSON['centers']:
         for sess in cent["sessions"]:
             sess_date = sess['date']
             if sess["min_age_limit"] == age and sess["available_capacity"] > 0:
                 slot_found =  True
                 msg = f"""For age 45+ [Vaccine Available] at {PINCODE} on {sess_date}\n\tCenter : {cent["name"]}\n\tVaccine: {sess["vaccine"]}\n\tDose_1: {sess["available_capacity_dose1"]}\n\tDose_2: {sess["available_capacity_dose2"]}"""
                 send_msg_on_telegram(msg)
                 print (f"INFO:[{curr_time}] Vaccine Found for 45+ at {PINCODE}")
     else:
         slot_found =  False
         print (f"INFO: [{today_date}-{curr_time}] Vaccine NOT-Found for 45+ at {PINCODE}")
 def get_availability_18(age = 18):
     raw_JSON, today_date, curr_time = update_timestamp_send_Request(PINCODE)
     for cent in raw_JSON['centers']:
         for sess in cent["sessions"]:
             sess_date = sess['date']
             if sess["min_age_limit"] == age and sess["available_capacity"] > 0:
                 slot_found =  True
                 msg = f"""For age 18+ [Vaccine Available] at {PINCODE} on {sess_date}\n\tCenter : {cent["name"]}\n\tVaccine: {sess["vaccine"]}\n\tDose_1: {sess["available_capacity_dose1"]}\n\tDose_2: {sess["available_capacity_dose2"]}"""
                 send_msg_on_telegram(msg)
                 print (f"INFO: [{curr_time}] Vaccine Found for 18+ at {PINCODE}")
     else:
         slot_found =  False
         print (f"INFO: [{today_date}-{curr_time}] Vaccine NOT Found for 18+ at {PINCODE}")
 def send_msg_on_telegram(msg):
     telegram_api_url = f"https://api.telegram.org/bot{tele_auth_token}/sendMessage?chat_id=@{tel_group_id}&text={msg}"
     tel_resp = requests.get(telegram_api_url)
 if tel_resp.status_code == 200:
     print ("Notification has been sent on Telegram") 
else:
     print ("Could not send Message")
 if name == "main":    
     while True:
         get_availability_45()
         get_availability_18()
         time.sleep(time_interval)

Find more codes on GitHub

Disclaimer

This code works perfectly but it is not yet mature. We will keep on using this code and will try to find bugs or improvement in the existing code, as and when these bugs or improvement are found, we will update the newer version of the code here (A newer version below the older version).

Hope you like it. If yes, then please share it with someone who is really interested in building one such application.

Way Forward

Once you know the concept of retrieving the content from internet, and learn automate a mobile or desktop application, then there could be infinite possibilities to explore your imagination. All the best.

Keep Learning and Keep Growing !!

4 thoughts on “Python bot to track vaccine slot and send notification on Telegram”

How did you like the content

Scroll to Top