Skip to content

Instantly share code, notes, and snippets.

@chiradeep
Last active April 3, 2022 16:42
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chiradeep/5a76369b8a2e6038737b764f5508411d to your computer and use it in GitHub Desktop.
Save chiradeep/5a76369b8a2e6038737b764f5508411d to your computer and use it in GitHub Desktop.
Google App Script to Collect GH Traffic Stats into Google Sheets
//Setup:
// Create a sheet with the first sheet called 'TrafficData'. Cell Values are:
// A1: Repo Traffic Collector
// A3: Organization B3: <org value>
// A4: Repo B4: <repo name>
// A7: Date, B7: Views, C7: Uniques, D7: Weeknumber
//Tools -> Script Editor
//Add this script, fill in your GitHub TOKEN (https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line)
//Run the onOpen script - you will be warned it is insecure, but accept anyway. This should add a menu item to your sheet
//Use the Custom GitHub menu to run the getRepoTrafficStats function
//Schedule the script to run every night at 1am to automatically update the next row
//https://developers.google.com/apps-script/guides/triggers/installable#time-driven_triggers
//Use the weeknumber column to generate cumulative stats for the week
//Example formula: =sumif(D$8:D,12,B$8:B) will give you cumulative week 12 stats
var TOKEN = 'YOUR_TOKEN_HERE';
// add custom menu
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom GitHub Menu')
.addItem('Get GitHub Traffic views', 'getRepoTrafficStats')
.addToUi();
}
function lastRow() {
column = 'A';
var lastRow = SpreadsheetApp.getActiveSheet().getMaxRows();
var values = SpreadsheetApp.getActiveSheet().getRange(column + "1:" + column + lastRow).getValues();
for (; values[lastRow - 1] == "" && lastRow > 0; lastRow--) {}
Logger.log(values[lastRow - 1])
return lastRow ;
}
function getRepoTrafficStats() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("TrafficData");
var org = sheet.getRange(3,2).getValue();
var repoName = sheet.getRange(4,2).getValue();
var baseURL = "https://api.github.com/repos/";
var headers = {
"Authorization": "Token " + TOKEN,
"Accept": "application/vnd.github.v3+json"
};
//Logger.log(headers);
var options = {
"headers": headers,
"method" : "GET",
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(baseURL + org + "/" + repoName + "/traffic/views", options);
// Parse the JSON reply
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data['views']);
var rows = Object.keys(data["views"]).map(function(key, index) {
val = data["views"][index]
return [val['timestamp'].substring(0,10), val['count'], val['uniques']];
});
Logger.log(rows); // array of rows
lastR = lastRow()
lastDate = sheet.getRange(lastR, 1).getValue();
lastViews = sheet.getRange(lastR, 2).getValue();
Logger.log("Last row=" + lastR);
Logger.log("Last date=" + lastDate);
Logger.log("Last views=" + lastViews);
lastDateIndex = 0
for (var i=0; i < rows.length; i++) {
if (rows[i][0] == lastDate) {
Logger.log("Last date in sheet found in row " + i);
lastDateIndex = i
break;
}
}
j=0; //re-update last row
if (lastDate == "Date") {
j = 1; //unless there is no data to begin with
}
for (var i=lastDateIndex; i< rows.length; i++) {
Logger.log("Updating row: " + (lastR + j))
rowNum = lastR + j
sheet.getRange(rowNum, 1, 1, 3).setValues([rows[i]]);
sheet.getRange(rowNum, 1, 1, 1).setNumberFormat('@'); //need date in text format
sheet.getRange(rowNum, 1, 1, 3).setHorizontalAlignment('right');
sheet.getRange(rowNum, 4).setFormula('=WEEKNUM(' + 'A' + rowNum+ ')');
j++;
}
}
@C0staTin
Copy link

This is a very useful code!
It works nicely for me.
The only thing I'm missing is the capability to filter out certain visitors sources (sites).
This info is available in Github stats, but I wonder if this could be done via API.

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