LoginSignup
63

More than 5 years have passed since last update.

Twitter Search APIの使い方

Last updated at Posted at 2014-09-02

ツイートを検索するには、Twitter Search APIを使用します。
Twitter Search APIとは、twitterに投稿されたつぶやきを柔軟に検索し、取得するためのサービスです。 キーワード検索、ツイートされた位置情報、最近人気のツイート、最も人気のあるツイートなど柔軟な検索ができます。

Twitter Search APIの試し方

本来であればTwitter開発者登録し、Twitterアプリを登録し、OAuth認証する必要がありますが、こちらからすぐに試すことができます。

https://dev.twitter.com/console
スクリーンショット 2014-09-02 18.51.13.png

まずは「Authentication」から「OAuth 1」を選択します。
下のようなポップアップが出てくるのでTwitterアカウントでログインしましょう

スクリーンショット 2014-09-02 18.52.50.png

認証ができたら「Select an API method」から「/search/tweets.json」を選択します。

これでさっそくリツイートを取得していきましょう。

画像ありツイートを取得する

スクリーンショット 2014-09-02 18.56.39.png

queryの中に以下を入れると画像ありツイートのみを取得することができます。

filter:images

また「include_entities」を「true」にしておきましょう。

kobito.1409652221.165136.png

画像のURLは以下の場所に入っています。

kobito.1409652302.890232.png

javascriptで取得する場合は取得したjsonを以下のように処理すると画像だけの配列として取得できます。

var images = json.statuses.map(function(d){ return d.entities.media[0].media_url;});

画像ありURLありツイートを取得する

kobito.1409652705.409969.png

q に「http」を足せばツイート内のURLを取得できます。
URLは以下の場所に入っています。

kobito.1409652793.135494.png

javascriptで取得する場合は取得したjsonを以下のように処理すると画像とURLの入ったオブジェクトの配列として取得できます。

var tweets = json.statuses.map(function(d){ return { 
media_url : d.entities.media[0].media_url,
expanded_url : d.urls[0].expanded_url
};});

リツイート数を取得する

私は画像が入っているかつツイートにURLが含まれているかつリツイートが多いツイートを取得したかったので、qに「RT」を足します。

kobito.1409653108.700607.png

これだとあるツイートのリツイートが重複取得されます。
しかし、
ドキュメントを見てみましたが、リツイートが多い順で取得がなかなか見つからなかったので、API側ではなく、リツイートが多い順でのソートはコードで処理する必要がありそうです。
リツイート数は以下の場所に入っています。

kobito.1409653266.420664.png

リツイート元の親ツイートは「retweeted_status」に入っています。

項目 コード
ツイートID retweeted_status.id_str
名前 retweeted_status.user.name
プロフィール画像 retweeted_status.user.profile_image_url
本文 retweeted_status.text
ツイート日時 retweeted_status.created_at

リツイートを取得し、重複を消すにはjavascriptではこう書いてみました。

//ツイートidを貯める
var tweet_ids = [];
var tweets = [];
json.statuses.forEach(function(d){
  //リツイートされているか、ツイートが重複していないか確認
  if(d.retweeted_status !== undefined && 
   tweet_ids.indexOf(d.retweeted_status.id_str) < 0 ){
    // 重複していない場合、tweet_idsを貯める
    tweet_ids.push(d.retweeted_status.id_str);
    tweets.push({
       media_url : d.entities.media[0].media_url,
       expanded_url : d.urls[0].expanded_url,
       name : d.retweeted_status.user.name,
       prof_image:d.retweeted_status.user.profile_image_url,
       retweet_count:d.retweet_count+"RT"
    });

    //リツイートが多い順にソート
    tweets.sort(function(a, b) {
      return (a.retweet_count > b.retweet_count) ? -1 : 1;
    });
  }
});

終わりに

Javascriptのコードを載せましたが、
OAuth認証をしないといけないので、簡単には使えないのがWEBアプリや アプリ開発時にちょっと大変ですね。
今回はTinitaum mobileを使ってコードを試していました。
次はJavascriptでOAuth認証するのを試してみます。

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
63