GUIビルダー使ってTwitterクライアントもどき

暑さには弱いです。Google Apps Scriptの季節です。

GUI Builder

function initTwitter() {
  var oAuthConf = UrlFetchApp.addOAuthService("twitter");
  oAuthConf.setAccessTokenUrl("http://api.twitter.com/oauth/access_token");
  oAuthConf.setRequestTokenUrl("http://api.twitter.com/oauth/request_token");
  oAuthConf.setAuthorizationUrl("http://api.twitter.com/oauth/authorize");
  oAuthConf.setConsumerKey("アレ");
  oAuthConf.setConsumerSecret("アレ");
}

function getLatestTweet() {
  var options = {
    "oAuthServiceName": "twitter",
    "oAuthUseToken": "always",
    "method": "GET"
  };
  var result = UrlFetchApp.fetch("http://api.twitter.com/1/statuses/home_timeline.json", options);
  var o = Utilities.jsonParse(result.getContentText());
  
  var tw = [];
  for(var i = 0; i < 5; i++) {
    tw[i] = {"url": o[i]["user"]["profile_image_url"], "tweet": o[i]["text"]};
  }
  
  return tw;
}

// スプレッドシートで表示するとき呼ぶ
function showGui(url, tweet) {
  var app = UiApp.createApplication();
  app.add(app.loadComponent("MyTwitter"));
  
  var text = app.getElementById("text1");
  //text.setText(tweet);
  var icon = app.getElementById("icon1");
  //icon.setUrl(url);
  
  SpreadsheetApp.getActiveSpreadsheet().show(app);
  return app;
}

function myTwitter() {
  initTwitter();
  var twi = getLatestTweet();
  showGui(twi.url, twi.tweet);
}

// サービスとして公開するとき呼ぶ
function doGet() {
  var app = UiApp.createApplication();
  app.add(app.loadComponent("MyTwitter"));
  
  initTwitter();
  var twi = getLatestTweet();
  
  for(var i = 0; i < twi.length; i++) {
    var text = app.getElementById("text" + (i+1));
    var icon = app.getElementById("icon" + (i+1));
    text.setText(twi[i].tweet);
    icon.setUrl(twi[i].url);
  }
  
  return app;
}

サービスとして公開したらこうなります。 https://spreadsheets.google.com/macros/exec?service=AKfycbxCqvY-oTA4DsC75d1M1QYBkeSGvhy2yi0