Skip to content

Instantly share code, notes, and snippets.

@nickboyce
Last active February 14, 2024 05:15
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save nickboyce/06c0ff48a2892311bd9a6601baed55b0 to your computer and use it in GitHub Desktop.
Save nickboyce/06c0ff48a2892311bd9a6601baed55b0 to your computer and use it in GitHub Desktop.
Track your Instagram followers over time with Google Sheets Scripts
// Thank you to @juliendev for his script (updated here with minor cosmetic changes)
// https://gist.github.com/JulienDev/df5a3b66e899c224fa1b2dc90acfa2ae
// Your sheet name in the document
var sheetName = "Sheet1";
// Your instagram user id
var user_id = ""; //find your id here : https://codeofaninja.com/tools/find-instagram-user-id
var instagram_base_url = "https://www.instagram.com/graphql/query/";
var following = "?query_hash=58712303d941c6855d4e888c5f0cd22f&variables=%7B%22id%22%3A%22" + user_id + "%22%2C%22first%22%3A24%7D"
var followers = "?query_hash=37479f2b8209594dde7facb0d904896a&variables=%7B%22id%22%3A%22" + user_id + "%22%2C%22first%22%3A24%7D"
var medias = "?query_hash=f2405b236d85e8296cf30347c9f08c2a&variables=%7B%22id%22%3A%22" + user_id + "%22%2C%22first%22%3A12%7D"
function insertFollowerCount() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(this.sheetName);
var followers = getFollowers();
var following = getFollowing();
var medias = getMedias();
var engagement = getEngagement(medias, followers);
sheet.appendRow([Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd"), followers, following, medias.count, engagement.totalLikes, engagement.totalComments, engagement.EngagementRatio]);
};
function getFollowers() {
return parseInt(fetch(instagram_base_url + followers)['data']['user']['edge_followed_by']['count']);
}
function getFollowing() {
return parseInt(fetch(instagram_base_url + following)['data']['user']['edge_follow']['count']);
}
function getMedias() {
return fetch(instagram_base_url + medias)['data']['user']['edge_owner_to_timeline_media'];
}
function getEngagement(medias, followers) {
var totalComments = 0,
totalLikes = 0;
for (var i = 0; i < 12; i++) {
totalComments += parseInt(medias.edges[i].node.edge_media_to_comment.count);
};
for (var l = 0; l < 12; l++) {
totalLikes += parseInt(medias.edges[l].node.edge_media_preview_like.count);
};
var engagementRatio = (((totalLikes + totalComments)) / followers) / 12;
return {
mediaCount: parseInt(medias.count),
totalComments: totalComments,
totalLikes: totalLikes,
EngagementRatio: engagementRatio
}
}
function fetch(url) {
var ignoreError = {
"muteHttpExcecptions": true
};
var source = UrlFetchApp.fetch(url, ignoreError).getContentText();
var data = JSON.parse(source);
return data;
}
@Alexia-iordanoglou
Copy link

It works 🎉! Thanks so much @JulienDev

@syrinx32123
Copy link

@JulienDev YOU ARE THE MAN!!!!! thanks a million!

@gc2222
Copy link

gc2222 commented Aug 29, 2019

Thank you so much @JulienDev! 👍👍

@nickboyce
Copy link
Author

Awesome work @JulienDev! 🚀

Now updated the article and the gist linked from it. Thanks so much! ✊

@lanirk
Copy link

lanirk commented Sep 12, 2019

thanks so much for the update! my script is working again, but I'm running into a weird bug whereby when I add a project trigger, it stops the script from working at all - trigger run or manually run!

My google sheet autosaves at the time I run insertFollowercount, so it is still accessing the document, but the data doesn't fill in. I tested over 4 days and the project trigger said it ran successfully - but no input.

I made additional sheets and reuploaded script, the script filled data in with no problem until I added the project trigger and then it stopped working. Checked timezones etc, everything seems to be correct! Any thoughts? Thank you so much in advance!

@Netuno98
Copy link

Is there a way to use this script to complete not public info? Right now I have to complete a table with all the statistics info across all social media platforms
Like, for every tweet I have to analyze how many retweets, impressions and likes it had. But that info is only available for the owner, and not public like instagram followers.
So is there a way to grab this kind of info from every tweet and send it to a table with the corresponding tweet's dates?

@syrinx32123
Copy link

Is anyone getting an error on this now?

I get this when using a daily trigger to run the script: Request failed for https://www.instagram.com returned code 429. Truncated server response: <meta http-equiv="X-UA-Compatible" ... (use muteHttpExceptions option to examine full response). (line 57, file "Code")

@bbakalov
Copy link

@syrinx32123 have the same shit.
When I send GET request directly from browser where I logged in to the instagra, response is CORRECT.
When I the same request from incognito mode OR postman, I have a bad response like this
{ "data": { "user": { "edge_followed_by": { "count": 405, "page_info": { "has_next_page": false, "end_cursor": null }, "edges": [] } } }, "status": "ok" }

So I think, it's important to be logged in to the IG. Still investigate this topic.

@bbakalov
Copy link

@syrinx32123 I have found solution. I'm not sure how long it will be working BUT it works now)

  1. Login to the instagram via browser (i'm using my usual everyday usage browser)
  2. Go to the API endpoint that you need via browser (example https://www.instagram.com/graphql/query/?query_hash=.....)
  3. Open browser console (in google chrome click F12) and go to the tab "Network"
  4. Reload the page with URL from step #2
  5. In the Network tab open request info and in the tab "Headers" you should find dropdown menu "Request headers", click on it and copy value from cookie section
  6. Go to your Google Script and modify function fetch(url)
function fetch(url) {
  var cookie = 'cookieValueFromTheStep#5';
  var header = {'Cookie':cookie};
  var opt = {
    muteHttpExcecptions: true,
    "headers":header
  };
  var source = UrlFetchApp.fetch(url, opt).getContentText();
  var data = JSON.parse(source);
  return data;
}
  1. Run script and be happy 🎉

If it was helpful, please subscribe to my IG account https://www.instagram.com/bbakalov/

@syrinx32123
Copy link

Anyone else having problems?

@syrinx32123
Copy link

Exception: Request failed for https://www.instagram.com returned code 429. Truncated server response: <!DOCTYPE html> <html lang="en" class="no-js not-logged-in "> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" ... (use muteHttpExceptions option to examine full response) (line 57, file "Code")

This is the error I'm getting.

@bbakalov
Copy link

Because you are not logging in. So approach described above works for me. Try something like this. Maybe you copied something not correct.

Exception: Request failed for https://www.instagram.com returned code 429. Truncated server response: <!DOCTYPE html> <html lang="en" class="no-js not-logged-in "> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" ... (use muteHttpExceptions option to examine full response) (line 57, file "Code")

This is the error I'm getting.

@rancilyo
Copy link

Exception: Request failed for https://www.instagram.com returned code 429. Truncated server response: <!DOCTYPE html> <html lang="en" class="no-js not-logged-in "> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" ... (use muteHttpExceptions option to examine full response) (line 57, file "Code")

This is the error I'm getting.

HI, I'm having this same issue. Tried @bbkalov solution but got lost at step 2. I also use different scripts for different accounts, so it's kind of annoying to log in/out for every one in order to make the script work. Rather write it down by hand and upload an excel.

@bbakalov
Copy link

@rancilyo you should not use different accounts. You need to take cookie data one time, and thats all.
I have described in the second step example of URL that script creates. Debug your code, and find whole URL that script generate. Open this link directly in browser and go further to the step 3.

@syrinx32123
Copy link

I'm not following. Can some one please help!

@syrinx32123
Copy link

There is something wrong with this line of code:

var source = UrlFetchApp.fetch(url, ignoreError).getContentText();

@syrinx32123
Copy link

Awesome work @JulienDev! 🚀

Now updated the article and the gist linked from it. Thanks so much! ✊

Hi Nick, do you have any update on this code please?

@JulienDev
Copy link

Could you try my updated code and let me know if that works for you too? https://gist.github.com/JulienDev/df5a3b66e899c224fa1b2dc90acfa2ae

@syrinx32123
Copy link

@syrinx32123 I have found solution. I'm not sure how long it will be working BUT it works now)

  1. Login to the instagram via browser (i'm using my usual everyday usage browser)
  2. Go to the API endpoint that you need via browser (example https://www.instagram.com/graphql/query/?query_hash=.....)
  3. Open browser console (in google chrome click F12) and go to the tab "Network"
  4. Reload the page with URL from step #2
  5. In the Network tab open request info and in the tab "Headers" you should find dropdown menu "Request headers", click on it and copy value from cookie section
  6. Go to your Google Script and modify function fetch(url)
function fetch(url) {
  var cookie = 'cookieValueFromTheStep#5';
  var header = {'Cookie':cookie};
  var opt = {
    muteHttpExcecptions: true,
    "headers":header
  };
  var source = UrlFetchApp.fetch(url, opt).getContentText();
  var data = JSON.parse(source);
  return data;
}
  1. Run script and be happy 🎉

If it was helpful, please subscribe to my IG account https://www.instagram.com/bbakalov/

Can you make a screen recording of your process and share it here? I lost you on step 2. And in the Network Console there is not tab called "headers"

@bbakalov
Copy link

bbakalov commented Nov 20, 2020

@syrinx32123 Check the video how to get your cookie value
https://streamable.com/ze9ktm

@aquelepablo
Copy link

@syrinx32123 I have found solution. I'm not sure how long it will be working BUT it works now)

  1. Login to the instagram via browser (i'm using my usual everyday usage browser)
  2. Go to the API endpoint that you need via browser (example https://www.instagram.com/graphql/query/?query_hash=.....)
  3. Open browser console (in google chrome click F12) and go to the tab "Network"
  4. Reload the page with URL from step #2
  5. In the Network tab open request info and in the tab "Headers" you should find dropdown menu "Request headers", click on it and copy value from cookie section
  6. Go to your Google Script and modify function fetch(url)
function fetch(url) {
  var cookie = 'cookieValueFromTheStep#5';
  var header = {'Cookie':cookie};
  var opt = {
    muteHttpExcecptions: true,
    "headers":header
  };
  var source = UrlFetchApp.fetch(url, opt).getContentText();
  var data = JSON.parse(source);
  return data;
}
  1. Run script and be happy 🎉

If it was helpful, please subscribe to my IG account https://www.instagram.com/bbakalov/

Can you make a screen recording of your process and share it here? I lost you on step 2. And in the Network Console there is not tab called "headers"

You can just type document.cookie on console, it will print the cookie value. 😉

@bartvandoren
Copy link

bartvandoren commented Nov 22, 2020

@syrinx32123 Check the video how to get your cookie value
https://streamable.com/ze9ktm

works like a charm! great work

@syrinx32123 , @aquelepablo, @bbakalov , @nickboyce
Any idea how to get the usernames of your followers?

@syrinx32123
Copy link

@syrinx32123 Check the video how to get your cookie value
https://streamable.com/ze9ktm

works like a charm! great work

@syrinx32123 , @aquelepablo, @bbakalov , @nickboyce
Any idea how to get the usernames of your followers?

I followed it exactly step by step but my screen looks different. It didn't work for me.

@zarasafdari
Copy link

Is this still working? I am getting errors...

@syrinx32123
Copy link

syrinx32123 commented Jan 20, 2021 via email

@mitchobrian
Copy link

No it’s not working

On Wed, Jan 20, 2021 at 11:02 AM zarasafdari @.> wrote: @.* commented on this gist. ------------------------------ Is this still working? I am getting errors... — You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://gist.github.com/06c0ff48a2892311bd9a6601baed55b0#gistcomment-3600433, or unsubscribe https://github.com/notifications/unsubscribe-auth/ANAHGXMP5IKPS2M65UOAWALS22S2RANCNFSM4IPUSEZA .

are there new solutions?

@NickCrews
Copy link

In fetch(), there's a typo, muteHttpExcecptions is misspelled. The rest of the script isn't working for me, but still I thought it might be worth pointing that out if people are copy pasting snippets like I am.

@bbakalov
Copy link

I have found solution how to get correct "cookie" value, for the request.
Here is an article: https://thomas-strosse.medium.com/how-to-automatically-create-instagram-analytics-with-a-google-sheets-scripts-325ee5fa8e7e
Over there paragraph start from words "To get the cookie data, do the following:" steps 1-5

It was useful for me. Maybe it helps someone.

@syrinx32123 I have found solution. I'm not sure how long it will be working BUT it works now)

  1. Login to the instagram via browser (i'm using my usual everyday usage browser)
  2. Go to the API endpoint that you need via browser (example https://www.instagram.com/graphql/query/?query_hash=.....)
  3. Open browser console (in google chrome click F12) and go to the tab "Network"
  4. Reload the page with URL from step #2
  5. In the Network tab open request info and in the tab "Headers" you should find dropdown menu "Request headers", click on it and copy value from cookie section
  6. Go to your Google Script and modify function fetch(url)
function fetch(url) {
  var cookie = 'cookieValueFromTheStep#5';
  var header = {'Cookie':cookie};
  var opt = {
    muteHttpExcecptions: true,
    "headers":header
  };
  var source = UrlFetchApp.fetch(url, opt).getContentText();
  var data = JSON.parse(source);
  return data;
}
  1. Run script and be happy 🎉

If it was helpful, please subscribe to my IG account https://www.instagram.com/bbakalov/

@NickCrews
Copy link

Oh as a follow up, I ended up just using one of the many instagram APIs available from RapidAPI. Someone else already did the dirty work, figured this stuff out, and then gave an even easier to use API for us. Many of them have a free tier that was totally adequate for my needs.

@rancilyo
Copy link

Oh as a follow up, I ended up just using one of the many instagram APIs available from RapidAPI. Someone else already did the dirty work, figured this stuff out, and then gave an even easier to use API for us. Many of them have a free tier that was totally adequate for my needs.

Thanks for the info. But, how does it work? I have 0 skills as a programmer, lol.

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