Twitter Ruby function to find all friends and followers of a user

Posted by chad on March 22, 2009

The twitter gem doesn’t do a good job of allowing unauthenticated queries, so I have to make a specific request to the twitter API to do this.

If you pass in Scrap.friendsandfollowers(‘rubyrescue’) you’ll get about 6000 ids. Anything better than a depth of ’1′ and you’ll need an un-rate-limited account w/Twitter as it will take more than 100 requests and they limit requests to 100/hour.

require 'twitter'
require 'net/http'
require 'json'

class Scrap

  def self.friendsandfollowers(users,depth=0,type = :all)
    users = [users] unless users.is_a?(Array)

    puts "at level #{depth}"

    newusers = []
    [:friends,:followers].each do |t|
      if [:all,t].include?(type)
        users.each() do |u|
          puts "looking for #{t.to_s.pluralize} of #{u}"
          newusers += JSON.parse(Net::HTTP.get(URI.parse("http://twitter.com/#{t}/ids/#{u}.json")))
        end
      end
    end

    newusers.uniq!

    if depth == 0
      return newusers
    else
      newusers.each() do |u|
        users += self.friendsandfollowers(u,depth-1,type)
      end
      return users.uniq
    end

  end

end
Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

Comments