Skip to content

Instantly share code, notes, and snippets.

@abir-taheer
Last active May 9, 2024 09:19
Show Gist options
  • Save abir-taheer/0d3f1313def5eec6b78399c0fb69e4b1 to your computer and use it in GitHub Desktop.
Save abir-taheer/0d3f1313def5eec6b78399c0fb69e4b1 to your computer and use it in GitHub Desktop.
"This is our community, this is our family, these are our friends." https://www.youtube.com/watch?v=gk7iWgCk14U&t=425s
if (window.location.origin !== "https://www.instagram.com") {
window.alert(
"Hey! You need to be on the instagram site before you run the code. I'm taking you there now but you're going to have to run the code into the console again.",
);
window.location.href = "https://www.instagram.com";
console.clear();
}
const fetchOptions = {
credentials: "include",
headers: {
"X-IG-App-ID": "936619743392459",
},
method: "GET",
};
let username;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const random = (min, max) => Math.floor(Math.random() * (max - min)) + min;
// This function handles all of the pagination logic
// Calls the API recursively until there are no more pages to load
const concatFriendshipsApiResponse = async (
list,
user_id,
count,
next_max_id = "",
) => {
let url = `https://www.instagram.com/api/v1/friendships/${user_id}/${list}/?count=${count}`;
if (next_max_id) {
url += `&max_id=${next_max_id}`;
}
const data = await fetch(url, fetchOptions).then((r) => r.json());
if (data.next_max_id) {
const timeToSleep = random(800, 1500);
console.log(
`Loaded ${data.users.length} ${list}. Sleeping ${timeToSleep}ms to avoid rate limiting`,
);
await sleep(timeToSleep);
return data.users.concat(
await concatFriendshipsApiResponse(
list,
user_id,
count,
data.next_max_id,
),
);
}
return data.users;
};
// helper methods to make the code a bit more readable
const getFollowers = (user_id, count = 50, next_max_id = "") => {
return concatFriendshipsApiResponse("followers", user_id, count, next_max_id);
};
const getFollowing = (user_id, count = 50, next_max_id = "") => {
return concatFriendshipsApiResponse("following", user_id, count, next_max_id);
};
const getUserId = async (username) => {
let user = username;
const lower = user.toLowerCase();
const url = `https://www.instagram.com/api/v1/web/search/topsearch/?context=blended&query=${lower}&include_reel=false`;
const data = await fetch(url, fetchOptions).then((r) => r.json());
const result = data.users?.find(
(result) => result.user.username.toLowerCase() === lower,
);
return result?.user?.pk || null;
};
const getUserFriendshipStats = async (username) => {
const user_id = await getUserId(username);
if (!user_id) {
throw new Error(`Could not find user with username ${username}`);
}
const followers = await getFollowers(user_id);
const following = await getFollowing(user_id);
const followersUsernames = followers.map((follower) =>
follower.username.toLowerCase(),
);
const followingUsernames = following.map((followed) =>
followed.username.toLowerCase(),
);
const followerSet = new Set(followersUsernames);
const followingSet = new Set(followingUsernames);
console.log(Array(28).fill("-").join(""));
console.log(
`Fetched`,
followerSet.size,
"followers and ",
followingSet.size,
" following.",
);
console.log(
`If this doesn't seem right then some of the output might be inaccurate`,
);
const PeopleIDontFollowBack = Array.from(followerSet).filter(
(follower) => !followingSet.has(follower),
);
const PeopleNotFollowingMeBack = Array.from(followingSet).filter(
(following) => !followerSet.has(following),
);
return {
PeopleIDontFollowBack,
PeopleNotFollowingMeBack,
};
};
// Make sure you don't delete the quotes
// Replace "example_username" below with your instagram username
//
// Change this:
username = "example_username";
//
//
//
getUserFriendshipStats(username).then(console.log);
@999UnreadMessages
Copy link

This no longer works for me either. Used it a couple of times a few months ago, now every time I try in the last 3 or 4 weeks I get the same errors as the above posters. Does anyone have a solution?

@jessica-guan
Copy link

I'm getting 0 followers and 0 following

@leslienguyn
Copy link

It works for me? It did show a "STOP! This page [Inspect Element -> Console] is meant for developers only. Do not insert code here because there are people trying to hack your information." When I pasted the code, it told me it did not allow pasting and to type "allow pasting" into the console before it let me run it. Other than that, worked normally for me.

@hel74
Copy link

hel74 commented Dec 31, 2023

I got that whole "STOP" message too, and I still pasted the code and tried running it. Now it shows this and won't work anymore
Image 2023-12-31 at 1 28 AM

@vrothermod
Copy link

I found that first typing "allow pasting" and pressing enter, and then pasting the above stuff will allow you to bypass the error!

@abir-taheer
Copy link
Author

I got that whole "STOP" message too, and I still pasted the code and tried running it. Now it shows this and won't work anymore Image 2023-12-31 at 1 28 AM

401 means you were signed out. Instagram has gotten a lot more aggressive with its automation detection. I was able to fix it by increasing the wait time between requests but this means the program will also take a lot longer to complete. Better than not it working at all I suppose. I've updated the code to reflect this.

@salthy26
Copy link

salthy26 commented Jan 4, 2024

hello, i just tried to do it, and it says restricted with an error and stops at domain and counts until a really long time. It does not progress or load the information when I exit the Instagram website to log back in. They made me confirm I wasn't a robot because I committed an action that was restricted. Is there an updated code that goes undetected?

@timiPOG
Copy link

timiPOG commented Jan 5, 2024

hey all, the code actually does still work! after you copy and paste the initial code, replace the variable "example_username" with your username. after that just wait about 1-2 minutes (may vary depending on how many followers you have) and the output will be there. hope this helps/works for u :p
image

@hel74
Copy link

hel74 commented Jan 8, 2024

Image 2024-01-08 at 3 02 AM
I tried it again, waited a couple mins, and it still says this :(

@nickoulos
Copy link

did anyone find a way to get this to work? it used to work for me but wont anymore.

Maybe try changing browser, because it still works on me

@shawndeezy22
Copy link

Image Image these are the two images I'm getting saying there is an error so I am not sure what I can do one is a bunch of errors and the other is saying that it's too many requests but I've been able to do it before is there any fix to this?

@Abdouexe
Copy link

Uploading Picsart_24-01-26_19-54-32-603.jpg…
Anyone can help?

@Portareumbra
Copy link

Has anyone figured out how to bypass the content policy thing?

@iamsyahroni
Copy link

Thank you!

@nisalfernando01
Copy link

Capture
anyone can help me?
Capture

@shawndeezy22
Copy link

I am getting this error message now I'm doing everything right I think
Image-2 copy

@salthy26
Copy link

hey insta detects a syntax error now, is there a new code we could use?
Screenshot 2024-02-26 at 3 06 21 AM

@salthy26
Copy link

It detects a syntax error. Is there an updated code on this?

@abir-taheer
Copy link
Author

It detects a syntax error. Is there an updated code on this?

The API responded with HTML instead of a JSON to one of the requests. Not sure what would trigger it but it looks like your adblocker is also blocking a lot of requests. Try disabling it on instagram before you run it again.

@salthy26
Copy link

so I dont have any adblockers on chrome also used safrai and was unable to use the code as its catching an error does anyon eknow how I can disable the adblockers on insta?

@heroenfather
Copy link

what i did was clear the console > then it shouls say "dont paste anything you dont blah blah blah" go down a line and type "allow pasting" and paste the code, should work

@MrStreeet
Copy link

I'm getting this error now when it was working perfectly
image

@shawndeezy22
Copy link

It's not working again

@r9naa
Copy link

r9naa commented Apr 16, 2024

Whenever I go to check my unfollowers on instagram it gives me this message now ;-;
IMG_2104

@salthy26
Copy link

they suspended my insta account from doing this code just today so be careful

@deyshohan
Copy link

they suspended my insta account from doing this code just today so be careful

did u unfollow a lot of people at once? like 10 or more? and did u do it frequently? because with this, u do have to be careful with the amount u unfollow and how frequently u do it to avoid it.

@salthy26
Copy link

they suspended my insta account from doing this code just today so be careful

did u unfollow a lot of people at once? like 10 or more? and did u do it frequently? because with this, u do have to be careful with the amount u unfollow and how frequently u do it to avoid it.

no i didn't it would be less than 5 but i didn't do it frequently but i did do it three days ago i wanna say so but hopefully i get it back they still havent given me a response so idk what i can do just wanted to give a heads up

@shadowofdeath26
Copy link

my account was suspended yesterday. I only followed one person.
It does not work anymore!

@deyshohan
Copy link

deyshohan commented Apr 23, 2024

eh i think the code is faulty at this point if its causing suspensions or false outputs. for me, it doesn't give the correct output; it misses 20+ ppl in the following output but the follower output is correct.

@shawndeezy22
Copy link

Image I keep getting this message now what should I do about it I also disable ad blockers as well so I don't understand the issue

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