Skip to content

Instantly share code, notes, and snippets.

@varun160490
Last active June 29, 2021 12:38
Show Gist options
  • Save varun160490/61f96b54a9b59f44b6e4468751faa525 to your computer and use it in GitHub Desktop.
Save varun160490/61f96b54a9b59f44b6e4468751faa525 to your computer and use it in GitHub Desktop.
Working script to book a vaccination slot on console as soon as a slot opens up in https://selfregistration.cowin.gov.in/
// This javascript code will alert you and immediately book the slot whenever a slot opens up on the given date within the given pincodes.
// **** THIS SCRIPT IS TO MAKE NEW BOOKING FOR DOSE 1 OR DOSE 2. IN CASE OF RESCHEDULE, FIRST CANCEL THE BOOKING AND THEN TRY TO BOOK USING THIS SCRIPT. ****
// **** RUN SCRIPT 5 MINUTES BEFORE THE SLOT OPENING TIME. IF THE SESSION IS EXPIRED (EXPIRES IN 10-15 MINUTES), LOG IN AND RERUN THE SCRIPT. ****
// Steps to use
// 1. Update pincodes,age,district_id,beneficiaries,dose,vaccine & vaccine_date.
// 2. Login to https://selfregistration.cowin.gov.in/
// 3. Right Click on the website
// 4. Click on Inspect
// 5. Switch to the Console Tab on the recently opened Inspect window
// 6. Copy paste the contents of this entire file - cowin_vaccination_autobooking.js
// 8. Press Enter
// 9. This will generate the captcha and show it in a new window. Note the captcha and close the window.
// 10. Within few seconds, A prompt will show on screen asking you to enter the Captcha code. Type in the Captcha as noted.
// 11. It will run every 3 seconds and check for availability of slots. Once available, it will immediately book the slot. Refresh the page once you get the booking confirmation message.
// Change the pincodes as per your city
var pincodes = [202001,202280];
// Change the age as per your requirement
var age = 18; //45,18
// Change the district id as per the city you are living in
var district_id = 623;
// Keep the vaccine as per your need. Currently it will look for both the vaccines.
var vaccines = ["COVISHIELD","COVAXIN","SPUTNIK V"];
// Enter dose = 1 for first dose, dose = 2 for second dose
var dose = 1;
// Change the date to the date of slot booking
var vaccine_date = "07-06-2021";
// Reference id of the person you are booking a slot for. Can find it written beside your name after you log in.
var beneficiaries = [66119476081580,66229455431599];
// Defined API Host endpoint
var host = "https://cdn-api.co-vin.in/api";
// Variable to keep track of whether slot is booked
var booked = false;
// Authorization token needed to book a slot - No Changes required
var authorizationToken = "Bearer " + sessionStorage.getItem("userToken").match(/"([^"]+)"/)[1];
var sleepNow = (delay) => new Promise((resolve) => setTimeout(resolve, delay))
var trialCounter = 1;
(function () {
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.async = true;
newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(newscript);
})();
function httpGet(method, theUrl, isPublic=true) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open(method, theUrl, false);
if(!isPublic)
xmlHttp.setRequestHeader("authorization", authorizationToken);
xmlHttp.send(null);
if(xmlHttp.status == 401){
alert('Your session has been expired. Please Login and rerun the script.');
location.reload();
}
return xmlHttp.responseText;
}
function getCaptcha() {
var url = host + "/v2/auth/getRecaptcha";
var data = JSON.parse(httpGet("POST", url,false)).captcha;
var myWindow = window.open("", "MsgWindow", "width=200,height=100");
myWindow.document.write(data);
}
async function fetchByDistrict(captcha) {
if (captcha.length > 0) {
console.log("Check: ", trialCounter++);
url = host + "/v2/appointment/sessions/public/calendarByDistrict?district_id=" + district_id + "&date=" + vaccine_date;
try {
centers = JSON.parse(httpGet("GET", url)).centers;
} catch (e) {
console.log("error");
}
for (i in centers) {
center = centers[i];
for (j in center.sessions) {
session = center.sessions[j];
var available_capacity = 0;
if(dose==1)
available_capacity = session.available_capacity_dose1;
else if(dose==2)
available_capacity = session.available_capacity_dose2;
if (!booked && session.min_age_limit == age && available_capacity > 0 && vaccines.includes(session.vaccine) && pincodes.includes(center.pincode) && vaccine_date == session.date) {
console.log("Vaccines available at : ", center.pincode, center.name, center.center_id, available_capacity);
data = {
center_id: center.center_id,
session_id: session.session_id,
dose: dose,
slot: session.slots[0],
beneficiaries: beneficiaries,
captcha: captcha
}
bookSlot(data);
}
}
}
if (!booked) {
await sleepNow(3000);
fetchByDistrict(captcha);
}
}
}
function bookSlot(data) {
console.log('Booking Started');
return $.ajax({
type: "POST",
url: host + "/v2/appointment/schedule",
async: false,
data: JSON.stringify(data),
timeout: 10000,
beforeSend: function (request) {
request.setRequestHeader("authorization", authorizationToken);
request.setRequestHeader("Content-Type", "application/json");
},
success: function (result) {
booked = true;
alert("Your appointment for the vaccine has been booked. \n\nAppointment No: " + result['appointment_confirmation_no']);
console.log('Booking Success');
},
error: function (error) {
console.log("BOOKING ERROR : ", error.responseText);
}
});
}
// Initiate Booking
getCaptcha();
setTimeout(function(){
fetchByDistrict(prompt("Enter Captcha Code below:"));
}, 3000);
@KeerthKumar
Copy link

There is no option to cancel the appointment even though the appointment time is passed. What to do in such case ?

@suyogp14
Copy link

suyogp14 commented May 28, 2021

@varun160490 I am also getting the same error like keshav..

polyfills-es2015.15fb4198457dfa37b8c6.js:1 Access to XMLHttpRequest at '
https://cdn-api.co-vin.in/api/v2/appointment/sessions/calendarByDistrict?district_id=392&date=29-05-2021'
from origin 'https://selfregistration.cowin.gov.in' has been blocked by
CORS policy: Response to preflight request doesn't pass access control
check: No 'Access-Control-Allow-Origin' header is present on the requested
resource.
(anonymous) @ polyfills-es2015.15fb4198457dfa37b8c6.js:1
D.s. @ polyfills-es2015.15fb4198457dfa37b8c6.js:1

@varun160490
Copy link
Author

@suyogp14, @sanjaysen83, @Keshavrko2,

I have updated the script for dose-specific. In the old script, it was trying to book for the second dose directly. Unfortunately, due to this suspicious activity, the Cowin system blocks all URLs for a few minutes. So please use the new script, and I hope it will solve the problem.

@varun160490
Copy link
Author

There is no option to cancel the appointment even though the appointment time is passed. What to do in such case ?

@KeerthKumar,
Then try to cancel it after rescheduling to a new date.

@MM1287
Copy link

MM1287 commented May 28, 2021

@KeerthKumar - if in case above option doesn't work then register beneficiaries to another mobile no.

@MM1287
Copy link

MM1287 commented May 28, 2021

@varun160490 - I have tweaked ur code for desktop alert and multiple dates.

Below is the code - ensure to grant or set access to CoWIN site for "Notification" = allow and "javascript" = allow from site settings.

// This javascript code will alert you whenever some slot opens up on the given date within the given pincodes.
// This script will run every 2 seconds and check for availability of slots.

// Steps to use
// 1. Update pincodes,age,district_id,vaccine & vaccine_date.
// 2. Login to https://selfregistration.cowin.gov.in/
// 3. Right Click on the website
// 4. Click on Inspect
// 5. Switch to the Console Tab on the recently opened Inspect window
// 6. Copy paste the contents of this entire file - cowin_vaccination.js
// 7. Press Enter

var sleepNow = (delay) => new Promise((resolve) => setTimeout(resolve, delay))
var trialCounter = 1;

// Change the pincodes as per your city
var pincodes = [411027,411017,411057,411033,411035,411044,411027,411026,411004,411007,412115];

// Change the age as per your requirement
var age = 18; //45,18

// Change the distric id as per the city you are living in
var district_id = 363;

// Change the vaccine as per your need. Check comments on how to get distric id.
//var vaccine = "COVISHIELD"; // COVISHIELD,COVAXIN

//var vaccine = "COVISHIELD,COVAXIN";
var vaccine = ["COVISHIELD", "COVAXIN","SPUTNIK V"];

// change the date to the date of slot booking
//var vaccine_date = "27-05-2021";

var dateArr = ["28-05-2021","29-05-2021"];

function showNotification(notifmsg) {
const notification = new Notification("Vaccine Availability Alert", {
body: notifmsg
})
}

function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}

async function fetchByDistrict() {
console.log("Check: ", trialCounter++);

//test notifications
//showNotification(trialCounter);

console.log(Notification.permission);
	for (k=0; k < dateArr.length; k++) {
	//url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/calendarByDistrict?district_id=" + district_id + "&date=" + dateArr[k];
	
	var vaccine_date = dateArr[k];
	
	url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/calendarByDistrict?district_id="+district_id+"&date="+vaccine_date;
	
try {
  centers = JSON.parse(httpGet(url)).centers;
} catch(e) {
  console.log("error");
	var audio = new Audio('https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3');
	audio.play();
	
	var err = "Error"
	showNotification(err);
	
}
		
for (i in centers) { 
	center = centers[i];
	 for (j in center.sessions) {
		session = center.sessions[j];
		//console.log(session);
			
		if (session.min_age_limit == age && session.available_capacity_dose1 > 0 && vaccine.includes(session.vaccine) && pincodes.includes(center.pincode)) {
			
			console.log("Vaccines available at : ", vaccine_date, center.pincode, center.name, session.available_capacity);
			
			if (Notification.permission === "granted") {
				var notif = "Date: "+ vaccine_date + " Pin: " + center.pincode + " Centre: " + center.name + " No. of Vaccines:" + session.available_capacity_dose1;
				showNotification(notif);
			} else if (Notification.permission !== "denied") {
				Notification.requestPermission().then(permission => {
				console.log(permission);
				});
			}
						
			var audio = new Audio('https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3');
			audio.play();
		}
    }	 
}
}  //end for k loop
await sleepNow(10000);
fetchByDistrict();

}

fetchByDistrict();

@sanjaysen83
Copy link

Hi varun160490

Thanks for your efforts to resolve that CORS issue but I am still seeing it unfortunately. It is not continuous but every now and then between requests it appears few times and then it starts to work again. COWIN must have some mechanism to stop requests which is suspicious and not having specific headers present with them.
2021-05-28 17_26_28-Window

KR
Sanjay

@MM1287
Copy link

MM1287 commented May 29, 2021

It happens because either sending too many request or its picking from cache.

Site allows approx 100 api hits in 5 mins or so.

If u face such issue frequently, then close entire browser, wait for some time > 5 mins, n retry.

-MM

@varun160490
Copy link
Author

Hi varun160490

Thanks for your efforts to resolve that CORS issue but I am still seeing it unfortunately. It is not continuous but every now and then between requests it appears few times and then it starts to work again. COWIN must have some mechanism to stop requests which is suspicious and not having specific headers present with them.

@sanjaysen83,
This seems to be a random error. I will check for a fix. Meanwhile, just login 5 minutes before booking; it will do the job for you.

@kaxevgg
Copy link

kaxevgg commented May 31, 2021

Hey @varun160490. I think the CORS issue can be fixed by changing xmlHttp.withCredentials to false. You can try and change the code accordingly.

@singhrajtomar
Copy link

Hi varun160490
Thanks for your efforts to resolve that CORS issue but I am still seeing it unfortunately. It is not continuous but every now and then between requests it appears few times and then it starts to work again. COWIN must have some mechanism to stop requests which is suspicious and not having specific headers present with them.

@sanjaysen83,
This seems to be a random error. I will check for a fix. Meanwhile, just login 5 minutes before booking; it will do the job for you.

Hello,
I did the same thing. Logged In 5 min before the slot opening, filled up captcha and it started. But somehow after 3 min i.e 2 min before the slot opened, I started getting the same error and was unable to book the slot. Here is the image containing details of same error.

Screenshot 2021-05-31 205642

@singhrajtomar
Copy link

Hey @varun160490. I think the CORS issue can be fixed by changing xmlHttp.withCredentials to false. You can try and change the code accordingly.

I cannot find xmlHttp.withCredentials in the code. can you help us by telling where to add?

@varun160490
Copy link
Author

@singhrajtomar, @sanjaysen83,

I have updated the code. Try now with the latest code.. so far, I didn't get any error. Let me know if you are still getting it.

Thanks, @kaxevgg, for the suggestion.

@ergauravmishra
Copy link

@varun160490 - thanks for developing this script. I've got friends and family members registered with its help, which was seeming impossible otherwise. Everytime someone books a slot using this script, you've saved a life _/_
Keep up the good work, thanks again!!

@varun160490
Copy link
Author

@varun160490 - thanks for developing this script. I've got friends and family members registered with its help, which was seeming impossible otherwise. Everytime someone books a slot using this script, you've saved a life /
Keep up the good work, thanks again!!

@ergauravmishra Thanks much buddy... :)

@dilipdhankecha
Copy link

dilipdhankecha commented Jun 1, 2021

Screenshot from 2021-06-01 17-04-38
@varun160490
When i am trying to book the slot then always after some tries i am getting an error in all check condition.
Where i made a mistake?

@Pawan446
Copy link

Pawan446 commented Jun 1, 2021

I'm getting below error when I'm trying to book
image

@riteshnarain
Copy link

riteshnarain commented Jun 3, 2021

Looks like now after 20 tries it gives HTTP 403 error. Happens exactly on 21st try and even if I change wait/sleep time to 10 seconds
I have already booked many people using this script so looks to be something new with cowin website
looks like they are logging people off after a certain number of tries

@singhrajtomar
Copy link

Looks like now after 20 tries it gives HTTP 403 error. Happens exactly on 21st try and even if I change wait/sleep time to 10 seconds
I have already booked many people using this script so looks to be something new with cowin website

Hey @varun160490,
I'm also getting the same error and exactly after 20 checks. Here is the image for your reference

Screenshot 2021-06-03 214721

@riteshnarain
Copy link

Rajtomar, that was easily handled earlier by changing sleep to 5000 ms as it would have ensured less than 100 hits in 5 mins. The new limit seems weird as it logs us out after 20 such requests irrespective of the sleep or any manual activity in portal. In fact, if you try and search manually once you get 403 error code, it will ask you to login (a refresh would still work - almost as if you have been logged off for a search operation)

@khushIdnani
Copy link

Hello Varun,
Thanks for the help, I have booked a few slots using this script it has been very helpful but,
I am also getting the same 403 error exactly after 20 tries so please can you look into the issue!
Screenshot 2021-06-04 165943

@francisbegbie
Copy link

Captcha is no longer required on CoWin.

@singhrajtomar
Copy link

Rajtomar, that was easily handled earlier by changing sleep to 5000 ms as it would have ensured less than 100 hits in 5 mins. The new limit seems weird as it logs us out after 20 such requests irrespective of the sleep or any manual activity in portal. In fact, if you try and search manually once you get 403 error code, it will ask you to login (a refresh would still work - almost as if you have been logged off for a search operation)

Yes I observed that in the console when I tried searching for slots manually. Also, If we do this activity too many times, our IP will get blocked under CORS policy. Saw the message of my IP getting blocked in console whereas the cowin website UI was constantly throwing error, "Something went wrong. Try again later".

@varun160490
Copy link
Author

@singhrajtomar, @khushIdnani, @riteshnarain, @Pawan446, @dilipdhankecha,

Yes, they are blocking the request after few seconds. I have solved the problem by using public API calls. Please use the latest code to book the slot. Let me know if you are still facing the issue.

@atul1357
Copy link

atul1357 commented Jun 7, 2021

Cowin removed captcha functionality.
will your script work now?

@varun160490
Copy link
Author

Cowin removed captcha functionality.
will your script work now?

@atul1357, Yes, it will work.

@klalj86
Copy link

klalj86 commented Jun 11, 2021

Hi Varun,
is there any way to book only free one?

@digantopaul
Copy link

digantopaul commented Jun 16, 2021

Hi Varun,
thank you for this marvelous effort you've put to help people in this time of need. Also, I really appreciate the patient support, immediate bug fixes with code updates as well as warm and courteous behavior you extended towards me while guiding me thoroughly to use these scripts. From my personal experience i completely vouch for their credibility and utility. They have proved extremely helpful in booking slot for my vaccination and all of it seemed effortless. Thanks again Varun...

@varun160490
Copy link
Author

Thank you so much @digantopaul.. :)

@varun160490
Copy link
Author

varun160490 commented Jun 20, 2021

Hi Varun,
is there any way to book only free one?

@klalj86, Not yet.. if you want you can add fee_type: "Free" in the code or only use pincodes with free one..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment