1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Automatically Following Followers on Twitter

Twitter With Ruby

By

The Twitter API can do anything you can do on the website. Though most Twitter scripts usually just get a timeline and do something with it, this script will go a little beyond that. A list of your followers will be retrieved, then a list of the people following you. Anyone not in your followers from the people following you will be added to your friends.

Section 1 is the standard Twitter gem set-up. Create a Twitter::Base object with your username and password and keep it in a variable called twitter for use later.

Section 2 starts to utilize the Twitter API, but first, a filter proc is created. Since we're not going to want all of the information about each user, we only want to keep the screen name and full name of each user. To do this, a simple call to map is used but, since we do it twice, we'll store the proc in a variable instead of passing it directly to the function. This prevents us from repeating ourselves, and makes it easier to make changes. Note that when map is called, the filter proc isn't simply passed as an argument, but the map(&filter) syntax is used. This is equivalent to placing a block literal after the function call.

Section 3 is really simple. Since the two arrays of users are just arrays, the minus operator can be used. The users we're interested in are the your followers minus your friends. For each one in this new list, print their usernames and URLs, then add them to your friends using the create_friendship method.

That's the whole script. If you ignore comments, blank lines, lines with just one keyword such as "end" and the require lines, this script was only 9 lines long. This really couldn't be any easier.

 #!/usr/bin/env ruby
 # The Twitter gem can be used not only
 # to post updates, but to utilize every
 # function off the Twitter API. If you
 # can do it on the website, you can do
 # it with the Twitter gem.
 require 'rubygems'
 require 'twitter'
 
 ### Section 1
 username = 'your_username'
 password = 'your_password'
 twitter = Twitter::Base.new( username, password )
 
 ### Section 2
 # Get a list of those following you, but
 # you are not following. Print their name
 # and URL.
 
 # Query for the information, keep only the
 # information we need.
 filter = proc {|f| [f.name, f.screen_name] }
 
 followers = twitter.followers.map(&filter)
 friends = twitter.friends.map(&filter)
 
 ### Section 3
 # Follow them
 (followers - friends).each do|f|
   puts "#{f[0]} - http://twitter.com/#{f[1]}"
   twitter.create_friendship f[1]
 
   # Sleep a few seconds, be nice to Twitter
   sleep 5
 end
 
  1. About.com
  2. Technology
  3. Ruby
  4. Networking
  5. Twitter--Ruby Script to Automatically Follow Followers

©2014 About.com. All rights reserved.