Convert Twitter JSON to RSS with Google Apps Script

This Google Script converts the JSON response from the Twitter API to standard RSS feeds. The results are cached for 60 minutes and all requests to Twitter are authenticated with OAuth, an important requirement of the Twitter API v1.1.

 

function JSONtoRSS(json, type, key) {

  oAuth();
  
  var options =
  {
    "method": "get",
    "oAuthServiceName":"twitter",
    "oAuthUseToken":"always"
  };
    
  try {

    var result = UrlFetchApp.fetch(json, options);    

    if (result.getResponseCode() === 200) {
      
      var tweets = Utilities.jsonParse(result.getContentText());
      
      if (tweets) {
                
        var len = tweets.length;
        
        var rss = "";
        
        if (len) {
          
          rss  = '<?xml version="1.0"?><rss version="2.0">';
          rss += ' <channel><title>Twitter ' + type + ': ' + key + '</title>';
          rss += ' <link>' + htmlentities ( json ) + '</link>';
          rss += ' <pubDate>' + new Date() + '</pubDate>';

          for (var i=0; i<len; i++) {
            
            var sender = tweets[i].user.screen_name;
            var tweet  = htmlentities ( tweets[i].text );
            
            rss += "<item><title>" + sender + ": " + tweet + "</title>";
            rss += " <author>" + tweets[i].user.name 
                            + " (@" + sender + ")</author>";
            rss += " <pubDate>" + tweets[i].created_at + "</pubDate>";
            rss += " <guid isPermaLink='false'>" + tweets[i].id_str + "</guid>";
            rss += " <link>https://twitter.com/" + sender 
                            + "/statuses/" + tweets[i].id_str + "</link>";
            rss += " <description>" + tweet + "</description>";
            rss += "</item>";                        
          }
          
          rss += "</channel></rss>";
          
          return rss;          
        }        
      }      
    }    
  } catch (e) {
    Logger.log(e.toString());
  }  
}

function doGet(e) {
   
  var a = e.parameter.action;
  var q = e.parameter.q;

  var feed = "https://api.twitter.com/1.1/";  
  
  switch (a) 
  {
    case "timeline": 
      feed += "statuses/user_timeline.json?screen_name=" + q;
      break;
    case "search":
      feed += "search/tweets.json?q=" + encodeURIComponent(q);
      break;
    case "favorites":
      feed += "favorites/list.json?screen_name=" + q;
      break;
    case "list":
      var i = q.split("/");
      feed += "lists/statuses.json?slug=" + i[1] + "&owner_screen_name=" + i[0];
      break;
    default:
      feed += "statuses/user_timeline.json";
      break;      
  }
  
  var id = Utilities.base64Encode(feed);
  
  var cache = CacheService.getPublicCache();
  var rss   = cache.get(id);
  
  if ( ! rss ) {
    rss = JSONtoRSS ( feed, a, q );
    cache.put(id, rss, 3600);
  }
  
  return ContentService.createTextOutput(rss)
    .setMimeType(ContentService.MimeType.RSS);
}

&nbsp;