Python and Twitter

Python and Twitter

I was playing around with twitter library on python, I actually ended up writing a bot , the bot actually has a list of hashtags within it and when you run the bot it goes to twitter search for the tweets , favorites the tweet and follow that person.

Why would someone want to do that , well just because you can.

So I was actually looking into this library for python and twitter interface : Python-Twitter . The only problem I faced was with documentation but it is somewhat gets clear when you clone it and run the index file in doc folder.

I will try to walk you through the code, I maintained a list of favorite hashtags :


favorite_hashtags = ['#mozilla','#mozlove','#python','#jnaapti','#msaan']

Now , with this hashtags I wrote a function to accept status object as a parameter and scrape the user id, user name and various info from the status objects.


def follow_user_hashtags_fav(status_object):
  user_dict = dict()
  user_dict = status_object.AsDict()
  user_name = user_dict['user']['name']
  user_id = user_dict['user']['id']
  api.CreateFavorite(status_object)
  print 'You favorited this tweet : \n',status_object.text
  api.CreateFriendship(user_id)
  print 'You are following : \n',user_name

In here the function that favorites the tweet and that follows the user is very clear. The trick is to get user id , which we are doing by getting a dictionary out of status object.

Now the only thing left is iterating through the hashtags:


for hashtag in favorite_hashtags:
  print 'For hashtag : \t', hashtag
  list_statuses = api.GetSearch(hashtag)
  for status in list_statuses:
    try:
     follow_user_hashtags_fav(status)
    except twitter.error.TwitterError:
     print "Some Error may be you favorited it twice or you are following yourself"

and voila that how it works.

Feel free to fork and use it on my repo: Tweet-Bot

Well you can see the script working here :