Hi Erik,
As I feared, it appears the cursor does not survive the retry when hitting the rate limit, so I'm still very stuck on this.
Here is my updated code, using your technique to detect and sleep through a rate limit error:
https://gist.github.com/ronhornbaker/7817176When run on the twitter user with 54,000 friends, I ended up getting the first 3,000 friends written to the file repeatedly.
I'll paste the pertinent method here for convenience:
def fetch_all_friends(twitter_username, max_attempts = 100)
# in theory, one failed attempt will occur every 15 minutes, so this could be long-running
# with a long list of friends
num_attempts = 0
client = twitter_client
myfile = File.new("#{twitter_username}_friends_list.txt", "w")
running_count = 0
cursor = -1
while (cursor != 0) do
begin
num_attempts += 1
friends = client.friends(twitter_username, {:cursor => cursor, :count => 200} )
friends.each do |f|
running_count += 1
myfile.puts "\"#{running_count}\",\"#{f.name.gsub('"','\"')}\",\"#{f.screen_name}\",\"#{f.url}\",\"#{f.followers_count}\",\"#{f.location.gsub('"','\"').gsub(/[\n\r]/," ")}\",\"#{f.created_at}\",\"#{f.description.gsub('"','\"').gsub(/[\n\r]/," ")}\",\"#{f.lang}\",\"#{f.time_zone}\",\"#{f.verified}\",\"#{f.profile_image_url}\",\"#{f.website}\",\"#{f.statuses_count}\",\"#{f.profile_background_image_url}\",\"#{f.profile_banner_url}\""
end
puts "#{running_count} done"
cursor = friends.next_cursor
break if cursor == 0
rescue Twitter::Error::TooManyRequests => error
if num_attempts <= max_attempts
# NOTE: Your process could go to sleep for up to 15 minutes but if you
# retry any sooner, it will almost certainly fail with the same exception.
puts "#{running_count} done"
puts "Hit rate limit, sleeping for #{error.rate_limit.reset_in}..."
sleep error.rate_limit.reset_in
retry
else
raise
end
end
end
end
And here was the output to the console prior to me stopping the script:
3000 done
Hit rate limit, sleeping for 881...
6000 done
Hit rate limit, sleeping for 876...
9000 done
Hit rate limit, sleeping for 878...
Looks good, except when I checked the file, there were 3 copies of every friend. :(
-Ron