Created
November 19, 2009 19:54
-
-
Save hayesdavis/238994 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'grackle' | |
require 'redis' | |
# Shows the list of mutual followers between two Twitter users using Redis | |
# sets and set intersections. | |
# | |
# Usage: | |
# ruby mutual_followers screen_name1 screen_name2 [reset] | |
# | |
# Arguments | |
# screen_name1, screen_name2: | |
# the Twitter users to compare. Assumes both users are not protected. | |
# reset: | |
# re-fetch the followers for both names. If this is not set, the list of | |
# followers stored in Redis from any previous executions of this script | |
# will be used. | |
# | |
# Requirements/Limitations | |
# * You'll need Grackle and the redis Ruby gem. | |
# * Assumes you have Redis running on the default port | |
# * Assumes neither Twitter account is protected | |
# | |
$stdout.sync = true | |
def with_cursor(res_proc) | |
cursor = -1 | |
values = [] | |
until cursor == 0 do | |
res = res_proc.call(cursor) | |
if res | |
values += yield(res) | |
cursor = res.next_cursor | |
else | |
cursor = 0 | |
end | |
end | |
values | |
end | |
def get_followers(client,screen_name) | |
Proc.new do |cursor| | |
client.statuses.followers? :screen_name=>screen_name, :cursor=>cursor | |
end | |
end | |
def store_followers(client,redis,screen_name,reset=false) | |
key = "#{screen_name}/followers" | |
redis.delete(key) if reset | |
if redis.keys(key).empty? | |
print "Getting followers for #{screen_name} [" | |
with_cursor(get_followers(client,screen_name)) do |res| | |
print '.' | |
res.users.each do |user| | |
redis.set_add key, user.screen_name | |
end | |
end | |
puts ']' | |
else | |
puts "Followers for #{screen_name} already stored" | |
end | |
key | |
end | |
user1 = ARGV[0] | |
user2 = ARGV[1] | |
reset = ARGV[2] == 'reset' | |
client = Grackle::Client.new | |
redis = Redis.new | |
user1_key = store_followers(client,redis,user1,reset) | |
user2_key = store_followers(client,redis,user2,reset) | |
mutual_followers = redis.set_intersect(user1_key,user2_key).sort | |
puts "#{mutual_followers.size} Mutual Followers:\n#{mutual_followers.join(", ")}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment