Complete guide to make Co-WIN Vaccine Registration Alert Bot

Gaurav Sharma Last Updated : 30 Oct, 2024
5 min read

This article was published as a part of the Data Science Blogathon

Introduction

Vaccination is now open for people of age above 18. But getting a vaccination appointment is as difficult as finding a needle in a haystack because slots are filled in an eye-blink. So, searching through the Co-WIN portal manually is slow and sometimes irritating as well because you will almost all the time land with a page showing all slots booked as there is a huge crowd of people who want to get vaccinated as early as possible.

So, this problem can be solved by making it easier for people to find out when the next appointment is available in their region. We will be using Co-WIN API which is made public by the government and we will also use telegram BOT API to send automated alerts on telegram about the details of the vaccination center.

So, let us get started!

A short introduction to API

A short introduction to API

Source:https://www.altexsoft.com

API is the acronym for Application Programming Interface. It is a software intermediary that allows two applications to talk to each other. Each time you use an app like Facebook, send an instant message on WhatsApp or telegram, check the weather on your phone, it is the API working behind the scenes.

When you use an application on the internet, the application sends data to a server. The server then retrieves that data, interprets it, performs the necessary action, and sends it back to your phone which is then presented to you in a readable way you want. This is what an API is – all of this happens via API.

 

Starting with Co-WIN API

You can get API from the API Setu website of government: https://apisetu.gov.in/public/api/cowin. These APIs are subject to a rate limit of 100 API calls per 5 minutes per IP. So, keep this in mind. We will be finding the slot for a week from today in a region by using a PIN CODE.  So, first let’s see what the output of API is if I give Pin code: 243001 and Date: 19-05-2021

URL: https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByPin?pincode=243001&date=19-05-2021

OUTPUT:

{
  "sessions": [
    {
      "center_id": 566656,
      "name": "District Hospital Bareilly",
      "address": "District Hospital",
      "state_name": "Uttar Pradesh",
      "district_name": "Bareilly",
      "block_name": "Civil Line UPHC",
      "pincode": 243001,
      "from": "09:00:00",
      "to": "17:00:00",
      "lat": 28,
      "long": 79,
      "fee_type": "Free",
      "session_id": "f349eb34-f5ba-4c40-855c-17d667dd2ca9",
      "date": "19-05-2021",
      "available_capacity_dose1": 0,
      "available_capacity_dose2": 20,
      "available_capacity": 20,
      "fee": "0",
      "min_age_limit": 45,
      "vaccine": "COVISHIELD",
      "slots": [
        "09:00AM-11:00AM",
        "11:00AM-01:00PM",
        "01:00PM-03:00PM",
        "03:00PM-05:00PM"
      ]
    },
    {
      "center_id": 610552,
      "name": "Subhas Nagar Uphc Bareilly",
      "address": "Subhash Nagar Bareilly",
      "state_name": "Uttar Pradesh",
      "district_name": "Bareilly",
      "block_name": "Subhash Nagar UPHC",
      "pincode": 243001,
      "from": "09:00:00",
      "to": "17:00:00",
      "lat": 28,
      "long": 79,
      "fee_type": "Free",
      "session_id": "b6481a0b-9ec5-4ec4-8251-960e93182027",
      "date": "19-05-2021",
      "available_capacity_dose1": 0,
      "available_capacity_dose2": 20,
      "available_capacity": 20,
      "fee": "0",
      "min_age_limit": 45,
      "vaccine": "COVISHIELD",
      "slots": [
        "09:00AM-11:00AM",
        "11:00AM-01:00PM",
        "01:00PM-03:00PM",
        "03:00PM-05:00PM"
      ]
    }
  ]
}

It can be observed that the data we got from URL is in JSON format. We received two centers for a vaccination with the given date and pin code. So, we must work on this JSON output only and extract what we need.

Now try this out and get your hands dirty …!

Importing Libraries

import requests
import datetime
import schedule
import time
import math

Ask pin code from the user:

Also check, if the pin code is valid or not.

Python Code:

import math
while True:
    pincode = int(input())
    digits = int(math.log10(pincode))+1
    if digits==6:
        break
    else:
        print("Invalid pin..Enter again:")
        

 

Make a list of one-week dates starting from today:

theday = datetime.date.today()
start = theday - datetime.timedelta(days=0)
dates = [start + datetime.timedelta(days=d) for d in range(7)]

Now, send the get request to URL with a date and pin code. The get request returns us data in JSON format and from this data, we need to filter out what we need. Since, we are planning to make alerts for 2 age groups i.e 18 to 44, above 45. So, we will make two separate lists for these two age groups to store vaccination center details.

The vaccination centre’s details include the following information:
1.Centre name
2.Centre Address
3. Vaccine Name
4. Available quantity for dose 1
5. Available quantity for dose 2

Now add each center’s detail in the list for the two age groups separately.

Code for this:

