Exemplo n.º 1
0
def test_min_age_limit_filter():
    cowin = CoWinAPI()
    availability = cowin.get_availability_by_district("395", min_age_limt=18)

    assert isinstance(availability, dict)
    assert isinstance(availability.get('centers'), list)
    assert len(availability.get('centers')[0].get('sessions')) == 0
Exemplo n.º 2
0
def vaccineCheck18():
    cowin = CoWinAPI()
    counter = 0
    totalAvailable = 0
    centerName = "Null"
    availDate = "Null"
    available_centers = cowin.get_availability_by_district(district_id, date, 18)
    #print(available_centers)
    center              =   available_centers["centers"]
    for i in range(0,len(center)) :
        for j in range(0,len(center[i]['sessions'])):
            available = available_centers['centers'][i]['sessions'][j]['available_capacity'];
            #print(available)
            if available > 0 :
                print("18+")
                print("Name : ", center[i]['name'])
                print("Available slots : ", available)
                print("Date : ", available_centers['centers'][i]['sessions'][j]['date'])
                availDate = available_centers['centers'][i]['sessions'][j]['date']
                totalAvailable += available
                centerName = center[i]['name']
                counter+=1
        
    if counter == 0 :
        print("18+ Sorry No Slots Available")
    else :
        if totalAvailable > 1 :
            totalVacc = str(totalAvailable)
            data = requests.post("https://maker.ifttt.com/trigger/vAvailable/with/key/cjnKf87f12oRWfsNuDNSF0?&value1=" + availDate + "&value2=" + totalVacc + "&value3=" + centerName)
  def checkForVaccine(self):
    district_id = '725' # We can make it to pass it as parameters.
    date = '10-05-2021'  # Optional. Takes today's date by default
    min_age_limit = 18  # Optional. By default returns centers without filtering by min_age_limit

    cowin = CoWinAPI()
    available_centers = cowin.get_availability_by_district(district_id, date, min_age_limit)
    
    # print(json.dumps(available_centers))
    #print(available_centers)
    #print(available_centers["centers"][0]["name"])
    #print(len(available_centers["centers"]))
    # print(len(available_centers["centers"][0]["sessions"]))
    # print(available_centers["centers"][0]["sessions"][3]["date"])
    # available_centers["centers"][0]["sessions"][1]["available_capacity"] = 1
    
    for i in range(len(available_centers["centers"])):
      print(available_centers["centers"][i]["name"]) # Prints the name of the hospital
      for j in range(len(available_centers["centers"][i]["sessions"])):
        print('\t',available_centers["centers"][i]["sessions"][j]["date"]) #Prints the date
        print('\t',available_centers["centers"][i]["sessions"][j]["available_capacity"],'\n') #Prints the quantity available
        available_capacity = available_centers["centers"][i]["sessions"][j]["available_capacity"] # assigning it to variable, it's too lang!

        if(available_capacity > 0):
          try:
            response = self.notifyUsers()
          except Exception as err:
            print(f'Some error while notifying users: {err}')
Exemplo n.º 4
0
def vaccineCheckV18():
    cowin = CoWinAPI()
    counter = 0
    available_centers = cowin.get_availability_by_district(district_id, date, 18)
    center              =   available_centers["centers"]
    for i in range(0,len(center)) :
        for j in range(0,len(center[i]['sessions'])):
            available = available_centers['centers'][i]['sessions'][j]['available_capacity'];
            #print(available)
            if available > 0 :
                print("18+")
                print("Name : ", center[i]['name'])
                print("Available slots : ", available)
                print("Date : ", available_centers['centers'][i]['sessions'][j]['date'])
                #speaker.say('18+ Hey !')
                speaker.say(available)
                speaker.say('Slots available at')
                speaker.say(center[i]['name'])
                #speaker.say('on')
                #speaker.say(available_centers['centers'][i]['sessions'][j]['date'])
                speaker.runAndWait()
                counter+=1
        
    if counter == 0 :
        speaker.say('18+ Sorry No Slots Available')
        speaker.runAndWait()
        print("18+ Sorry No Slots Available")
Exemplo n.º 5
0
def get_availability(
        date,
        min_age=18,
        state="Bihar",
        districts=["Patna", "Muzaffarpur", "Vaishali"],
        blocks=["Saraiya", "Vaishali", "Paroo", 'Lalganj', 'Marwan']):
    cowin = CoWinAPI()
    data = pd.DataFrame([])
    for district in districts:
        dist = get_district_id(state.lower(), district.lower())
        avail = cowin.get_availability_by_district(dist, date, min_age)
        data1 = createDf(avail["centers"])
        data = pd.concat([data, data1])

    vac = pd.DataFrame([])
    for block in blocks:
        vac1 = data[data["block_name"] == block]
        vac = pd.concat([vac, vac1])
    vac = vac.reset_index().drop(["index"], axis=1)

    columns = [
        'date', 'vaccine', 'available_capacity', 'name', 'min_age_limit'
    ]
    vac = vac[columns]
    return vac
