python, tutorial

Making a twitter bot in python

Hi there guys. I hope you are fine. In this post I am going to tell you how you can make a twitter auto favouriter or a.k.a Twitter Bot. I am not going to make a twitter follower as it will get you banned quickly if you use it a lot. This post is going to help you to increase your twitter followers organically. By organically I mean that your followers will be those who really want to listen to your content. You can either use services on the web to increase your followers inorganically or else you can use this script ;) . So what affect does favouriting has on the user who’s post you favourite ? When you favourite someone’s post he will get curious as who favourited his post. Then he will visit your profile and will follow you if he likes your tweets. So without wasting any time lets begin.

The basic mechanism or the way of working of our bot will be that you will give it a keyword like “python” and it will search twitter for that keyword. After searching it will start favouriting the tweets from top to bottom.

First of all I am going to use “twitter” module for this project. There are a lot of twitter related modules on PyPI but this module did the trick so I thought to use it (https://pypi.python.org/pypi/twitter/1.10.0) . Secondly in order to follow along you will have to make a dev account on twitter and register an application with any name (https://dev.twitter.com/apps). Lets begin by importing the twitter module and initiating connection with twitter using the OAUTH tokens. :

from twitter import Twitter, OAuth, TwitterHTTPError

OAUTH_TOKEN = 'your oauth token'
OAUTH_SECRET = 'your oauth secret'
CONSUMER_KEY = 'your consumer key'
CONSUMER_SECRET = 'your consumer secret'

t = Twitter(auth=OAuth(OAUTH_TOKEN, OAUTH_SECRET,
            CONSUMER_KEY, CONSUMER_SECRET))

So now we have initiated connection with twitter. This is the basic structure of our twitter auto favouriter or a.k.a twitter bot. Now lets move on and define a method which will search for tweets on twitter.

def search_tweets(q, count=100):
    return t.search.tweets(q=q, result_type='recent', count=count)

So now we have to define a method which will favourite a tweet:

def fav_tweet(tweet):
    try:
        result = t.favorites.create(_id=tweet['id'])
        print "Favorited: %s" % (result['text'])
        return result
    # when you have already favourited a tweet
    # this error is thrown
    except TwitterHTTPError as e:
        print "Error: ", e
        return None

So now we have a searching method and a favouriting method. Now tell me what is left ? Obviously the main code that will drive our whole program is left. So here you go:

def auto_fav(q, count=100):
    result = search_tweets(q, count)
    a = result['statuses'][0]['user']['screen_name']
    print a
    success = 0
    for tweet in result['statuses']:
        if fav_tweet(tweet) is not None:
            success += 1
    print "We Favorited a total of %i out of %i tweets" % (success,
          len(result['statuses']))

So thats it! We have a complete bot for twitter. This bot currently only favourites tweets based on a keyword. Save this code in a file called twitter_bot.py . Now you can use this bot by typing this in the terminal:

$ python

>>> import twitter_bot
>>> twitter_bot.auto_fav('#python','20')

The above command will search for 20 latest tweets containing the hashtag “python”. After that it will favourite all of those tweets. This bot itself works but I can not gurantee that you will get followers quickly and I can not even gurantee that you will not get banned by twitter for using this a lot. You can use this once in a day. Hopefully I will write a twitter follower bot in the future as well but till then this script is your best bet.

This is the complete script:

from twitter import Twitter, OAuth, TwitterHTTPError

OAUTH_TOKEN = 'your oauth token'
OAUTH_SECRET = 'your oauth secret'
CONSUMER_KEY = 'your consumer key'
CONSUMER_SECRET = 'your consumer secret'

t = Twitter(auth=OAuth(OAUTH_TOKEN, OAUTH_SECRET,
            CONSUMER_KEY, CONSUMER_SECRET))

def search_tweets(q, count=100):
    return t.search.tweets(q=q, result_type='recent', count=count)

def fav_tweet(tweet):
    try:
        result = t.favorites.create(_id=tweet['id'])
        print "Favorited: %s" % (result['text'])
        return result
    # when you have already favourited a tweet
    # this error is thrown
    except TwitterHTTPError as e:
        print "Error: ", e
        return None

def auto_fav(q, count=100):
    result = search_tweets(q, count)
    a = result['statuses'][0]['user']['screen_name']
    print a
    success = 0
    for tweet in result['statuses']:
        if fav_tweet(tweet) is not None:
            success += 1
    print "We Favorited a total of %i out of %i tweets" % (success,
          len(result['statuses']))

This is the final result of running this sript:

yasoob@yasoob:~/Desktop$ python
Python 2.7.3 (default, Apr 10 2013, 06:20:15) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import twitter_bot as bot
>>> bot.auto_fav('django',1)
Favorited: Enjoying @freakboy3742’s discussion of cultural naming patterns vis a vis Django users at #DjangoCon
We Favorited a total of 1 out of 1 tweets
>>>

I hope you liked todays post. If you have any questions then feel free to comment below and do follow us if you want to get regular updates from our blog. If you want me to write on one specific topic then do tell it to me in the comments below. Stay tuned for my next post.

About these ads
Standard

20 thoughts on “Making a twitter bot in python

  1. Stuart says:

    Very very cool. A real world application like this twitter bot is why I keep coming back to your blog mate!

    Yes, with twitter I do believe their is some sort of connection limit which you can find through their original API documents, but they might be a bit out of date with their relatively new OAUTH stuff.

    • Hi! There are supporters like you that keep me and this blog alive and secondly I agree that the twitter docs are a bit outdated and so are a lot of tutorials on the web. Twitter does not clearly mention the maximum number of api calls we can make. Lets see when twitter will update their info and will mention this :) .

  2. Mikhail says:

    Can I ask, please?
    What does mean count=100 in conditions (q, count=100)?

    I’ve already submitted to the value that is erased and written to a new, equal to a hundred?
    Sorry, if I ask something silly, but I new to Python :)

    • Hi MIKHAIL. Firstly thanx for replying and secondly I have not used count=100 in a condition. I have used it in a function. I could have written “def search_tweets(q, count)” but there can be a problem with that. If we don’t pass a value for count our function will give an error. I have set a default value of 100 so that if I don’t pass a value for count my function will take count to be equal to 100. I hope that clarifies everything. Still if you have any other question then feel free to post.

  3. oliver says:

    hi!
    I have a proposition/question.
    can You tell how to make autoresponder bot?

    for example, bot search word ‘Python’ and replies ‘I love Python too’. can You do this?

    • It’s not really difficult. You just tell me what words do you want to search for and what do you want to reply. This is going to be on twitter, right ? So keep in mind that you can not do a lot of requests because twitter has an api limit . However it is still doable. :)

      • oliver says:

        It will be in Ukrainian language. I can change words myself, I just wanna sample, because I just started to learn Python few month ago, but it’s difficult to me to work with twitter api :]
        It will be autoresponder bot, that wishes something.

        I know about API limit. Nearly 1000 twits

        Also, have two suggestions for you:
        1. Make auto-reply bot that launch automatically. For example, once in 5 minutes.
        2. Select reply-phrase from some range of phrases (for example: we have three reply-phrases in a range: “Me too!”, “I love it soooo much” and “Python – forever!”. When someone post a twit with a word “Python” in it – bot replies with a random selected phrase from our range)

    • I will try to make it in the upcoming holidays and hopefully if everything goes as planned it will be up in the upcoming weeks. Just follow this blog to stay tuned when I post it. :)

  4. Tami says:

    Could you tell me how to create a twitter follower bot? For example, say I wanted a bot that could make 10.000 followers, is this possible? Thank you!

  5. Drew Moffitt says:

    Hi Here is the error I am received. Does anyone know why this may be happening?

    >>> twitter_bot.auto_fav(‘#python’,’1′)
    taswarbhatti
    Error: Twitter sent status 404 for URL: 1.1/favourites/create.json using parameters: (id=401405655812034560&oauth_consumer_key=wrbBvjW7UP1JR2F2wkfBw&oauth_nonce=7098331017675876433&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1384537602&oauth_token=468924404-zBlNm2da4xZxIGpLj6zjBBxfplKlcwMYlfTGp0kH&oauth_version=1.0&oauth_signature=N33NU1bB3%2Bgdr6LwzQFf64NX%2BaI%3D)
    details: {“errors”:[{"message":"Sorry, that page does not exist","code":34}]}
    Traceback (most recent call last):
    File “”, line 1, in
    File “twitter_bot.py”, line 33, in auto_fav
    print “We Favorited a total of %i out of %i tweets” (success, len(results['statues']))
    KeyError: ‘statues’

    Thank you.

  6. Drew Moffitt says:

    YASOOB, any insight as to why I am getting this error?
    >>> twitter_bot.auto_fav(‘#python’,’1′)
    taswarbhatti
    Error: Twitter sent status 404 for URL: 1.1/favourites/create.json using parameters: (id=401405655812034560&oauth_consumer_key=wrbBvjW7UP1JR2F2wkfBw&oauth_nonce=7098331017675876433&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1384537602&oauth_token=468924404-zBlNm2da4xZxIGpLj6zjBBxfplKlcwMYlfTGp0kH&oauth_version=1.0&oauth_signature=N33NU1bB3%2Bgdr6LwzQFf64NX%2BaI%3D)
    details: {“errors”:[{"message":"Sorry, that page does not exist","code":34}]}
    Traceback (most recent call last):
    File “”, line 1, in
    File “twitter_bot.py”, line 33, in auto_fav
    print “We Favorited a total of %i out of %i tweets” (success, len(results['statues']))
    KeyError: ‘statues’

  7. Pingback: Get Started with Mike Verdone’s PyPi Twitter API | Gersande

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