LoginSignup
66
63

More than 5 years have passed since last update.

Twitter API (Ruby)

Last updated at Posted at 2012-12-26

TwitterAPIの使い方です。bot作成など、色々遊べます。
OAuth認証の記事はたくさんあったけど、APIの記事はなかったので。

追記:Qiita「TwitterAPI Devise連携/グラフ可視化/データの効率的格納/API高速化」 にて続きを書きました。

できること

TwitterクライアントやBotを作るための機能は揃っています。

例1:呟く

hoge.rb
Twitter.update("api_testなう")

例2:特定ユーザーがフォローしているID一覧を取得

hoge.rb
Twitter.friend_ids("mosa_siru")
#フォローしてるIDを表示。実行結果:
@attrs=
  {:previous_cursor=>0,
   :next_cursor_str=>"0",
   :previous_cursor_str=>"0",
   :ids=>
    [421856832,
     373248221,
     80331643,
     752440345,
.
.
.

導入

Gem

gem  'twitter'

最新バージョン(4.3)は最新のTwitterAPI ver1.1対応となります。

gem  'twitter', '3.7.0'

TwitterAPI ver1.0対応となります。

$bundle installで準備完了。

API制限

ver1.1

1アカウントのエンドポイントごとに、15分で15回or180回となります。(1時間あたり60回または720回)
ツイートの表示やユーザー検索などは多くできます。

ver1.0

1アカウントごとに、1時間あたり350リクエスト。場合によっては多くとれますが、2013年3月初旬までしか使えません。

認証

Twitter developerにてログイン後、右上のアイコンから「My Application」→「Create a new application」で詳細を入力します。

  • websiteはhttp://localhostは許可されないですが、http://192.168.0.1:8080などは大丈夫です。
  • Callback URLは適当でいいので必ず書いてください。

登録後、「Create my access token」でアクセストークンを得ます。キーとトークンの情報をメモします。

次に取得したトークン等を読み込ませます。Railsなら以下に書くと良いでしょう。

config/initializers/twitter.rb
Twitter.configure do |config|
  config.consumer_key = "YOUR_CONSUMER_KEY"
  config.consumer_secret = "YOUR_CONSUMER_SECRET"
  config.oauth_token = "YOUR_OAUTH_TOKEN"
  config.oauth_token_secret = "YOUR_OAUTH_TOKEN_SECRET"
end

認証できていない場合、APIを叩いても「Bad Authentication data」となります。(APIver1.1は認証必須です)

参考

66
63
3

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
66
63