Exemplo n.º 6
0
def test_fees_filter():
    cowin = CoWinAPI()
    availability = cowin.get_availability_by_district("395",
                                                      date="03-05-2021",
                                                      fees=Fees.PAID)

    assert isinstance(availability, dict)
    assert isinstance(availability.get('centers'), list)
Exemplo n.º 7
0
def test_dose_filter():
    cowin = CoWinAPI()
    availability = cowin.get_availability_by_district("395",
                                                      date="03-05-2021",
                                                      dose=Dose.FIRST)

    assert isinstance(availability, dict)
    assert isinstance(availability.get('centers'), list)
Exemplo n.º 8
0
def test_vaccine_filter():
    cowin = CoWinAPI()
    availability = cowin.get_availability_by_district("395",
                                                      date="03-05-2021",
                                                      vaccine=Vaccine.COVAXIN)

    assert isinstance(availability, dict)
    assert isinstance(availability.get('centers'), list)
Exemplo n.º 9
0
def test_min_age_limit_filter():
    cowin = CoWinAPI()
    availability = cowin.get_availability_by_district("395",
                                                      date="03-05-2021",
                                                      min_age_limt=18)

    assert isinstance(availability, dict)
    assert isinstance(availability.get('centers'), list)
Exemplo n.º 10
0
def get_availability():
    cowin = CoWinAPI()
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    available_centers = cowin.get_availability_by_district(district_id, date, min_age_limit)
    for i in available_centers['centers']:
        for x in i['sessions']:
            if x['available_capacity'] > 0:
                print(i['name'], "\t", i['pincode'], "\t", x['available_capacity'], current_time)
Exemplo n.º 11
0
def get_district_id(state, district):
    cowin = CoWinAPI()
    states = cowin.get_states()
    state = [i for i in states["states"] if state in i["state_name"].lower()]

    districts = cowin.get_districts(state[0]["state_id"])
    district = [
        i for i in districts["districts"]
        if district in i["district_name"].lower()
    ]

    district_id = str(district[0]["district_id"])
    return district_id
def notify_for_vaccine():
	## Email object----------------------------------------------
	smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465)
	smtpObj.login('sender_email_id', 'password') #Put your own SMTP server Credentials
	##-----------------------------------------------------------

	## Cowin Results
	state_id = '26' #Put your state ID
	district_id = '446' #Put your disctrict ID
	date = datetime.today().strftime("%d-%m-%Y")
	min_age_limit = 18 #Put the age limit you want to register

	available_centers_data = []
	availability = 0
	cowin = CoWinAPI()

	available_centers = cowin.get_availability_by_district(district_id,date,min_age_limit)
	print("Checking centers for vaccination..........")

	for center in available_centers['centers']:
		_date_capacity = 0
		available_sessions = []

		for session in center['sessions']:
			if(session['available_capacity'] > 10): #decide availability threshold
				_date_capacity = 1
				availability = 1
				available_sessions.append(session)
		if(_date_capacity):
			center['sessions'] = available_sessions
			available_centers_data.append(center)
	## Cowin results End

	## Sending Email
	if availability == 1:
		print(json.dumps(available_centers_data))
		smtpObj.sendmail(' SMTP Sender Email ID ',
		 '*****@*****.**', #put recepient Email ID
		 'Subject: Covid Test Center Available!\nDear User,\
		 \n\nPlease checkout the data below for information on vaccine centers\n\n.'+
		 json.dumps(available_centers_data,indent=4)+'\n\n-----END-----')
	## -------------

	smtpObj.quit()
Exemplo n.º 13
0
def test_get_availability_by_district():
    cowin = CoWinAPI()
    availability = cowin.get_availability_by_district("395")

    assert isinstance(availability, dict)
    assert isinstance(availability.get('centers'), list)
Exemplo n.º 14
0
def test_get_districts():
    cowin = CoWinAPI()
    districts = cowin.get_districts("21")

    assert isinstance(districts, dict)
    assert districts.get('districts')[0].get('district_id') == 391
Exemplo n.º 15
0
from cowin_api import CoWinAPI

pin_code = "560035"
date = '11-05-2021'  # Optional. Default value is today's date
min_age_limit = 45  # Optional. By default returns centers without filtering by min_age_limit

cowin = CoWinAPI()
available_centers = cowin.get_availability_by_pincode(pin_code, date,
                                                      min_age_limit)
print(available_centers)
# Just Change these values
no_of_days = 28  # Change this to 7,14,21 or 28
pincodes = ['141001',
            '141002']  # Add as many pincodes as you want separated by commas
