Skip to content

Instantly share code, notes, and snippets.

@mhawksey
Last active August 14, 2018 17:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhawksey/1247932 to your computer and use it in GitHub Desktop.
Save mhawksey/1247932 to your computer and use it in GitHub Desktop.
Google Apps Script to get viralheat sentiment analysis for a bunch of cells
var VIRAL_KEY = "YOUR_API_KEY"; // your viralheat API key. Register at https://viralheat.com/register
var doc = SpreadsheetApp.getActiveSpreadsheet(); // sets the current spreadsheet
var sheet = doc.getSheetByName("Main"); // defines we are working from the sheet named Main
var START_ROW = 2; // location of first row of data
var TEXT_COL = 1; // the column number of where the text you want to analyse is
var MOOD_COL = 6; // the column number of where you want to record the mood returned by viralheat
var PROB_COL = 7; // the column number of where you want to record the probability that the mood is correct
function getStats() {
var last = sheet.getLastRow(); // find the last row in the sheet
for (var rowIdx=0; rowIdx < last; rowIdx++){ // setup a loop to cycle across each text cell
var rowNum = rowIdx+START_ROW;
var itemtext = sheet.getRange(rowNum,TEXT_COL).getValue(); // get the text you want to analyse
if(sheet.getRange(rowNum, MOOD_COL)!="" && itemtext != "" && itemtext.length < 360){
var senti = getSentiment(itemtext); // call the getSentiment function with the text
sheet.getRange(rowNum, MOOD_COL).setValue(senti.mood); // record the returned mood
sheet.getRange(rowNum, PROB_COL).setValue(senti.prob); // record the returned probability
}
}
doc.toast("Done");
}
function getSentiment(text){
try { // setup some options for the UrlFetch
var options =
{
"method" : "get",
"contentType" : "application/json"
};
// pass the text to viralheat
var response = UrlFetchApp.fetch("https://app.viralheat.com/social/api/sentiment/?text="+encodeURIComponent(text)+"&api_key="+VIRAL_KEY, options);
// turn the result from JSON into a variable
var results = JSON.parse(response.getContentText());
Utilities.sleep(5000);
// pass the result back
return results;
} catch(e){
Logger.log(e);
}
var err = "-";
return err;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment