Twitter APIリミットでrescueに返されるerrorオブジェクト - 別館 子子子子子子(ねこのここねこ)で記載したように、Twitter::REST::Client#followers を使ってフォロワーの名前を取得しようとすると、20人毎にAPIを消費してしまいます。そしてこのAPIの上限は15回/15分です。直ぐに尽きてしまいます。
適切なやりかた
Twitter::REST::Client#follower_idsメソッドを使います。これならば1API毎に5000idまで取得できます。
ただ、取得できるのはidであってアカウント名ではありません。ここで欲しいのはアカウント名です。
ということで、Twitter::REST::Client#usersメソッドにid配列を渡して、各アカウントの情報を取得します。100idでAPIを1つ消費します。
そして、このusers(正確には/users/lookup)APIの上限は180回/15分です。普通の使い方では尽きないでしょう。
スクリプト例
follower_idsで全idを取得し、そこから100id毎の配列を作ってusersメソッドに渡します。これにより100アカウント分のTwitter::Userの配列オブジェクトを取得します。これを全てまとめればOKです。
#!/usr/bin/env ruby # coding: utf-8 require 'twitter' client = Twitter::REST::Client.new(KEY_SECRET_HASH) #followers = [] follower_ids = client.follower_ids("riocampos").to_a begin # 2015/10/29更新 followers = follower_ids.each_slice(100).to_a.inject ([]) do |users, ids| users.concat(client.users(ids)) end # 以前書いたものも履歴として残しておきます… # loop_count = (follower_ids.size - 1) / 100 + 1 # loop_count.times do # ids_temp = follower_ids.pop(100) # accounts_temp = client.users(ids_temp) # followers.concat(accounts_temp) # end followers.each_with_index{ |user, i| puts "#{i + 1}: #{user.screen_name}" } rescue Twitter::Error::TooManyRequests => error sleep error.rate_limit.reset_in retry end
おまけ:フォローしているアカウント名の取得
Twitter::REST::Client#friend_idsメソッドを使います。
後半のみ。
#followings = [] following_ids = client.friend_ids("riocampos").to_a begin # 2015/10/29更新 followings = following_ids.each_slice(100).to_a.inject ([]) do |users, ids| users.concat(client.users(ids)) end # 以前書いたものも履歴として残しておきます… # loop_count = (following_ids.size - 1) / 100 + 1 # loop_count.times do # ids_temp = following_ids.pop(100) # accounts_temp = client.users(ids_temp) # followings.concat(accounts_temp) # end followings.each_with_index{ |user, i| puts "#{i + 1}: #{user.screen_name}" } rescue Twitter::Error::TooManyRequests => error sleep error.rate_limit.reset_in retry end