# 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](https://github.com/bear/python-twitter) . The only problem I faced was with documentation but it is somewhat gets clear when you clone it and run the [index](https://github.com/bear/python-twitter/tree/master/doc/_build/html) file in [doc](https://github.com/bear/python-twitter/tree/master/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](https://github.com/farhaanbukhsh/Tweet-Bot)

Well you can see the script working here :

[![](https://cdn.hashnode.com/res/hashnode/image/upload/v1622182754154/dkiBnVt-O.png)](https://asciinema.org/a/b28wmbtrspdn3ai9rvakyvpkc)
