Twitter rate limit hit while requesting friends with ruby gem

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 13:37:43

问题


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!


回答1:


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}



回答2:


try using a cursor: http://rdoc.info/gems/twitter/Twitter/API/FriendsAndFollowers#friends-instance_method (for example, https://gist.github.com/kent/451413)



来源:https://stackoverflow.com/questions/16618037/twitter-rate-limit-hit-while-requesting-friends-with-ruby-gem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!