使用 ruby​​ gem 请求好友时,推特​​速率受到限制 [英] Twitter rate limit hit while requesting friends with ruby gem

查看:27
本文介绍了使用 ruby​​ gem 请求好友时,推特​​速率受到限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法打印出我在 Twitter 上关注的人的列表.此代码在 250 人时有效,但现在我正在关注 320 人,因此失败了.

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.

失败描述:代码请求超出了 Twitter 的速率限制.代码在重置限制所需的时间内休眠,然后重试.

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

谢谢!

推荐答案

以下代码将返回一组用户名.绝大多数代码由以下作者编写:http://workstuff.tumblr.com/post/4556238101/a-short-ruby-script-to-pull-your-twitter-followers-who

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

首先创建以下定义.

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

使用以下两行第二次收集您的推特好友

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

这篇关于使用 ruby​​ gem 请求好友时,推特​​速率受到限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