Mass/Bulk Follow with py-twitter

While trying to maintain the Greek Liberals twitter account, specifically trying to follow a bunch of people that I also follow, I didn’t manage to find a satisfactory solution to automatically follow a specific list of screen names.

Zac Bowling‘s bulk following tool wasn’t working for me (I get an authentication error). The only other promising solution is Flashtweet but they insist on loading the list of new people to follow from another twitter account’s follow list. At first that might not seem like a problem, since I could simply load my personal twitter account friends in Flashtweet and check the people I wanted to follow. But I already had a hand-picked list of people that I wanted the GreekLiberals twitter account to follow. I created this list by going through the CSV file that Tweeple exports where I can browse all the details of a user instead of just the twitter name like in Flashtweet’s interface. I don’t want to start mindlessly following people who for starters might not even speak greek or be otherwise interested in dialogue with the Greek Liberals.

So I decided to write a py-twitter script to do the importing. Here it is:

import twitter
import simplejson
from urllib2 import HTTPError, URLError

class MassFollower(twitter.Api):
   ''' Follow a list of people '''

   def AllFriends(self):
      friends = []
      while (not len(friends) % 100) :
         # see http://code.google.com/p/python-twitter/issues/detail?id=20
         friends.extend(self.GetFriends(page=((len(friends)/100)+1)))
      return friends

   def MassFollow(self,names):
      for name in set(names)-set([f.screen_name for f in self.AllFriends()]):
         if not self.GetUser(name).protected:
            try:
               self.CreateFriendship(name)
            except HTTPError, e:
               print "got error with code",e.code
               # see http://code.google.com/p/python-twitter/issues/detail?id=33 
               if e.code == 401 or e.code == 403:
                  data=simplejson.loads(e.read())
                  print "got data", data
                  if (hasattr(data,'error')):
                     print "can't follow ", name, " because ", err.error
                     continue
               raise

if __name__ == "__main__":
   import sys
   import getpass
   u=sys.argv[1]
   file=open(sys.argv[2],'r')
   p=getpass.getpass("Twitter password: ")
   try:
      api = MassFollower(username=u,password=p)
      api.MassFollow([ line.strip() for line in file ])
   except IOError, e:
      if hasattr(e, 'reason'):
         print "Can't contact twitter:", e.reason
      elif hasattr(e, 'code'):
         if e.code==400:
            print "Probably struck rate limit, try again later."
         else:
            print 'The server couldn\'t fulfill the request: code',e.code

Kudos to Niklas Saers whose own py-twitter utility, lasttweet.py, tipped me off to the page parameter argument to GetFriends method. At the time of this writing, an observant fellow will notice that, according to the aforelinked docs, there is no parameter named page. This is why this script is currently dependent on a version of py-twitter greater than 0.5, which is currently the stable version. So basically you need to get a svn checkout and install it manually on your system.

Apart from being my first use of the twitter API it is also the first semi-usefull thing I’ve written in python, so I would be gratefull for criticism or comments regarding the code above.

Advertisements

18 thoughts on “Mass/Bulk Follow with py-twitter

  1. Actually, the documentation does not work. The error occurs when you don’t the necessary arguments, i.e. your twitter username and the filename to read the usernames to follow from. Obviously some error checking would not be entirely useless. 🙂

  2. Perfect for being visiting your blog yet again, it is months for me. I require these content articles to comprehensive my assignment inside the college, and it also has identical topic along with your posting. Many thanks, great share.

  3. As the sweat evaporates, it creates a cooling effect.
    this ceiling fan is very different to the fan described above due to the design features.

    Now, as I sit in my family room, feet propped up in my
    comfy recliner, I can finally enjoy the fruits of my labor.

  4. I hardly leave a response, but I browsed some responses here Mass/Bulk Follow with py-twitter | kouk.

    I do have a few questions for you if it’s okay.
    Could it be simply me or does it look like a few of the responses appear like
    they are coming from brain dead people? 😛 And, if you
    are posting on additional online sites, I would like to follow anything new you have to post.
    Would you post a list of every one of all your shared sites like your linkedin profile, Facebook page or twitter feed?

  5. However, this scene changed when more programmers became aware of
    virus programming and started building viruses that manipulated and destroyed data on infected computers.
    Advertisers all over the place, advertising everything underneath
    the sun. The Unit is powered by the Main chip adopting
    the CORTEX A8 core Sam – Sung S5PV210,and CPU
    frequency up to 1GHz, Memory 512MB, internal
    2G memory space for TV and Internet integration.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s