Created
March 11, 2009 02:35
-
-
Save siuying/77262 to your computer and use it in GitHub Desktop.
find my twitter first follows first follows first ...
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
require 'yaml' | |
require 'twitter' | |
require 'graphviz' | |
config = YAML.load_file('twitter.yml') | |
twit = Twitter::Base.new(config['username'], config['password']) | |
user_name = config['username'] | |
def load_user(twit, user_name) | |
cache = YAML.load_file('user.yml') || {} | |
if cache[user_name].nil? | |
cache[user_name] = twit.user(user_name) | |
File.open('user.yml', 'w+' ) do |out| | |
YAML.dump(cache, out) | |
end | |
end | |
cache[user_name] | |
end | |
def first_friend(twit, user) | |
fcount = user.friends_count | |
fpage = (fcount.to_f / 100).ceil | |
last_user = twit.friends_for(user.screen_name, :page => fpage).last | |
last_user = load_user(twit, last_user.screen_name) # get extended user info | |
end | |
def tree_has_loop?(tree) | |
tree.flatten.inject(Hash.new(0)) {|h,x| h[x]+=1;h}.collect(){|x,y| y > 2}.include?(true) | |
end | |
def build_user_tree(twit, user_name) | |
tree = [] | |
current_user = load_user(twit, user_name) | |
while !current_user.nil? && !tree_has_loop?(tree) do | |
last_user_name = current_user.screen_name | |
current_user = first_friend(twit, current_user) | |
current_user_name = current_user.screen_name rescue "" | |
puts "#{last_user_name} - #{current_user_name}" | |
tree << [last_user_name, current_user_name] unless current_user.nil? | |
end | |
tree | |
end | |
def draw_tree(tree=[]) | |
# initialize new Graphviz graph | |
g = GraphViz::new( "structs", "type" => "graph" ) | |
g[:rankdir] = "TB" | |
g.node[:fontname] = "Trebuchet MS" | |
g.edge[:dir] = "forward" | |
g.edge[:arrowsize]= "0.5" | |
tree.flatten.uniq.each do |user| | |
g.add_node(user).label = user | |
end | |
tree.each do |users| | |
g.add_edge(users[0], users[1]) | |
end | |
g.output( "output" => "png", :file => "graph.png" ) | |
end | |
tree = build_user_tree(twit, user_name) | |
puts tree | |
draw_tree(tree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment