user1476028
user1476028

Reputation: 49

Twitter rate limit hit while requesting friends with ruby gem

I am having trouble printing out a list of people I am following on twitter. This code worked at 250, but fails now that I am following 320 people.

Failure Description: The code request exceeds twitter's rate limit. The code sleeps for the time required for the limit to reset, and then tries again.

I think the way it's written, it just keeps retrying the same entire rejectable request, rather than picking up where it left off.

MAX_ATTEMPTS = 3
num_attempts = 0
begin
    num_attempts += 1
    @client.friends.each do |user|
        puts "#{user.screen_name}"
    end
rescue Twitter::Error::TooManyRequests => error
    if num_attempts <= MAX_ATTEMPTS
        sleep error.rate_limit.reset_in
        retry
    else
        raise
    end
end

Thanks!

Upvotes: 0

Views: 1931

Answers (2)

user1476028
user1476028

Reputation: 49

The following code will return an array of usernames. The vast majority of the code was written by the author of: http://workstuff.tumblr.com/post/4556238101/a-short-ruby-script-to-pull-your-twitter-followers-who

First create the following definition.

def get_cursor_results(action, items, *args)
  result = []
  next_cursor = -1
  until next_cursor == 0
    begin
      t = @client.send(action, args[0], args[1], {:cursor => next_cursor})
      result = result + t.send(items)
      next_cursor = t.next_cursor
    rescue Twitter::Error::TooManyRequests => error
      puts "Rate limit error, sleeping for #{error.rate_limit.reset_in} seconds...".color(:yellow)
      sleep error.rate_limit.reset_in
      retry
    end
  end
  return result  
end

Second gather your twitter friends using the following two lines

friends = get_cursor_results('friends', 'users', 'twitterusernamehere')
screen_names = friends.collect{|x| x.screen_name}

Upvotes: 3

Related Questions