Last active
August 29, 2015 14:27
-
-
Save mxhold/cd1ed000b0e6c9c9ecb6 to your computer and use it in GitHub Desktop.
Shows the interesting intersections of followers between two Twitter users
This file contains 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
#!/usr/bin/env ruby | |
# Usage: | |
# ./twitter_intersect username1 username2 | |
# You'll need to `gem install twitter` | |
require 'twitter' | |
# see: https://dev.twitter.com/oauth/overview/application-owner-access-tokens | |
@client = Twitter::REST::Client.new do |config| | |
config.consumer_key = "CONSUMER_KEY" | |
config.consumer_secret = "CONSUMER_SECRET" | |
config.access_token = "ACCESS_TOKEN" | |
config.access_token_secret = "ACCESS_SECRET" | |
end | |
def follower_ids(username) | |
@client.follower_ids(username).to_a | |
end | |
def following_ids(username) | |
@client.friend_ids(username).to_a | |
end | |
# this caches users to avoid looking up the same user | |
# multiple times | |
def users(user_ids) | |
@users ||= {} | |
result = [] | |
ids_to_lookup = [] | |
user_ids.each do |id| | |
if @users[id] # already in cache | |
result << @users[id] | |
else # will need to be fetched | |
ids_to_lookup << id | |
end | |
end | |
# fetch all non-cached users at once | |
new_users = @client.users(ids_to_lookup).to_a | |
# update cache | |
new_users.each do |user| | |
@users[user.id] = user | |
end | |
(result + new_users) | |
end | |
def print_users(user_ids) | |
users(user_ids) | |
.map { |user| [user.screen_name, user.name ] } | |
.map { |username, name| puts "#{username.ljust(20)}#{name}" } | |
end | |
def print_section(title, user_ids) | |
puts "## #{title} (#{user_ids.size})" | |
print_users(user_ids) | |
puts "\n" | |
end | |
username1 = ARGV.shift | |
username2 = ARGV.shift | |
user1_follower_ids = follower_ids(username1) | |
user1_following_ids = following_ids(username1) | |
user2_follower_ids = follower_ids(username2) | |
user2_following_ids = following_ids(username2) | |
print_section( | |
"Followers in common", | |
user1_follower_ids & user2_follower_ids | |
) | |
print_section( | |
"#{username1}'s followers that #{username2} follows", | |
user1_follower_ids & user2_following_ids | |
) | |
print_section( | |
"#{username2}'s followers that #{username1} follows", | |
user2_follower_ids & user1_following_ids | |
) | |
print_section( | |
"Both following", | |
user1_following_ids & user2_following_ids | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment