Skip to content

Instantly share code, notes, and snippets.

@abir-taheer
Last active July 16, 2025 16:41
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);
@tangzwire
Copy link

It feels like the code works sometimes, not all the time. Then why does it say SyntaxError in this case?

@duartea411
Copy link

This didn't work and I got a pop up saying if I try doing it again I'll permanently disable my account?!

@jeffron13
Copy link

Same exact thing happened to me. Instagram said it detected automated activity and threatened to permanently disable my account from using this code recently. I have always used this code the same way but I think instagram is making this not work anymore.

@abir-taheer
Copy link
Author

It feels like the code works sometimes, not all the time. Then why does it say SyntaxError in this case?

Syntax error means invalid code. You probably accidentally copied the title or didn't copy the entirety before pasting

@abir-taheer
Copy link
Author

Same exact thing happened to me. Instagram said it detected automated activity and threatened to permanently disable my account from using this code recently. I have always used this code the same way but I think instagram is making this not work anymore.

Hmm, that sounds pretty serious. I'll update the script and make the the waiting period in between requests longer and add a delay between getting the followers and following but apart from that it's outside of my hands.

@tangzwire
Copy link

It feels like the code works sometimes, not all the time. Then why does it say SyntaxError in this case?

Syntax error means invalid code. You probably accidentally copied the title or didn't copy the entirety before pasting

Ah OK could be. However code seem to work now. Couldnt find any issues with the code so far. But I tried running the code when I logged into Instagram, I waited like 2-3 minutes before running the code and it was successful.

@tangzwire
Copy link

Same exact thing happened to me. Instagram said it detected automated activity and threatened to permanently disable my account from using this code recently. I have always used this code the same way but I think instagram is making this not work anymore.

Hmm, that sounds pretty serious. I'll update the script and make the the waiting period in between requests longer and add a delay between getting the followers and following but apart from that it's outside of my hands.

Same exact thing happened to me. Instagram said it detected automated activity and threatened to permanently disable my account from using this code recently. I have always used this code the same way but I think instagram is making this not work anymore.

I am not getting that popup message when running the code, however whenever I log into Instagram web I do get that popup message from time to time.

A lot of people from Reddit have reported that they are getting the error message without using any 3rd party apps or running any kind of automated service. If you search for "We have detected automated activities on your account reddit" you will find threads regarding this (where people complain about getting the popup message without using any 3rd party service or automated service).

@andrewlin27
Copy link

andrewlin27 commented Jun 7, 2023

It seems like I have too many followers/following and it doesn't finish reading all the data as the final count and output are both inaccurate. Specifically, for an account with 1300 followers, it only reads about 1000 of them. Would it solve this problem if I change timeToSleep to something less like random(50, 200) instead of random(100, 500)?

@jeffron13
Copy link

jeffron13 commented Jun 8, 2023

Hi update to my previous comment. I tried this on a different account and a different browser with some success. I felt like the pauses were longer too which might of helped. I recommend using chrome not safari and logging into a different instagram account than your own but still type in your username. I guess you can look at anybody's not following back if their account is public with this code. it did end up only loading 1300/1700 of my following but it did all of my 3000+ followers so the output was a little lacking. should I just do it again? I'm kinda scared doing this since that message they sent me about automated activity detected.

@andrewlin27
Copy link

Hi update to my previous comment. I tried this on a different account and a different browser with some success. I felt like the pauses were longer too which might of helped. I recommend using chrome not safari and logging into a different instagram account than your own but still type in your username. I guess you can look at anybody's not following back if their account is public with this code. it did end up only loading 1300/1700 of my following but it did all of my 3000+ followers so the output was a little lacking. should I just do it again? I'm kinda scared doing this since that message they sent me about automated activity detected.

How are you able to even load 1300? I can only load 1000 max and that's with an ethernet cable on chrome. Are you doing anything special?

@ebanksa1
Copy link

ebanksa1 commented Jul 6, 2023

Hi, I am getting this message, can anyone help?

ErrorUtils caught an error:

Cannot read properties of undefined (reading 'map')

Subsequent non-fatal errors won't be logged; see https://fburl.com/debugjs.

@hqnqip
Copy link

hqnqip commented Jul 10, 2023

The program works as intended. Although, judging from the other comments, I'll refrain from using it often.

Copy link

ghost commented Jul 14, 2023

dear abir,
is it possible to see recent unfollowings or any sort of activity in our profiles?using this code is really helpful,given that third party apps can harm our accounts.thank you very much!I'll be waiting for your response

@annieehng
Copy link

For people having any problems, make sure to clear your console before copying and pasting. I did it once after getting an error, and it worked

@muharsadika
Copy link

it works. thank you :)

@abir-taheer
Copy link
Author

Screen Shot 2023-08-11 at 12 39 09 PM

It doesn't seem to be working anymore. I keep getting this :/

An error code in the 500s means an internal server error. Something wrong on instagram's side not yours.

@tangzwire
Copy link

Screen Shot 2023-08-11 at 12 39 09 PM

It doesn't seem to be working anymore. I keep getting this :/

Code is working fine for me. If you are receiving an error message, it could be that something is down/not working on Instagrams side. I would just wait till next day and run the code again. Just make sure not to change anything on the code if you dont know what you are doing. Also not a good idea to use the code very often as it can sometimes generate a message from Instagram saying that it has detected an automatic behaviour from your account.

For me, what happens is that if I run this code, the next day I will automatically get logged out from Instagram. I would just login to Instagram but then I would wait maybe 5-10 hours before I run the code again (just to be on the safe side).

But @abir-taheer, much thanks to you for creating such solution!

@Devtool-192
Copy link

Screen Shot 2023-08-17 at 2 38 41 pm

Hi It always worked for me but now im getting this and not sure whats happening. It logs me out when I try now

@zlindra
Copy link

zlindra commented Aug 19, 2023

hi abir, idk why but after this, now my following number is locked even if i start to follow/unfollow new people, it stays on “3271” pls help!!!

i also experience this! does anyone know how to fix it?

@Xeizer-xei
Copy link

const fetchOptions = {
credentials: "include",
headers: {
"X-IG-App-ID": "936619743392459",
},
method: "GET",
};

let username;

window.resolveInstaScriptPermissions = () => {};

async function executeWithNotice(fn, ...args) {
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();
return;
}

const permission = new Promise(resolve => (window.resolveInstaScriptPermissions = resolve));

const WARNING = `
--- IMPORTANT PLEASE READ ---\n\n
Hey! \n
No worries, everything is fine. Before starting, let me explain how this works and share some advice.\n
First, never blindly paste code into the console unless you understand it.\n
Although this code isn't malicious, the developer console is risky unless you're confident in your abilities.\n
Pasting code you don't comprehend is like giving your phone to a stranger.\n
Anything you can do on Instagram's website or app can be done through code in the developer console. Be very cautious!\n\n
How this script works:\n
(APIs allow your browser to communicate with Instagram's servers)\n

  1. We use the Instagram search API with your username to obtain your User ID, which identifies your account on Instagram.\n
  2. We call the 'following' API endpoint with your user ID.\n
    This mimics scrolling through your own Instagram following list, with pauses between requests to avoid looking like a bot.\n
  3. We repeat this process for the 'followers' API endpoint, creating lists of your followers and followings.\n
  4. We compare the lists, displaying the difference as 'People who don't follow you back' and vice versa.\n\n
    Now that you know how it works, do you want to continue? (If not, close this tab.)\n`;

// Sorry I know this is ugly I didn't want to make the file too long
document.write(<pre style='white-space: pre-wrap;word-wrap: break-word;'>${WARNING}</pre> <br /> <button style='cursor:pointer;padding: 1rem;box-shadow: 4px 5px 1px #b0b0b0;font-size: 18px;background: #00b894; color: white;border-radius: 10px;' onClick="window.resolveInstaScriptPermissions()">OK I understand and want to continue</button>);

await permission;

document.write("

Ok, thanks. Look back at the console to see the output. Refreshing this tab will also make everything go back to normal.

")
return await fn(...args);
}

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const random = (min, max) => Math.ceil(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(100, 500);
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) => {
if (username === "example_username") {
username = window.prompt(
"Hey, it looks like you forgot to change the username variable. No worries, we'll update it right now. What's your 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";
//
//
//
executeWithNotice(getUserFriendshipStats, username).then(console.log);

@shawndeezy22
Copy link

is this the new link to copy where do we start and where do we finish I don't know it is and what I should copy and paste

@shawndeezy22
Copy link

Xeizer-xei

Image

i also copied and pasted the script exactly and this is the message that I got I tried a couple of times I even tried to copy and paste the script from the comments that you wrote but it was still very confusing so I'm not sure what else I can do can you please explain. @Xeizer-xei @abir-taheer

@delurk-alt
Copy link

hi! total coding noob here. how can i just get a list of the current follower and following list? this only prints out those not following back.

@jas-yang
Copy link

hi! total coding noob here. how can i just get a list of the current follower and following list? this only prints out those not following back.

replace

return {
    PeopleIDontFollowBack,
    PeopleNotFollowingMeBack,
  };

with

return {
    followerSet,
    followingSet,
  };

@stevannohero
Copy link

stevannohero commented Oct 6, 2023

It seems like I have too many followers/following and it doesn't finish reading all the data as the final count and output are both inaccurate. Specifically, for an account with 1300 followers, it only reads about 1000 of them. Would it solve this problem if I change timeToSleep to something less like random(50, 200) instead of random(100, 500)?

have you found the solution on this? it doesnt load all my following and followers as well @andrewlin27

@kuki88
Copy link

kuki88 commented Oct 8, 2023

image

there's an error, maybe instagram has blocked this method somehow?

@akaplan521
Copy link

did meta/insta block this damn

@IceLordOtis
Copy link

IceLordOtis commented Oct 10, 2023

image

there's an error, maybe instagram has blocked this method somehow?

This also happened to me for the first time today

@hel74
Copy link

hel74 commented Oct 10, 2023

uhh does this work still? its been working fine before

Screenshot 2023-10-10 at 12 55 12 AM

@cchoi928
Copy link

Yo, I have the same problem as kuki88 and icelordOtis, I've been using this method for months and it's worked without a single problem but all of a sudden today when I tried to use it said it "violates the following Content Security Policy Directive", things like that and it appears in big red paragraphs. LIterally this is the first time that I've ever had this problem.

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