My First Google Script

This is my first simple Google script. In practice, this script is really is a simple JavaScript app which is being hosted by Google instead of inside a regular web server.

It runs on a simple timer, sends an http request to a static html file, parses for elements, selects one at random, and posts it to twitter.

The script runs as a Google script (see https://developers.google.com/apps-script/overview), but it also requires a corresponding twitter app (see dev.twitter.com and apps.twitter.com). For the app created, represented in the script at TWITTER_CONSUMER_KEY and TWITTER_CONSUMER_SECRET, the twitter app needs to be able to “Sign in with Twitter” and needs “Read and write” access.

Code



//  Get your own Twitter Keys from dev.twitter.com and fill them here

var TWITTER_CONSUMER_KEY     =  "xxxxxxxxxxxxxxxxxxx";
var TWITTER_CONSUMER_SECRET  =  "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";


//  This is the main function. Pleas do not modify this code.

function initialize() {  
  uninstall();
  createTriggers();
  sendTweet();  
}

function runProgram() {
  initialize();
}

function uninstall() {    
  
  var triggers = ScriptApp.getScriptTriggers();
  
  for (i=0; i<triggers.length; i++) {
    ScriptApp.deleteTrigger(triggers[i]);
  }  
    
}

function createTriggers() {
    
  ScriptApp.newTrigger('sendTweet')
   .timeBased()
   .everyDays(2)
   .create();  
}

function sendTweet() {
  var qurl = 'https://dl.dropboxusercontent.com/u/7115756/Quotes.html'
  var response = UrlFetchApp.fetch(qurl);
  
  quote = doACite(response);
  //quote = doHTML(response);
  Logger.log(quote);

  postTweet(quote); //works
  
}

function doACite(httpresponse) {
  var qxml = httpresponse.getContentText();
  var qdoc = XmlService.parse(qxml);
  var html = qdoc.getRootElement();
  
  var cites = getElementsByTagName(html, 'quote');
  
  return cites[Math.floor(Math.random()*cites.length)].getValue();
}


function doHTML(responseDetails) {
  //tagline_array = responseDetails.responseText.split('%');
  text_array = responseDetails.getContentText().split('== Quotes ==');
  tagline_array = text_array[1].split('~~~');
  
  quote = tagline_array[Math.floor(Math.random()*tagline_array.length)];
  
  return quote
}

function getElementsByClassName(element, classToFind) {  
  var data = [];
  var descendants = element.getDescendants();
  descendants.push(element);  
  for(i in descendants) {
    var elt = descendants[i].asElement();
    if(elt != null) {
      var classes = elt.getAttribute('class');
      if(classes != null) {
        classes = classes.getValue();
        if(classes == classToFind) data.push(elt);
        else {
          classes = classes.split(' ');
          for(j in classes) {
            if(classes[j] == classToFind) {
              data.push(elt);
              break;
            }
          }
        }
      }
    }
  }
  return data;
}


function getElementsByTagName(element, tagName) {  
  var data = [];
  var descendants = element.getDescendants();  
  for(i in descendants) {
    var elt = descendants[i].asElement();     
    if( elt !=null && elt.getName()== tagName) data.push(elt);      
  }
  return data;
}

//post tweet
function postTweet(msg) {
  oAuth();
  Logger.log('oAuth complete');
  var status='Test tweet';
  var options = {
    "method": "post",
    "oAuthServiceName": "twitter",
    "oAuthUseToken": "always",
    "payload":{"status":msg}
  };
  var url = "https://api.twitter.com/1.1/statuses/update.json";
  Logger.log('begin post');
  var request = UrlFetchApp.fetch(url, options);
  Logger.log('post complete');
}

//  The script uses OAuth to connect with your Twitter account
//  Thus, you need not share your login credentials with anyone

function oAuth() {
//  var CONSUMER_KEY = "*************************";
//  var CONSUMER_SECRET = "**************************************************";
  ScriptProperties.setProperty("TWITTER_CONSUMER_KEY", TWITTER_CONSUMER_KEY);
  ScriptProperties.setProperty("TWITTER_CONSUMER_SECRET", TWITTER_CONSUMER_SECRET);
  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/authenticate");
  oauthConfig.setConsumerKey(ScriptProperties.getProperty("TWITTER_CONSUMER_KEY"));
  oauthConfig.setConsumerSecret(ScriptProperties.getProperty("TWITTER_CONSUMER_SECRET"));
  var options = {muteHttpExceptions: true,oAuthServiceName:'twitter',oAuthUseToken:'always'}
  var url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
  var response = UrlFetchApp.fetch(url, options).getContentText();
  Logger.log(response);
}

function encodeURL(string){
   var tmp =  encodeURIComponent(string);
   tmp = tmp.replace(/!/g,'%21');
   tmp = tmp.replace(/\*/g,'%2A');
   tmp = tmp.replace(/\(/g,'%28');
   tmp = tmp.replace(/\)/g,'%29');
   tmp = tmp.replace(/'/g,'%27');
   return tmp;
}

A Few References

Advertisements