public
Last active

TAGS 2.4.4 Google Apps Script to pull searches from the Twitter API into a Google Spreadsheet (see http://bit.ly/TAGSsetup )

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
// Part of this code up to END OF (c) is:
/*
Copyright 2011 Martin Hawksey
 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
 
http://www.apache.org/licenses/LICENSE-2.0
 
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
 
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sumSheet = ss.getSheetByName("Readme/Settings");
var REFERER = sumSheet.getRange("B9").getValue();
var SEARCH_TERM = sumSheet.getRange("B10").getValue();
var SEARCH_DURATION = sumSheet.getRange("B11").getValue();
var NUMBER_OF_TWEETS = sumSheet.getRange("B12").getValue();
var RESULT_TYPE = sumSheet.getRange("B13").getValue();
 
function onOpen() {
var menuEntries = [ {name: "API Authentication", functionName: "configureAPI"}, {name:"Test Collection", functionName: "testCollection"}, {name: "Run Now!", functionName: "collectTweets"} ];
ss.addMenu("Twitter", menuEntries);
}
 
function authenticate(){
authorize();
}
function configureAPI() {
renderAPIConfigurationDialog();
}
 
function renderAPIConfigurationDialog() {
// modified from Twitter Approval Manager
// http://code.google.com/googleapps/appsscript/articles/twitter_tutorial.html
var doc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setTitle(
"Twitter API Authentication Configuration").setHeight(400).setWidth(420);
app.setStyleAttribute("padding", "10px");
 
//var dialog = app.loadComponent("GUIComponent");
var dialogPanel = app.createFlowPanel().setWidth("400px");
var label1 = app.createLabel("1. Register for an API key with Twitter at http://dev.twitter.com/apps/new (if you've already registered a Google Spreadsheet/Twitter mashup you can reuse your existing Consumer Key/Consumer Secret). In the form these are the important bits: ").setStyleAttribute("paddingBottom", "10px");
var label2 = app.createLabel(" - Application Website = anything you like").setStyleAttribute("textIndent", "30px");
var label3 = app.createLabel(" - Application Type = Browser").setStyleAttribute("textIndent", "30px");
var label4 = app.createLabel(" - Callback URL = https://spreadsheets.google.com/macros").setStyleAttribute("textIndent", "30px");
var label5 = app.createLabel(" - Default Access type = Read-only ").setStyleAttribute("textIndent", "30px").setStyleAttribute("paddingBottom", "10px");
var label6 = app.createLabel("2. Once finished filling in the form and accepting Twitter's terms and conditions you'll see a summary page which includes a Consumer Key and Consumer Secret which you need to enter below").setStyleAttribute("paddingBottom", "10px");
var label7 = app.createLabel("3. When your Key and Secret are saved you need to open Tools > Script Editor ... and run the 'authenticate' function").setStyleAttribute("paddingBottom", "10px");
//("<strong>hello</strong><ul><li>one</li></ul>");
dialogPanel.add(label1);
dialogPanel.add(label2);
dialogPanel.add(label3);
dialogPanel.add(label4);
dialogPanel.add(label5);
dialogPanel.add(label6);
dialogPanel.add(label7);
 
var consumerKeyLabel = app.createLabel(
"Twitter OAuth Consumer Key:");
var consumerKey = app.createTextBox();
consumerKey.setName("consumerKey");
consumerKey.setWidth("90%");
consumerKey.setText(getConsumerKey());
var consumerSecretLabel = app.createLabel(
"Twitter OAuth Consumer Secret:");
var consumerSecret = app.createTextBox();
consumerSecret.setName("consumerSecret");
consumerSecret.setWidth("90%");
consumerSecret.setText(getConsumerSecret());
var saveHandler = app.createServerClickHandler("saveConfiguration");
var saveButton = app.createButton("Save Configuration", saveHandler);
var listPanel = app.createGrid(2, 2);
listPanel.setStyleAttribute("margin-top", "10px")
listPanel.setWidth("100%");
 
listPanel.setWidget(0, 0, consumerKeyLabel);
listPanel.setWidget(0, 1, consumerKey);
listPanel.setWidget(1, 0, consumerSecretLabel);
listPanel.setWidget(1, 1, consumerSecret);
 
 
// Ensure that all form fields get sent along to the handler
saveHandler.addCallbackElement(listPanel);
//var dialogPanel = app.createFlowPanel();
//dialogPanel.add(helpLabel);
dialogPanel.add(listPanel);
dialogPanel.add(saveButton);
app.add(dialogPanel);
doc.show(app);
}
 
function collectTweets() {
// if continuous sheetname = archive else make a name
if (RESULT_TYPE == "continuous"){
var sheetName = "Archive";
} else {
var sheetName = Utilities.formatDate(new Date(), "GMT", "dd-MMM-yy hh:mm"); //make a new sheet name based on todays date
}
// if sheetname doesn't exisit make it
if (!ss.getSheetByName(sheetName)){
var temp = ss.getSheetByName("TMP");
var sheet = ss.insertSheet(sheetName, {template:temp});
} else {
var sheet = ss.getSheetByName(sheetName);
}
// else if already have archive get since id
var stored = getRowsData(sheet);
if (stored.length >0 ){
var sinceid = stored[0]["id_str"];
}
//if no since id grab search results
if (sinceid){
var data = getTweets(SEARCH_TERM, NUMBER_OF_TWEETS, sinceid); // get results from twitter sinceid
} else {
var data = getTweets(SEARCH_TERM, NUMBER_OF_TWEETS); // get results from twitter
}
// if some data insert rows
if (data.length>0){
sheet.insertRowsAfter(1, data.length);
setRowsData(sheet, data);
}
}
 
function testCollection(){
var data = getTweets(SEARCH_TERM, 5); // get results from twitter
if (data.length>0){
Browser.msgBox("Found some tweets. Here's an example one from "+data[0]["from_user"]+" which says: "+data[0]["text"]);
} else {
Browser.msgBox("Twitter said: "+ScriptProperties.getProperty("errormsg"));
}
}
 
function getTweets(searchTerm, maxResults, sinceid, languageCode) {
//Based on Mikael Thuneberg getTweets - mod by mhawksey to convert to json
// if you include setRowsData this can be used to output chosen entries
if (isConfigured()){
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl(
"https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
} else {
var requestData = {"method":"GET", "headers": { "User-Agent": REFERER}}
}
try {
var pagenum = 1;
var data =[];
var idx = 0;
var sinceurl ="";
// prepare search term
 
if (SEARCH_DURATION != "default"){
var period = 0;
switch (SEARCH_DURATION){
case "yesterday":
period = 0;
break;
case "-2 days":
period = 1;
break;
case "-3 days":
period = 2;
break;
case "-4 days":
period = 3;
break;
case "-5 days":
period = 4;
break;
case "-6 days":
period = 5;
break;
case "-7 days":
period = 6;
break;
}
var until=new Date();
until.setDate(until.getDate());
var since = new Date(until);
since.setDate(since.getDate()-1);
}
if (typeof maxResults == "undefined") {
maxResults = 100;
}
if (maxResults > 1500) {
maxResults = 1500;
}
if (maxResults > 100) {
resultsPerPage = 100;
maxPageNum = maxResults / 100;
} else {
resultsPerPage = maxResults;
maxPageNum = 1;
}
if (sinceid != null && sinceid.length > 0) {
sinceurl = "&since_id=" + sinceid;
}
//Logger.log(twDate(since)+" "+twDate(until));
searchTerm = encodeURIComponent(searchTerm);
var baseURL = "http://search.twitter.com/search.json";
for (pagenum = 1; pagenum <= maxPageNum; pagenum++) {
var URL = "";
if (typeof nextPage != "undefined"){
URL = nextPage;
} else if (pagenum == 1) {
URL = URL + "?q=" + searchTerm;
if (typeof since != "undefined") URL = URL + "&since=" + twDate(since);
if (typeof until != "undefined") URL = URL + "&until=" + twDate(until);
URL = URL + "&rpp=" + resultsPerPage;
URL = URL + "&page=" + pagenum;
URL = URL + "&result_type=recent";
URL = URL + "&include_entities=true";
URL = URL + "&with_twitter_user_id=true";
URL = URL + sinceurl;
if (typeof languageCode != "undefined") {
if (languageCode.length > 0) {
URL = URL + "&lang=" + languageCode;
}
}
}
if (URL != ""){
Logger.log(URL);
var response = UrlFetchApp.fetch(baseURL+URL, requestData);
var contentHeader = response.getHeaders();
if (response.getResponseCode() == 200) {
var responseData = Utilities.jsonParse(response.getContentText());
var nextPage = responseData.next_page;
var currentPage = responseData.page;
var objects = responseData.results;
for (i in objects){ // not pretty but I wanted to extract geo data
if (objects[i].geo != null){
objects[i]["geo_coordinates"] = "loc: "+objects[i].geo.coordinates[0]+","+objects[i].geo.coordinates[1];
}
objects[i]["status_url"] = "http://twitter.com/"+objects[i].from_user+"/statuses/"+objects[i].id_str;
objects[i]["time"] = (objects[i]["created_at"]).substring(5,25);
objects[i]["entities_str"] = Utilities.jsonStringify(objects[i]["entities"]);
data[idx]=objects[i];
idx ++;
}
}
}
}
return data;
} catch (e) {
Logger.log("Line "+e.lineNumber+" "+e.message+e.name);
Browser.msgBox("Line "+e.lineNumber+" "+e.message+e.name);
ScriptProperties.setProperty("errormsg","Line "+e.lineNumber+" "+e.message+e.name);
return data;
}
}
 
function twDate(aDate){
var dateString = Utilities.formatDate(aDate, "GMT", "yyyy-MM-dd");
return dateString;
}
 
// END OF (c)
 
// The rest of this code is currently (c) Google Inc.
 
// setRowsData fills in one row of data per object defined in the objects Array.
// For every Column, it checks if data objects define a value for it.
// Arguments:
// - sheet: the Sheet Object where the data will be written
// - objects: an Array of Objects, each of which contains data for a row
// - optHeadersRange: a Range of cells where the column headers are defined. This
// defaults to the entire first row in sheet.
// - optFirstDataRowIndex: index of the first row where data should be written. This
// defaults to the row immediately below the headers.
function setRowsData(sheet, objects, optHeadersRange, optFirstDataRowIndex) {
var headersRange = optHeadersRange || sheet.getRange(1, 1, 1, sheet.getMaxColumns());
var firstDataRowIndex = optFirstDataRowIndex || headersRange.getRowIndex() + 1;
var headers = normalizeHeaders(headersRange.getValues()[0]);
 
var data = [];
for (var i = 0; i < objects.length; ++i) {
var values = []
for (j = 0; j < headers.length; ++j) {
var header = headers[j];
values.push(header.length > 0 && objects[i][header] ? objects[i][header] : "");
}
data.push(values);
}
 
var destinationRange = sheet.getRange(firstDataRowIndex, headersRange.getColumnIndex(),
objects.length, headers.length);
destinationRange.setValues(data);
}
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// This argument is optional and it defaults to all the cells except those in the first row
// or all the cells below columnHeadersRowIndex (if defined).
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
var headersIndex = columnHeadersRowIndex || range ? range.getRowIndex() - 1 : 1;
var dataRange = range ||
sheet.getRange(headersIndex + 1, 1, sheet.getMaxRows() - headersIndex, sheet.getMaxColumns());
var numColumns = dataRange.getEndColumn() - dataRange.getColumn() + 1;
var headersRange = sheet.getRange(headersIndex, dataRange.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(dataRange.getValues(), normalizeHeaders(headers));
}
 
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
 
// Returns an Array of normalized Strings.
// Empty Strings are returned for all Strings that could not be successfully normalized.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
keys.push(normalizeHeader(headers[i]));
}
return keys;
}
 
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
//if (!isAlnum(letter)) { // I removed this because result identifiers have '_' in name
// continue;
//}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
 
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
 
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
 
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}
 
// The first part of this code was developed by google and has a copyright statement.
// Everything after // Archive Twitter Status Updates is by mhawksey and released under CC
 
 
// Copyright 2010 Google Inc. All Rights Reserved.
/**
* @fileoverview Google Apps Script demo application to illustrate usage of:
* MailApp
* OAuthConfig
* ScriptProperties
* Twitter Integration
* UiApp
* UrlFetchApp
*
* @author vicfryzel@google.com (Vic Fryzel)
*/
 
/**
* Key of ScriptProperty for Twitter consumer key.
* @type {String}
* @const
*/
var CONSUMER_KEY_PROPERTY_NAME = "twitterConsumerKey";
 
/**
* Key of ScriptProperty for Twitter consumer secret.
* @type {String}
* @const
*/
var CONSUMER_SECRET_PROPERTY_NAME = "twitterConsumerSecret";
 
/**
* Key of ScriptProperty for tweets and all approvers.
* @type {String}
* @const
*/
var TWEETS_APPROVERS_PROPERTY_NAME = "twitterTweetsWithApprovers";
 
/**
* @param String Approver email address required to give approval
* prior to a tweet going live. Comma-delimited.
*/
function setApprovers(approvers) {
ScriptProperties.setProperty(APPROVERS_PROPERTY_NAME, approvers);
}
 
/**
* @return String OAuth consumer key to use when tweeting.
*/
function getConsumerKey() {
var key = ScriptProperties.getProperty(CONSUMER_KEY_PROPERTY_NAME);
if (key == null) {
key = "";
}
return key;
}
 
/**
* @param String OAuth consumer key to use when tweeting.
*/
function setConsumerKey(key) {
ScriptProperties.setProperty(CONSUMER_KEY_PROPERTY_NAME, key);
}
 
/**
* @return String OAuth consumer secret to use when tweeting.
*/
function getConsumerSecret() {
var secret = ScriptProperties.getProperty(CONSUMER_SECRET_PROPERTY_NAME);
if (secret == null) {
secret = "";
}
return secret;
}
 
/**
* @param String OAuth consumer secret to use when tweeting.
*/
function setConsumerSecret(secret) {
ScriptProperties.setProperty(CONSUMER_SECRET_PROPERTY_NAME, secret);
}
 
 
/**
* @return bool True if all of the configuration properties are set,
* false if otherwise.
*/
function isConfigured() {
return getConsumerKey() != "" && getConsumerSecret != "" ;
}
 
 
/** Retrieve config params from the UI and store them. */
function saveConfiguration(e) {
setConsumerKey(e.parameter.consumerKey);
setConsumerSecret(e.parameter.consumerSecret);
var app = UiApp.getActiveApplication();
app.close();
return app;
}
 
/**
* Authorize against Twitter. This method must be run prior to
* clicking any link in a script email. If you click a link in an
* email, you will get a message stating:
* "Authorization is required to perform that action."
*/
function authorize() {
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl(
"https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"method": "GET",
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
var result = UrlFetchApp.fetch(
"http://api.twitter.com/1/account/verify_credentials.json",
requestData);
var o = Utilities.jsonParse(result.getContentText());
ScriptProperties.setProperty("STORED_SCREEN_NAME", o.screen_name);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.