Rails4でTwitterStreamingAPIを使う その1
Ruby2.0, Rails4で確認
tweetstream gemを使用してTwitterStreamingAPIを試してみました。
今回は
目標:ハッシュタグがyoutubeとなっているtweetを取得してlogに表示する
という所までやってみたいと思います。
Twitterアプリケーションの作成
- Twitter Developers にログイン 
- ヘッダーの右端にあるアイコンをクリックして「My applications」クリック 
- 「Create a new application」をクリックしてアプリ作成画面へ 
- 必要項目を入力してアプリケーションを作成 
- アプリケーション作成後、ページ下部にある「Create my access token」をクリック
- しばらくしてページをリロードするとアクセストークンが表示されるので「Consumer key」、「Consumer secret」、「Access token」、「Access token secret」をメモしておきます
Railsアプリケーションの作成
- アプリ名はstreaming_sampleとします。
``bash rails new streaming_sample ```
- Gemfileにtweetstreamを追加。
# Gemfile
gem 'tweetstream'- initializerにtweetstream設定を追加
# config/initializers/tweetstream.rb
TweetStream.configure do |config|
  config.consumer_key       = 'YOUR KEY'
  config.consumer_secret    = 'YOUR SECRET'
  config.oauth_token        = 'YOUR ACCESS TOKEN'
  config.oauth_token_secret = 'YOUR SECRET TOKEN'
  config.auth_method        = :oauth
endtweet収集の部分をdaemon化
- script/twitter_streaming.rbを作成
# mkdir script
# script/twitter_streaming.rb
ENV["RAILS_ENV"] ||= "development"
root = File.expand_path(File.join(File.dirname(__FILE__), '..'))
require File.join(root, "config", "environment")
daemon = TweetStream::Daemon.new('twitter_streaming', :log_output => true)
daemon.on_inited do
  ActiveRecord::Base.connection.reconnect!
  daemon_logger = Logger.new(File.join(Rails.root, "log", "stream.log"))
  Rails.logger = ActiveRecord::Base.logger = daemon_logger
  Rails.logger.debug "Listening..."
end
daemon.on_error do |message|
  Rails.logger.error message
end
daemon.track('#youtube') do |tweet|
  Rails.logger.debug tweet.text
enddaemonスクリプトに関しては公式ドキュメントに書かれていたものを参考にしつつ、logファイルにうまく書き込めなかったので少しいじりました。
- daemonを起動
RAILS_ENV=development ./bin/rails runner script/twitter_streaming.rb start- ログを確認すると#youtubeを含むtweetが記録されていきます
tail -f log/stream.log
# #youtubeに関するtweetが随時記録されていく- daemonの停止はstopでできます
RAILS_ENV=development ./bin/rails runner script/twitter_streaming.rb stop- その他のdaemon用オプションは以下
RAILS_ENV=development ./bin/rails runner script/twitter_streaming.rb
ERROR: no command given
Usage: twitter_streaming   -- 
* where  is one of:
  start         start an instance of the application
  stop          stop all instances of the application
  restart       stop all instances and restart them afterwards
  reload        send a SIGHUP to all instances of the application
  run           start the application and stay on top
  zap           set the application to a stopped state
  status        show status (PID) of application instances
* and where  may contain several of the following:
    -t, --ontop                      Stay on top (does not daemonize)
    -f, --force                      Force operation
    -n, --no_wait                    Do not wait for processes to stop
Common options:
    -h, --help                       Show this message
        --version                    Show version今回は「#youtube」を検索条件としましたが、どういうキーワードを検索条件に指定すべきか迷ったときは、 Streaming API keyword matchingでいろいろ試してみるといいと思います。
tweetstreamのその他の機能に関しては、 tweetstreamのドキュメントとと Twitterの公式ドキュメントを参照ください。
次回は取得したtweetをMongoDBに保存するようにしてみたいと思います。