Rubyで特定ユーザのTimelineを取得する方法。
目的
pso2の緊急クエストの発生間隔・発生エリアに偏りがあるか調べる。
特定のユーザのつぶやきを取得して統計処理にかける。
方法
ruby(>=2.0)とgem twitter(>=5)を使って取得する。
gem twitter(>=5)の変更点
主に以下の2点の変更で、以前のコードだと動かない。
認証方法がスレッドセーフになった
公式サイトの説明は下記参照。
https://github.com/sferik/twitter#configuration
抜粋すると、今までの認証方法はスレッドセーフじゃないから止めた。
代わりにTwitter::REST::Clientを使ってくれと書いてある。
Streaming(UserStrema)モードの追加
認証方法はRESTとほぼ同じで、Twitter::Streaming::Clientを使う。
インストール方法
gem install twitter
コードの例
参考:https://github.com/sferik/twitter#usage-examples
get_tl.rb
require 'twitter'
@client = Twitter::REST::Client.new do |config|
config.consumer_key = ''
config.consumer_secret = ''
config.access_token = ''
config.access_token_secret = ''
end
# 特定ユーザのtimeline取得
@client.user_timeline("pso2_emg_hour").each do |timeline|
puts @client.status(timeline.id).text
end
# 特定ユーザのtimelineを件数(2件)指定して取得
@client.user_timeline("pso2_emg_hour", { count: 2 } ).each do |timeline|
puts @client.status(timeline.id).text
end
Timeline取得メソッドのオプション
API
user_timeline(user, options = {})
- user
Integer/String/URIのいずれか
- options
以下のオプションのハッシュ
オプション名 | 型 | 意味 |
---|---|---|
:since_id | Integer | Returns results with an ID greater than (that is, more recent than) the specified ID. |
:max_id | Integer | Returns results with an ID less than (that is, older than) or equal to the specified ID. |
:count | Integer | 遡る件数を指定する。200以下でなければならない。 |
:trim_user | Boolean/Integer/String | Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1 |
:exclude_replies | Boolean/Integer/String | This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets - this is because the count parameter retrieves that many tweets before filtering out retweets and replies |
:contributor_details | Boolean/Integer/String | Specifies that the contributors element should be enhanced to include the screen_name of the contributor. |
:include_rts | Boolean/Integer/String | Specifies that the timeline should include native retweets in addition to regular tweets. Note: If you're using the trim_user parameter in conjunction with include_rts, the retweets will no longer contain a full user object. |
参考:rdoc生成
rubyをrbenvにてインストールしている場合、
現状の最新版であれば以下のように生成する。
でも、出力はできるけどソース読んだ方が早かった。。。
cd .rbenv/versions/2.1.4/lib/ruby/gems/2.1.0/gems/twitter-5.13.0/lib/twitter
rdoc twitter --op ~/twitter/doc
Twitter::Rest::Timelinesを参照する。
番外編:Pryを使って投稿
読み込み
> require "./get_tl.rb"
投稿もできる
> @client.update 'test'