listOfAllCentresFor45=[]
listOfAllCentresFor18=[]
for d in dates:
        d1=str(d.strftime("%d-%m-%Y"))
        url = 'https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByPin?
        pincode={0}&date={1}'.format(243001,d1)
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0)
                   Gecko/20100101 Firefox/87.0'}
        x = requests.get(url, headers=headers)
        data = x.json()
        cnt1=1
        cnt2=1
        centre_detail_1 = ""
        centre_detail_2 = ""
        centre_detail_1 = centre_detail_1 + "Date: "+ d1 + "nn" 
        centre_detail_2 = centre_detail_2 + "Date: "+ d1 + "nn"
        for d in data["sessions"]:
            if d["min_age_limit"] == 45:
                centre_detail_1 =centre_detail_1 + "Centre {0}: ".format(cnt1)+ "nCentre Adrress:" 
                + d['name'] + ", " + d["address"] + "nVaccine: " + d['vaccine'] 
                + "nAvailable Capacity dose 1: " + str(d["available_capacity_dose1"]) 
                + "nAvailable Capacity dose 2: " + str(d["available_capacity_dose2"]) + 'n'
                listOfAllCentresFor45.append(centre_detail_1)
                centre_detail_1=''
                cnt1=cnt1+1
            elif d["min_age_limit"] == 18:
                centre_detail_2 =centre_detail_2 + "Centre {0}: ".format(cnt2)+ "nCentre Adrress:" 
                + d['name'] + ", " + d["address"] + "nVaccine: " + d['vaccine'] 
                + "nAvailable Capacity dose 1: " + str(d["available_capacity_dose1"]) 
                + "nAvailable Capacity dose 2: " + str(d["available_capacity_dose2"]) + 'n' 
                listOfAllCentresFor18.append(centre_detail_2)
                centre_detail_2=''
                cnt2=cnt2+1

After this code we get two lists: listOfAllCentresFor45 and listOfAllCentresFor18. These lists have details of all the centers where a person can go for vaccination.

So, here half the path is covered.

Now, we need to send these details on telegram. So, we will use telegram bot API and create a group to send these details as messages. Refer documentation of telegram bot API to know how to get this API.

Sending a list of centers vaccinating 45+ age group people:

 

Create a message string first out of the list so that this message string can directly be passed to

URL. Now you need to provide the API_KEY and CHAT_ID which you got from the telegram bot. Replace

these two in the base_url below to complete the URL.

This is a URL for those above age >= 45:

base_url = “https://api.telegram.org/bot_YOUR-API_‘+’sendMessage?chat_id=_YOUR-CHAT-ID_&text={0}.format(messageFor45)

messageFor45 = ""
    if len(listOfAllCentresFor45) >0:
        messageFor45 = messageFor45 + "*Available  vaccination centres for 45 plus:*nn"
        for mess in  listOfAllCentresFor45:
            messageFor45 = messageFor45 + mess
            messageFor45 = messageFor45 + "n"
    else:
        messageFor45 = messageFor45 + "*No slot available for 45 and above age*"
    base_url = "https://api.telegram.org/bot_YOUR-API_'
    +'sendMessage?chat_id=_YOUR-CHAT-ID_&text={0}.format(messageFor45)
    print("Response:",requests.get(base_url))
    print("Message Sent for 45+!")

This is a URL for those age >= 18:

base_url = “https://api.telegram.org/bot_YOUR-API_‘+’sendMessage?chat_id=_YOUR-CHAT-ID_&text={0}.format(messageFor18)

messageFor18 = ""
    if len(listOfAllCentresFor18) >0:
        messageFor18 = messageFor18 + "*Available  vaccination centres for 18 and above age:*nn"
        for mess in  listOfAllCentresFor18:
            messageFor18 = messageFor18 + mess
            messageFor18 = messageFor18 + "n"
    else:
        messageFor18 = messageFor18 + "*No slot available for 18 and above age*"
    base_url = 'https://api.telegram.org/bot1845865793:AAF7slwdglakV31F5Q85JFAVf-KuyPCXIQ0/sendMessage?chat_id=-518514918&text={0}'.format(messageFor18)
    print("Response:",requests.get(base_url))
    print("Message Sent for 18+!")

Scheduling it for daily alerts three times a day:

For this we will be using schedular module of python. We will schedule the above code to run daily at a specific time.

Example: schedular.every().day().at(“10:00”).do(function_name)

So, put the above full code under a function for eg. vaccine_notifier, then schedule it for three times a day:

schedule.every().day.at("09:30").do(vaccine_notifier)
schedule.every().day.at("14:30").do(vaccine_notifier)
schedule.every().day.at("20:30").do(vaccine_notifier)
print("Execution started...")
while 1:
    schedule.run_pending()
    time.sleep(1)

That’s it! We are all set to receive notification on telegram about the available vaccination centres.

End Notes:

For full working, code refers to my Github repository here. You should try this code and get your hands dirty because you will come up with something by which you can also contribute to society by helping them.

Thanks for reading the article 🙂

 

The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion. 

Love Programming, Blog writing and Poetry

Free Courses

Responses From Readers

Clear

Raj
Raj

I keep seeing this Max retries exceeded with url: /api/v2/appointment/sessions/public/findByPin?pincode=248001&date=27-05-2021 (Caused by SSLError(SSLError(1, u'[SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590)'),)) while making the GET call in requests.

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details