-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschedule_slot.py
632 lines (530 loc) Β· 36.2 KB
/
schedule_slot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
from typing import Counter
from fake_useragent import UserAgent
from bs4 import BeautifulSoup
import datetime
import requests
import hashlib
import base64
import time
import json
import re
import winsound
import threading
def line_break(): print("*"*55)
class CoWinBook():
def __init__(self):
try:
a = open("appsettings.json")
except FileNotFoundError:
self.collectDataFromCMD()
else:
i = input("Do you want to load last settings? y/n: ")
if i.lower()== "y":
self.setVarFromJSON()
else:
self.collectDataFromCMD()
# Collect data from cmd
def collectDataFromCMD(self):
self.mobile_no = self.collectMobile()
# Request Session
self.session = requests.Session()
# intializing session
self.getSession()
self.user_id = self.select_beneficiaries() # Selected Users for Vaccination
self.pincodes = self.collectPin()
self.center_id = [] # Selected Vaccination Centers
# Vaccination Center id and Session id for Slot Booking
self.vacc_center = None
self.vacc_session = None
self.slot_time = None
self.center_name = None
self.appointmentID = None
# Dose 1 or Dose 2
self.dose = self.collectDose()
self.vaccine_name = self.collectVaccineName()
# OTP Fetching method
self.otp = None
# User Age 18 or 45
self.age = self.collectAge()
print(f"You fall in cat: {self.age}+")
# Data for sending request
self.data = {}
# Token Recieved from CoWIN
self.bearerToken = None # Session Token
self.sleepinterval = self.collectSleep()
self.vaccinetype = self.collectVaccineType()
self.date = self.collectDate()
# Login and Save Token in file( filename same as mobile no)
# self.select_beneficiaries()
self.writeJSON()
# Start Looping the booking process
self.booked = False
while self.booked==False:
self.request_slot(data)
# validate and write collected data into JSON file
def writeJSON(self):
global data
data = {
"BeneficiaryIds": self.user_id,
"mobile":self.mobile_no,
"age":self.age,
"SleepIntervalInSeconds":self.sleepinterval,
"MinimumVaccineAvailability":len(self.user_id),
"DoseType":self.dose,
"VaccineFeeType": self.vaccinetype,
"VaccineName": self.vaccine_name,
"VaccinationCentreName": "",
"PINCodes": self.pincodes,
"DateToSearch": self.date,
"DaysToSearchFurther":4
}
with open("appsettings.json","w") as f:
json.dump(data,f)
# Collect Vaccine Center Name
def collectCenterName(self):
a = input("Enter center name(Press")
# Collect Vaccine Name
def collectVaccineName(self):
print("1: Enter 1 for COVISHIELD\n2: Enter 2 for COVAXIN\n3: Enter 3 for SPUTNIK V")
t = input("Enter your response(press enter to skip): ")
if t=='1' or t=='2' or t=='3':
if t =='1':
return 'COVISHIELD'
if t=='2':
return 'COVAXIN'
if t=='3':
return 'SPUTNIK V'
else:
return ''
# collect date
def collectDate(self):
while True:
d = input("Enter date to search in dd-mm-yyyy format: ")
d1 = d.split('-')
if d1[0].isnumeric and d1[1].isnumeric and d1[2].isnumeric and 0<int(d1[0])<32 and 0<int(d1[1])<13 and len(d1[2])==4:
return datetime.datetime(day=int(d1[0]), month=int(d1[1]),year=int(d1[2])).strftime("%d-%m-%Y")
else:
print("Invalid Date. Please try again..")
# Collect vaccine type
def collectVaccineType(self):
print("1: Enter 1 for free\n2: Enter 2 for paid")
t = input("Enter your response(press enter to skip): ")
if t=='1' or t=='2':
if t =='1':
return 'Free'
if t=='2':
return 'Paid'
else:
return 'Free'
# collect sleep interval
def collectSleep(self):
i = input("Enter sleep time after a reqest(press enter to skip): ")
if i.isnumeric() and int(i)>20:
return int(i)
else:
return 20
# Collect Mobile No
def collectMobile(self):
while True:
m = input("Enter your mobile no: ")
if len(m)==10 and m.isnumeric():
return m
else:
print("Invalid input. Please Try Again......\n")
# Collect age from user
def collectAge(self):
age= int(input("Enter your age: "))
if age<18:
print("You are not eligible for vaccination")
elif age>= 18:
return 18 if age < 45 else 45
else:
print("Invalid input")
# Collect dose from user
def collectDose(self):
while True:
dose = int(input("\nSelect dose type:\n1. Enter 1 for dose-1\n2. Enter 2 for dose-2\nEnter your response here: "))
if dose == 1 or dose == 2:
print("you have selected dose-", dose)
return dose
else:
print("Invalid input")
continue
# Collect pincodes from user
def collectPin(self):
pincode_list= []
while True:
pin = input("\nEnter a pincode: ")
if len(pin)==6:
pincode_list.append(pin)
i = input("Enter 'y' to add more pincodes or press enter to continue: ")
if i.lower()=='y':
print(pincode_list)
continue
else:
print("\nSelected Pincodes are:", pincode_list)
return pincode_list
else:
print("invalid input")
# Validate pin codes
def validatePinCode(self, pin_codes_list):
for pin in pin_codes_list:
if len(pin)!=6:
return False
return True
def setVarFromJSON(self):
# checking json data
def checkData(data):
if data["BeneficiaryIds"]==[] or data["BeneficiaryIds"]==None:
raise Exception("Error in Settings: Beneficiary ID should not be blank")
elif data["mobile"]== "" or data["mobile"]==None:
raise Exception("Error in Settings: Mobile number Should not left blank")
elif len(data["mobile"])!=10:
raise Exception("Error in Settings: Invalid mobile number")
elif data["age"]=="" or data["age"]==None:
raise Exception("Error in Settings: Please define age")
elif data["age"]<18:
raise Exception("Error in Settings: This age is not eligible for vaccination")
elif data["SleepIntervalInSeconds"]==None or data["SleepIntervalInSeconds"]=="":
raise Exception("Error in Settings: Please define sleep interval")
elif data["MinimumVaccineAvailability"]==None or data["MinimumVaccineAvailability"]=="":
raise Exception("Error in Settings: Please define MinimumVaccineAvailability")
elif data["DoseType"] != 1 and data["DoseType"]!= 2:
raise Exception("Error in Settings: Invalid dose type")
elif data["VaccineFeeType"]=='free' or data["VaccineFeeType"]=='paid':
raise Exception("Error in Settings: Invalid vaccine type")
elif not self.validatePinCode(data["PINCodes"]):
raise Exception("Error in Settings: Please define dose type")
# Opening JSON file
try:
with open("appsettings.json") as f:
data = json.load(f)
checkData(data)
except Exception as e:
print(e)
self.mobile_no = str(data["mobile"])
self.pincodes = data["PINCodes"] # Area Pincode
self.center_id = [] # Selected Vaccination Centers
self.user_id = data["BeneficiaryIds"] # Selected Users for Vaccination
self.vaccine_name = data["VaccineName"]
# Vaccination Center id and Session id for Slot Booking
self.vacc_center = None
self.vacc_session = None
self.slot_time = None
self.center_name = None
self.appointmentID = None
# Dose 1 or Dose 2 ( default : 1)
self.dose = data["DoseType"]
# OTP Fetching method
self.otp = None
# User Age 18 or 45
self.age = 18 if int(data["age"]) < 45 else 45
# print(self.age)
# Request Session
self.session = requests.Session()
# Data for sending request
self.data = {}
# Token Recieved from CoWIN
self.bearerToken = None # Session Token
# Login and Save Token in file( filename same as mobile no)
self.getSession()
# self.select_beneficiaries()
# Start Looping the booking process
self.booked = False
while self.booked==False:
self.request_slot(data)
# select Beneficiary
def select_beneficiaries(self):
response = self.session.get('https://cdn-api.co-vin.in/api/v2/appointment/beneficiaries').json()
USERS = []
index = []
selected_user_ID = set()
selected_users = set()
if not response.get('beneficiaries',[]):
print("No user added in beneficiaries. Please visit cowin and register a member to continue.\n Exiting software.............")
exit()
# print(json.dumps(response, indent=3))
counter = 1
for user in response.get('beneficiaries'):
user_dict = {}
user_name = user.get("name")
reference_id = user.get("beneficiary_reference_id")
user_dict["index"] = counter
user_dict["user_name"] = user_name
user_dict["reference_ID"] = reference_id
USERS.append(user_dict)
index.append(counter)
counter+=1
isNotSelected = True
line_break()
print("Please select beneficiaries from below:\n")
while isNotSelected:
for data in USERS:
print(f"{data['index']}: Press {data['index']} to Select {data['user_name']} ")
selection = input("\n Enter Your response: ")
if int(selection) in index:
for data in USERS:
if int(selection)== data['index']:
selected_user_ID.add(data['reference_ID'])
selected_users.add(data['user_name'])
else:
i = input("Do you want to add more? Enter 'y' or press enter to continue: ")
if i.lower()=="y":
continue
else:
print("you have selected", selected_users)
isNotSelected = False
else:
print("Invalid Selection\n")
return list(selected_user_ID)
# Set Header in self.session = requests.Session()
def set_headers(self):
ua = UserAgent()
self.session.headers.update({
'User-Agent': ua.random,
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'en-US,en;q=0.5',
'Content-Type': 'application/json',
'Origin': 'https://selfregistration.cowin.gov.in',
'Connection': 'keep-alive',
'Referer': 'https://selfregistration.cowin.gov.in/',
'TE': 'Trailers',
})
# returning self.data
def get_data(self):
return json.dumps(self.data).encode('utf-8')
# Save Token after login to CoWIN
def putSession(self):
with open(f"{self.mobile_no}.log", "w") as f:
f.write(self.bearerToken)
# Get Token saved in file for relogin and use
def getSession(self):
self.set_headers()
try:
with open(f"{self.mobile_no}.log", "r") as f:
self.bearerToken = f.read()
self.session.headers.update({
'Authorization': 'Bearer {}'.format(self.bearerToken)
})
self.session.get('https://cdn-api.co-vin.in/api/v2/appointment/beneficiaries').json()
except (FileNotFoundError,json.decoder.JSONDecodeError):
self.login_cowin()
# Login to selfregistration.cowin.gov.in/
def login_cowin(self):
self.data = {
"secret":"U2FsdGVkX1+gGN13ULaCVtLSWmsyZwAdXXTIAvLQp2HOXrIBCcq0yyOZQqzzfiFiEYs7KoAOTK2j4qPF/sEVww==",
"mobile": self.mobile_no
}
response = self.session.post('https://cdn-api.co-vin.in/api/v2/auth/generateMobileOTP',data=self.get_data())
otpSha265 = self.get_otp()
txn_id = response.json()['txnId']
self.data = {
"otp":otpSha265,
"txnId": txn_id
}
response = self.session.post('https://cdn-api.co-vin.in/api/v2/auth/validateMobileOtp',data=self.get_data())
self.bearerToken = response.json()['token']
self.session.headers.update({
'Authorization': 'Bearer {}'.format(self.bearerToken)
})
self.putSession()
# Request for OTP
def get_otp(self):
def play():
for i in range(10):
winsound.Beep(500,200)
a= threading.Thread(target=play)
a.start()
print(f"Otp sent to your mobile phone {self.mobile_no}")
otp = input("\nEnter OTP : ")
return hashlib.sha256(otp.encode('utf-8')).hexdigest()
# Request for Current Slot Deatails ( Private Request )
def request_slot(self, data):
# def extractDate(date):
# temp = date.split("-")
# return datetime.datetime(day=int(temp[0]), month=int(temp[1]), year=int(temp[2]))
# base = extractDate(data["DateToSearch"])
# date_list = [base + datetime.timedelta(days=x) for x in range(int(data["DaysToSearchFurther"]))]
# date_str = [x.strftime("%d-%m-%Y") for x in date_list]
for pincode in self.pincodes:
line_break()
print(f"Searching for PinCode- {pincode}")
response = self.session.get(f'https://cdn-api.co-vin.in/api/v2/appointment/sessions/calendarByPin?pincode={pincode}&date={data["DateToSearch"]}')
if response.ok:
try:
# print(response.json())
if self.check_slot(response.json(),data=data, pincode=pincode):
self.booked = True
return True
else:
continue
except:
print("Request Error. Too much requests.")
break
elif response.status_code == 401:
print("Re-login Account : " + datetime.datetime.now().strftime("%H:%M:%S") + " π€³")
self.login_cowin()
self.request_slot(data)
else:
print("Error Fetching slot:")
print(f"resp_Code = {response.status_code} and MSG:{response.json()}")
line_break()
print("Last Checked β
: " + datetime.datetime.now().strftime("%H:%M:%S") + " π")
time.sleep(int(data["SleepIntervalInSeconds"]))
# When last Checked
# Check Slot availability
def check_slot(self,response, data, pincode):
for center in response.get('centers',[]):
if center ==[]:
print(f"[Warning] No Centers found at pincode-{pincode}")
else:
for session in center.get('sessions',[]):
self.vacc_center = center.get('center_id')
self.vacc_session = session.get("session_id")
self.center_name = center.get('name')
slot_times = session.get('slots')
slot_times.reverse() # reversing the slot list so booking chances will be higher
for slot in slot_times:
self.slot_time = slot# glitch[0] was default
# self.slot_time = session.get('slots')[1]# glitch[0] was default
center_pin = center.get('pincode')
capacity = session.get(f'available_capacity_dose{data["DoseType"]}')
session_date = session.get('date')
vaccine_name = session.get('vaccine')
vaccine_type = center.get('fee_type')
# Check with center name
if data["VaccinationCentreName"] != "":
if data["VaccineName"] != "":
if int(session.get('min_age_limit')) == self.age and data["VaccineFeeType"]==vaccine_type and data["VaccineName"]== vaccine_name and (data["VaccinationCentreName"]).lower() in self.center_name.lower():
if capacity >= int(data["MinimumVaccineAvailability"]):
MSG = f'π {capacity} {vaccine_name} / {session_date} / {self.center_name} π{center_pin}'
print("Hurry Centers Available\n",MSG)
BOOKED = self.book_slot()
if BOOKED:
print("Shutting Down CoWin Script π©βπ» ")
return True
else:
print(f"[info] Sorry {capacity} Vaccine Found found at {self.center_name} on {session_date}.")
else:
continue
elif int(session.get('min_age_limit')) == self.age and data["VaccineFeeType"]==vaccine_type and (data["VaccinationCentreName"]).lower() in self.center_name.lower():
if capacity >= int(data["MinimumVaccineAvailability"]):
MSG = f'π {capacity} {vaccine_name} / {session_date} / {self.center_name} π{center_pin}'
print("Hurry Centers Available\n",MSG)
BOOKED = self.book_slot()
if BOOKED:
print("Shutting Down CoWin Script π©βπ» ")
return True
else:
print(f"[info] Sorry {capacity} Vaccine Found found at {self.center_name} on {session_date}.")
# Check With Vaccine name
elif data["VaccineName"] != "":
if int(session.get('min_age_limit')) == self.age and data["VaccineFeeType"]==vaccine_type and data["VaccineName"]== vaccine_name:
if capacity >= int(data["MinimumVaccineAvailability"]):
MSG = f'π {capacity} {vaccine_name} / {session_date} / {self.center_name} π{center_pin}'
print("Hurry Centers Available\n",MSG)
BOOKED = self.book_slot()
if BOOKED:
print("Shutting Down CoWin Script π©βπ» ")
return True
else:
print(f"[info] Sorry {capacity} Vaccine Found found at {self.center_name} on {session_date}.")
else:
continue
# Check With capacity
elif int(session.get('min_age_limit')) == self.age and data["VaccineFeeType"]==vaccine_type:
if capacity >= int(data["MinimumVaccineAvailability"]):
MSG = f'π {capacity} {vaccine_name} / {session_date} / {self.center_name} π{center_pin}'
print("Hurry Centers Available\n",MSG)
BOOKED = self.book_slot()
if BOOKED:
print("Shutting Down CoWin Script π©βπ» ")
return True
else:
print(f"[info] Sorry {capacity} Vaccine Found found at {self.center_name} on {session_date}.")
else:
continue
else:
print("[Warning!] No vaccine slot found as per your search! Try changing search criteria.")
return False
# Get Solved Captcha in String
def get_captcha(self):
model = "eyJNTExRTExRTExRTExMUUxMUUxMUVpNTExRTExRTExRTExRTExRTExRTExRWk1MTFFMTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRWk1MTFFMTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRWk1MTFFMTExRTExRWk1MTFFMTFFMTFFMTFFaIjogIjAiLCAiTUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUVpNTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTFoiOiAiMSIsICJNTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExMUUxMUUxMUUxMUUxMUUxMUUxMUVpNTExRTExMUUxMUUxMUUxMUUxMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTExRTExRTExRTExRTExRTExMUUxMTFFMTFFaIjogIjIiLCAiTUxMUUxMUUxMUUxMUUxMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRWk1MTFFMTFFMTFFMTFFMTFFMTExMUUxMUUxMUUxMUUxMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTExMUUxMUUxMUUxMUUxMUUxMUUxMTExRTExRTExRTExRTExRTExRTExMTExMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUVoiOiAiMyIsICJNTExRTExRTExRTExRWk1MTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTExRTExRTExRTExRWk1MTFFMTExRTExRTExRTExRTExRTExRTExMUUxMTFFMTExRTExRTExRTExRTExRTExRTExRTExMUUxMUUxMUUxMUVpNTExRTExRTExRTExRTExRWiI6ICI0IiwgIk1MTFFMTFFMTFFMTFFMTFFMTFFMTFFMTExMUUxMUUxMUUxMUUxMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFaTUxMUUxMUUxMUUxMUUxMTExMUUxMTFFMTExRTExRTExRTExMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMTExRTExRTExRTExRTExRWiI6ICI1IiwgIk1MTFFMTFFMTFFMTFFMTFFMTF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FMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTExRTExRTExRWk1MTFFMTFFMTFFMTFFMTExRTExRTExRTExRTExRTExRTExRTExMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTExRTExRTExRTExRTExRTExRTExRTExRTExMUUxMWiI6ICJHIiwgIk1MTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRWk1MTFFMTFFMTFFMTFFMTFFMTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRWiI6ICJIIiwgIk1MTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFaTUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUVoiOiAibCIsICJNTExMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUVpNTExMTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRWiI6ICJKIiwgIk1MTFFMTFFMTFFMTExRTExRTExRTExRTExRTExRTExMUUxMUUxMUUxMTExMUVpNTExRTExRTExRTExMUUxMUUxMTFFMTFFMTFFMTFFMTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRWiI6ICJLIiwgIk1MTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFaTUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUVoiOiAiTCIsICJNTExRTExMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUVpNTExRTExRTExRTExRTExRTExMUUxMUUxMUUxMUUxMUUxMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMT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TExMUVoiOiAidiIsICJNTExRTExMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMTFFMTFFMTFFMTFFMTFFMTExRWk1MTFFMTFFMTFFMTFFMTFFMTExRTExRTExRTExRTExMUUxMTFFMTFFMTFFMTExRTExRTExRTExRTExRTExRTExMUUxMUUxMUUxMUUxMWiI6ICJ3IiwgIk1MTFFMTFFMTFFMTExRTExRTExRTExRTExRTExRTExRTExRTExRWk1MTFFMTFFMTFFMTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExMUUxMUUxMUUxMUUxMUUxMTFFaIjogIngiLCAiTUxMUUxMUUxMUUxMUUxMUUxMUUxMUUxMTFFMTFFaTUxMUUxMTFFMTFFMTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExMUUxMUVoiOiAieSIsICJNTExRTExRTExRTExRTExRTExRTExRTExMUUxMUUxMUUxMUUxMUUxMUVpNTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExRTExMUUxMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFMTFFaIjogInoifQ=="
# Send request for Captcha
data = '{}'
response = self.session.post('https://cdn-api.co-vin.in/api/v2/auth/getRecaptcha', data=data)
if not response.ok:
self.login_cowin()
return self.get_captcha()
# Get Captcha Data from Json
svg_data = response.json()['captcha']
soup = BeautifulSoup(svg_data,'html.parser')
model = json.loads(base64.b64decode(model.encode('ascii')))
CAPTCHA = {}
for path in soup.find_all('path',{'fill' : re.compile("#")}):
ENCODED_STRING = path.get('d').upper()
INDEX = re.findall('M(\d+)',ENCODED_STRING)[0]
ENCODED_STRING = re.findall("([A-Z])", ENCODED_STRING)
ENCODED_STRING = "".join(ENCODED_STRING)
CAPTCHA[int(INDEX)] = model.get(ENCODED_STRING)
CAPTCHA = sorted(CAPTCHA.items())
CAPTCHA_STRING = ''
for char in CAPTCHA:
CAPTCHA_STRING += char[1]
return CAPTCHA_STRING
# Print Slip
def downloadBookings(self):
try:
response = self.session.get(f'https://cdn-api.co-vin.in/api/v2/appointment/appointmentslip/download?appointment_id={self.appointmentID}')
status = response.status_code
if status == 200:
with open(f"{self.mobile_no}_appointment_slip_{self.appointmentID[:10]}.pdf", "wb") as f:
f.write(response.content)
elif status == 400:
print("Unable to Print. Please download manually")
print(f'{status} : {response.json()}')
else:
print("Unable to Print. Please download manually")
print(f'{status} : {response.json()}')
except:
print("Unable to Print. Please download manually")
# Book Slot for Vaccination
def book_slot(self):
captcha = self.get_captcha()
self.data = {
"center_id":self.vacc_center ,
"session_id":self.vacc_session,
"beneficiaries":self.user_id,
"slot":self.slot_time,
"captcha": captcha,
"dose": self.dose
}
response = self.session.post('https://cdn-api.co-vin.in/api/v2/appointment/schedule',data=self.get_data())
status = response.status_code
if status == 200:
line_break()
print(f"π₯ Appointment scheduled successfully!!π₯³ at-{self.center_name} on slot - {self.slot_time}\n")
res = response.json()
result = res.get("appointment_confirmation_no")
self.appointmentID = result
print(f"Your Appointment ID is {result}")
line_break()
with open(f"{self.mobile_no}_Booking_ID.txt","a") as f:
f.write(f"\nYour Appointment ID is {result} booked on {datetime.datetime.now()}")
self.downloadBookings()
return True
elif status == 409:
print("This vaccination center is completely booked for the selected date π₯")
return False
elif status == 401:
self.login_cowin()
self.book_slot()
else:
print("Error in Booking Slot")
print(f'{status} : {response.json()}')
return False
if __name__ == '__main__':
line_break()
print("Welcome to CoWin Auto Slot Booking.....")
line_break()
cowin = CoWinBook()