min_age_limit = 18  # Change this to 18 if you want 18+

BASE_DATE = datetime.datetime.now()
DATE_LIST = date_list = [
    BASE_DATE + datetime.timedelta(days=x * 7)
    for x in range(int(no_of_days / 7))
]

dates = [date.strftime("%d-%m-%Y") for date in date_list]

# Start the API
cowin = CoWinAPI()

# Logging stuff
MY_PATH = os.getcwd()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler(
    f'{os.path.join(MY_PATH, "cowin_email_alerts.log")}')
fmt = logging.Formatter('%(levelname)s : %(name)s : %(asctime)s : %(message)s')
file_handler.setFormatter(fmt)
logger.addHandler(file_handler)


def send_email(text_file: str):
    """ This function sends the email if the Vaccination slot is available
Exemplo n.º 17
0
def test_get_availability_by_pincode():
    cowin = CoWinAPI()
    availability = cowin.get_availability_by_pincode("400080")

    assert isinstance(availability, dict)
    assert isinstance(availability.get('centers'), list)
Exemplo n.º 18
0
def test_get_states():
    cowin = CoWinAPI()
    states = cowin.get_states()

    assert isinstance(states, dict)
    assert states.get('states')[0].get('state_id') == 1
Exemplo n.º 19
0
        session.ehlo()
        session.starttls()
        session.ehlo()

        # Login to Gmail
        session.login(GMAIL_USERNAME, GMAIL_PASSWORD)

        # Send Email & Exit
        session.sendmail(GMAIL_USERNAME, recipient,
                         headers + "\r\n\r\n" + content)
        session.quit()


sender = Emailer()

cowin = CoWinAPI()

while True:
    try:
        start_dates = [
            datetime.now() + timedelta(days=i * 7) for i in range(WEEKS)
        ]
        dates = [start_date.strftime('%d-%m-%Y') for start_date in start_dates]

        for district in DISTRICTS:
            for date in dates:
                print("Fetching for date:", date, "district:", district)
                available_centers = cowin.get_availability_by_district(
                    district, date, AGE_LIMIT)

                for center in available_centers['centers']:
Exemplo n.º 20
0
from cowin_api import CoWinAPI

cowin = CoWinAPI()

states = cowin.get_states()
print(states)

# get the state id from above add it here
state_id = '12'
cowin = CoWinAPI()
districts = cowin.get_districts(state_id)
print(districts)
Exemplo n.º 21
0
    # Authentication
    s.login("senderEmailId", "senderEmailPassword")

    # message to be sent
    message = " ".join(slots)

    # sending the mail ( you can email to multiple people)
    s.sendmail("senderEmailId", ["receiverNo1EMailId", "receieveNo2MailId"],
               message)

    # terminating the session
    s.quit()


cowin = CoWinAPI()
while (1):
    #Get the disctrict Id using states.py, eg: chandigarh - 108
    #Chandigarh
    fillslotsForGivenCenter(
        cowin.get_availability_by_district('108', date,
                                           min_age_limit).get('centers'))
    #Mohali
    fillslotsForGivenCenter(
        cowin.get_availability_by_district('496', date,
                                           min_age_limit).get('centers'))

    now = datetime.datetime.now()

    print(slots)
Exemplo n.º 22
0
from cowin_api import CoWinAPI
import datetime
import subprocess
district_id = '303'
cowin = CoWinAPI()
x = datetime.datetime.now()
date = str(x.strftime("%d-%m-%Y"))
#print(date)
min_age_limit = 18  # Optional. By default returns centers without filtering by min_age_l
flag = 0

for j in range(5):
    x = datetime.datetime.now() + datetime.timedelta(days=j)
    date = str(x.strftime("%d-%m-%Y"))
    print(' [ + ] Date: '+date)
    available_centers = cowin.get_availability_by_district(district_id, date, min_age_limit)
    #print(available_centers['centers'])
    #flag = 0
    for i in available_centers['centers']:
        if (i.get('sessions')[0].get('available_capacity_dose1') > 0):
            flag = 1
        print(' Hospital: ' + i.get('name') + ' pincode: ' + str(i.get('pincode')) + '\n\t Minimmum age limit = ' + str(i.get('sessions')[0].get('min_age_limit')) + '\n\t vaccine name: '+ str(i.get(
'sessions')[0].get('vaccine')) + '\n\t Dose1 left: ' + str(i.get('sessions')[0].get('available_capacity_dose1')) + '\n\t Dose2 left: ' + str(i.get('sessions')[0].get('available_capacity_dose2'))
)


#if(flag == 1):
#    subprocess.run(['notify-send', 'slots empty!! Go get it!'])
Exemplo n.º 23
0
from cowin_api import CoWinAPI
cowin = CoWinAPI()

stats = cowin.get_states()
print(stats)