LoginSignup
5
3

More than 5 years have passed since last update.

Rubyで新しい順から、ほしい数だけtweetを取得する

Last updated at Posted at 2018-01-30

はじめに

tweetの内、数を指定して、新しい順からtweetを抽出したかったのでRubyで書いてみました。今回は認証済みのユーザをユーザータイムラインを使っていますが、ユーザを指定すれば他のtweet群でも同じような処理ができると思います。

gem

使うgemはtwitterです
twitter gem: GitHub

gem install twitter

認証

以下のコードで認証を行います。

client = Twitter::REST::Client.new do |config|
  config.consumer_key        = "YOUR_CONSUMER_KEY"
  config.consumer_secret     = "YOUR_CONSUMER_SECRET"
  config.access_token        = "YOUR_ACCESS_TOKEN"
  config.access_token_secret = "YOUR_ACCESS_SECRET"
end

tweetを取得

コードは以下の通りです。

def get_tweets(count)
    # countに満たないtweet数でも、エラーは起きない
    epoc_count = (count / 200) + 1

    tweets = [@client.user_timeline(count: 1)][0]
    epoc_count.times do
      @client.user_timeline(count: 200, max_id: tweets.last.id-1).each do |t|
        if tweets.count == count
          break
        end
        tweets << t
      end
    end

    # Array
    tweets.map! {|t| t.text}
  end

count引き数で欲しい数を指定しています。ちなみに抽出先ユーザのtweet数がcountに満たない場合でもエラーは起きません。ですが、本当はそこで分岐した方が良いかもしれません。(総tweet数はすぐ取れるのかな?)

@client.user_timeline(count: 200, max_id: tweets.last.id-1)という部分で、ユーザのタイムラインを抽出しています。一度のリクエストで200件までしか取れないみたいです。なのでmax_idを指定して、どのtweetから200件かを抽出する度に変えます。それを繰り返すことで、順々に古いものを抽出しています。

tweets = [@client.user_timeline(count: 1)][0]

ちなみにここでは一番新しいtweetを配列の初期化の時に入れているのですが、これは一番新しいtweetのmax_idが分からないため無理やりこうしました... 

t = TwitterContent.new()
tweets = t.get_tweets(140)

あとはこの様に指定すれば、最新から件数分のtweetを取得できます。

参考

Twitter API
Twitter gem Document
Twitter gem GitHub
書いてる途中に気づきましたが、以前にもPythonで同じようなことしてました...

5
3
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
5
3