LoginSignup
4
6

More than 5 years have passed since last update.

はじめに

miuraと言います。
岩手県立大学を2008年3月に卒業して、愛知で組込みソフト業界で働いています。

事の発端

Twitterアカウントに対して、プロモーションをかけるという話があり、アカウントのリストをGoogleスプレッドシートで共有してリストの更新、連絡した/してないを管理する事になりました。
いちいち手で更新するのは面倒だなと思い、Twitter APIでリストを作成してみようと考えました。

いざ、書いてみる

使う言語

ExcelがVBAでプログラミングできるように
Googleスプレッドシートを操作するための言語としてGoogle Apps Scriptがあります。

Google Apps Scriptで使えるTwitter APIのライブラリ

少し調べたら、OAuth1 for Apps Scriptっていうのがありました。

できました

OAuth1 for Apps Scriptの使い方が大体分かったら、そんなに難しくなかったです。
ちょっと長いですが、そのまま載っけます。

コード.gs
function search() {
  var service = getTwitterService();

  if (service.hasAccess()) {
    var url = 'https://api.twitter.com/1.1/users/search.json';
    url += '?q=' + encodeURIComponent("IPU");

    var doc = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = doc.insertSheet();
    var cell = sheet.getRange("a1");
    var rows = 2;

    for (var page = 1; page <= (1000/20); page++) {
      var response = service.fetch(url + '&page=' + page); /* ページを指定してデータを取得 */
      var results = JSON.parse(response.getContentText()); /* 取得したデータをJSON形式に変換 */
      for (var i = 0; i < results.length; i++) {
        var cols = 1;
        cell.offset(rows, cols++).setValue('=hyperlink("twitter.com/' + results[i]["screen_name"] + '";"' + results[i]["screen_name"] + '")');
        cell.offset(rows, cols++).setValue(results[i]["name"]);
        cell.offset(rows, cols++).setValue(results[i]["location"]);
        cell.offset(rows, cols++).setValue(results[i]["description"]);
        rows++;
      }
    }
  } else {
    var authorizationUrl = service.authorize();
    Logger.log('Please visit the following URL and then re-run the script: ' + authorizationUrl);
  }
}

/* コールバック関数 */
/* https://github.com/googlesamples/apps-script-oauth1 */
/* からほぼ流用 */
function authCallback(request) {
  var service = getTwitterService();
  var isAuthorized = service.handleCallback(request);
  if (isAuthorized) {
    return HtmlService.createHtmlOutput('Success! You can close this page.');
  } else {
    return HtmlService.createHtmlOutput('Denied. You can close this page');
  }
}

/* Twitterサービスを使うための設定 */
/* https://github.com/googlesamples/apps-script-oauth1 */
/* からほぼ流用 */
function getTwitterService() {
  var service = OAuth1.createService('twitter');
  service.setAccessTokenUrl('https://api.twitter.com/oauth/access_token')
  service.setRequestTokenUrl('https://api.twitter.com/oauth/request_token')
  service.setAuthorizationUrl('https://api.twitter.com/oauth/authorize')

  service.setConsumerKey("*************************");
  service.setConsumerSecret("**************************************************");
  service.setProjectKey("**************************-******");
  service.setCallbackFunction('authCallback');

  service.setPropertyStore(PropertiesService.getScriptProperties());
  return service;
}

 実行結果

"IPU"でやると、こんな感じ。
岩手県立大学の中では、総合政策が1番上に出てますね。意外。

スクリーンショット 2015-11-30 22.56.37.png

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6