Skip to content

Instantly share code, notes, and snippets.

@zahhar zahhar/gs_igm.js
Last active Jul 17, 2018

Embed
What would you like to do?
Google Spreadsheet script for Instagram metrics
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Instagram')
.addItem('Update metrics', 'appendInstagramMetrics')
.addToUi();
}
function appendInstagramMetrics() {
var today = Utilities.formatDate(new Date(), "GMT+2", "dd.MM.yyyy HH:mm");
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets().forEach(function (s) {
s.appendRow([today].concat(getInstagramMetricsForUser(s.getName())));
var lastCell = s.getRange(s.getLastRow(), s.getLastColumn());
lastCell.setFormulaR1C1("=(R[0]C[-3]-R[-1]C[-3])");
});
}
function getInstagramMetricsForUser(username) {
var url = 'https://www.instagram.com/'+username+'/';
var page = UrlFetchApp.fetch(url).getContentText();
var html = HtmlService.createHtmlOutput(page).getContent();
var regExp = new RegExp(/<meta property=\"og:description\" content=\"([\d,]*) Followers, ([\d,]*) Following, ([\d,]*) Posts(.*)\" \/>/);
var matches = regExp.exec(html);
matches.forEach(function (m, i) {
matches[i] = m.replace(",","");
});
return [matches[1],matches[2],matches[3]];
}
@zahhar

This comment has been minimized.

Copy link
Owner Author

commented Jul 17, 2018

How-to

  1. Create new Google Sheet. For convenience, set column names on the very first row to: "Date and time" (for column A), "Followers" (for column B), "Following" (for column C), "Posts" (for column D), "Followers Delta" (for column E).
  2. Rename Sheet1 into Instagram account you want to track, e.g. your account name. Account has to be public. If you leave it as it, it will track this guy: https://www.instagram.com/Sheet1/. If you want to track more then one account, create new sheet per each account, name it accordingly, and set column names as described above.
  3. Open Script editor and paste this gist into it. You may want to adjust timezone and date/time format at Line 9. (Tools->Script editor)
  4. In Script editor, set time-driven trigger to call appendInstagramMetrics() function as frequently as you would like to update metrics, e.g. once a day or once an hour (for testing purposes you can update it every minute).
  5. Save script, close editor, and reopen Google Sheet you created. You will see new menu item "Instagram" appeared, where from you can trigger metrics update manually (makes sense for testing, as the goal is to have it triggered automatically on timer you configured on the previous step).

After some idle time you should see each sheet will populate automatically with number of Followers, Following and Posts particular account had at the specific date and time, and calculated Follower Delta between calls.

Enjoy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.