Source

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.

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.

Newsletter

×

If you liked what you read then I am sure you will enjoy a newsletter of the content I create. I send it out every other month. It contains new stuff that I make, links I find interesting on the web, and occasional discount coupons for my book. Join the 5000+ other people who receive my newsletter:

I send out the newsletter once every other month. No spam, I promise + you can unsubscribe at anytime

✍️ Comments

Stuart

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.

Yasoob
In reply to Stuart

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 :) .

Mikhail

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 :)

Yasoob
In reply to Mikhail

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.

oliver

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?

Yasoob
In reply to oliver

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. :)

gloriahughes

Can you just make the code available for the autoresponder bot with instructions please? Thank you soooooo much!

Yasoob
In reply to gloriahughes

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. :)

Tami

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!

Gersande La Fleche

Thank you so much for introducing me to PyPi’s twitter API - you inspired me to write a little tutorial here : http://www.gersande.com/get-started-with-the-pypi-twitter-api/ - I mention you as an important resource at the end! :D Thank you so much!

Yasoob
In reply to Gersande La Fleche

Hi Gersande. I am really glad to hear that :) and your post looks good.

Drew Moffitt

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’

Yasoob
In reply to Drew Moffitt

I will take a look into this later. I hope you can wait.

Eric Matzner
In reply to Drew Moffitt

looks like you messed something up with creating the Oauth tokens. Great tutorial by @yasoob but he should have mentioned to also make sure you give write abilities (post) to the account. double check you filled in all the tokens correctly.

Dada

Really Good Post ! Simple and efficient

James

Where do you get OAuth tokens?

Moderndayfreak (@moderndayfreak)

Working on a twitter generator app that will be automated similar to this. Like to get your feedback. Thanks! http://www.free-retweets.com

Gelbra

I get an error that says: UnicodeEncodeError: ‘charmap’ codec can’t encode character ‘\u2026’ in position 112: character map to (undefined)

What does this mean? how can i get rid of it?

Thanks

Southclaw

Reblogged this on Southclaw.

Inzimam

how to post a tweet using python?

Inzimam

Ok I got it. But Do I have to keep my computer turned on and running this code all the time for it to work?

Yasoob
In reply to Inzimam

Yes :) only if you want to constantly monitor reddit. Otherwise you can restart it whenever you turn on your computer.

Thomas Anderson

How could you use multiple access tokens to favorite more tweets per hour?

Say something

Send me an email when someone comments on this post.

Thank you!

Your comment has been submitted and will be published once it has been approved. 😊

OK