LoginSignup
0
0

More than 3 years have passed since last update.

Ruby でツイートを取得する

Posted at

何番煎じ?

twitter gem を使います。Twitter の開発者登録とアプリケーション登録は済ませているものとします。

以下は irb 上で動作確認をしました。

認証

APIキーとAPIシークレットによって認証をします。Example を読む限り、bearer token を使っている方の認証のはずです。(他にも認証方法があり、目的によって使い分けます。)

client = Twitter::REST::Client.new do |config|
  config.consumer_key    = "YOUR_API_KEY"
  config.consumer_secret = "YOUR_API_SECRET"
end

特定のユーザーのツイートは client.user_timeline (ref) で取得できます。ユーザーIDかユーザーのスクリーンネームで取得できます。

tweets = client.user_timeline(
  user_id, {
    :count => 200,
    :include_rts => false
  }
)

:count の max は 200 で、Twitter API の制限としては3200個まで取得できるので、 200以上昔のものを取得したい場合はたぶん :max_id を指定すればいいと思います。

:include_rts を切れば RT を除外できます。

Array<Twitter::Tweet> で返ってきます。

ツイートオブジェクトのメソッドは色々あり、ここではとりあえず本文をみてみましょう。

tweets.map do |tweet|
  tweet.text
end

てな感じです。

0
0
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
0
0