Code Your Own Python Twitter Bot in Ten Minutes

18

Twitter bot in Python - Source code pic

Note: Our syntax highlighter is causing issues with our server. We’ve disabled it temporarily. Please use the code from the git repository to refer the line numbers. Or… Count it yourself ;)

The following twitter bot is a hobby project that I tried when I started to learn Python a few months ago. I guess it’d be so easy for you to build one too.

This article is focused on Python learners and beginners like me, and of course for the non-programmers.

Setup

Installing Python

We are about to write a python script and hence we would need a python environment in your system in order to execute the script.

Download and install python from here.

You could install the legacy version (2.7.x) if you want to learn python peacefully or you could choose the most recent version (3.4.x) if you want to live on the edge and suffer like me. But, this bot is written in Python 3. If you are sure that you need python, just for the sake of the bot, proceed with Python 3.

Twitter bot script

Step 1: Create a directory where your Twitter bot is going to live in. From now on, everything happens inside this folder.

Twython is a powerful Python Twitter API library. We are going to use this to enable communication with your bot and Twitter, via the Twitter API.

Step 2: Open the command window inside the directory (Shift + Right click and select Open command window here) and Install twython using the command  pip install twython. (If you don’t have pip, install it by using this command python get-pip.py and then install Twython)

Step 3: Now create an empty file and rename it to MyTwitterBot.py

I recommend using the mighty Sublime Text for the beginners when working with Python.

Step 4:

The script

from twython import Twython, TwythonError
import time

These are the modules we’ll be using to setup the bot. Twython is the module that we are going to use to connect with the Twitter API and TwythonError to handle the error. Your bot should need a time interval to tweet. So we are importing time module too.

APP_KEY = 'YOUR KEY'
APP_SECRET = 'YOUR SECRET KEY'
OAUTH_TOKEN = 'YOUR TOKEN'
OAUTH_TOKEN_SECRET = 'YOUR SECRET TOKEN'

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

This part gives your bot the proper credentials to communicate with your actual twitter account. You must create a new app on twitter to get these access tokens. Also, make sure that you give your app the permission to read and write (You might be asked to verify your mobile number for this. If mobile number verification fails, try verifying it with a mobile app.)

Specify all the necessary tokens from the new twitter app in lines 3 to 6.

As shown on line 8, create an array called twitter with all the above access tokens in the list. Every time we tweet, we are going to use this array.

Liners.txt

This is your tweet repository. Create a new text file liners.txt, – Your twitter bot is going to fetch tweets from this text file only. So make sure you add enough tweets.

The loop

try:
	with open('liners.txt', 'r+') as tweetfile:
		buff = tweetfile.readlines()

	for line in buff[:]:
		line = line.strip(r'\n')
		if len(line)<=140 and len(line)>0:
			print ("Tweeting...")
			twitter.update_status(status=line)
			with open ('liners.txt', 'w') as tweetfile:
				buff.remove(line)
				tweetfile.writelines(buff)
			time.sleep(900)
		else:
			with open ('liners.txt', 'w') as tweetfile:
				buff.remove(line)
				tweetfile.writelines(buff)
			print ("Skipped line - Char length violation")
			continue
	print ("No more lines to tweet...")


except TwythonError as e:
	print (e)
Note: This removes the lines in the liners.txt file as the lines are tweeted. If you want to preserve the contents of the file, just remove buff.remove(line) snippet and the write line parts from the above loop.
The above stuff is self-explanatory. However, for the curious, this loop checks the first line, tweets it, removes it (or eats it like a Tasmanian devil) and then sleeps for fifteen minutes. Then it again does the job. Line 14 will strip any empty lines from the liners.txt and line 24 will remove the line that has more than 140 characters.

Here is the complete code for your reference:

"""

URL: https://geekswipe.net/2014/10/code-python-twitter-bot-in-ten-minutes/
Author: Karthikeyan KC
Name: Funzoned Twitter Bot
Description: A Twitter bot that tweets one liners every fifteen minutes.
Comment: This bot is created for learning purposes and is full of 'novice' bugs. It might evolve soon. The process runs on my laptop from a terminal and it will be on and off at times.
Twitter: http://twitter.com/funzoned
Bitbucket: https://bitbucket.org/karthikeyankc/funzoned-twitter-bot/src/

"""

from twython import Twython, TwythonError
import time

APP_KEY = 'YOUR KEY'
APP_SECRET = 'YOUR SECRET'
OAUTH_TOKEN = 'YOUR TOKEN'
OAUTH_TOKEN_SECRET = 'YOUR SECRET TOKEN'

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

try:
	with open('liners.txt', 'r+') as tweetfile:
		buff = tweetfile.readlines()

	for line in buff[:]:
		line = line.strip(r'\n') #Strips any empty line.
		if len(line)<=140 and len(line)>0:
			print ("Tweeting...")
			twitter.update_status(status=line)
			with open ('liners.txt', 'w') as tweetfile:
				buff.remove(line) #Removes the tweeted line.
				tweetfile.writelines(buff)
			time.sleep(900)
		else:
			with open ('liners.txt', 'w') as tweetfile:
				buff.remove(line) #Removes the line that has more than 140 characters.
				tweetfile.writelines(buff)
			print ("Skipped line - Char length violation")
			continue
	print ("No more lines to tweet...") #When you see this... Well :) Go find some new tweets...


except TwythonError as e:
	print (e)

Hello bot

Now that you have set up your bot, it’s time to wake it up. Add a message to the liners.text. Open the command window inside the directory and type the command python MyTwitterBot.py. Now head over to your associated twitter account and check if the bot is alive. You could also run it as a cron job for the long run.

Congratulations! You’ve now created your own Python bot :)

Now, explore Twitter API and try adding more features to your bot. You can also edit and modify my codes. Or if you choose to contribute, you can fork it from here. Check out the past tweets from my Funzoned bot here.

If you would like to retain all your tweets, check out the improved code here.

If you have any issues, post it in the comments section and I’ll help you out.

This post was first published on October 11, 2014.

Karthikeyan KC

Aeronautical Engineer, Science Fiction Author, Gamer, and an Explorer. I am the creator of Geekswipe. I love writing about Physics and Astronomy. I am now creating Swyde.

Related

Leave a Reply

Your email address will not be published. Required fields are marked *

18 Responses

  1. Hi – came across this page and was wondering whether I can re-use that opening image on one of my Medium posts (https://medium.com/@massenz)? also I think I found your Flickr feed: your photos are beautiful and I was wondering whether you license them under Creative Commons? (couldn’t find anything there to this effect).

    I would obviously credit them back to you.
    Thanks!

  2. Hi KArtik. Thank you so much. I am getting a hang of it now and this helps me a lot.

  3. Hi thanks to this. I am learning Python and I love this.

  4. Lucal Raine

    Great tuts. Actually you can do much more with Twython. I initially use Tweepy, but switched to Twython for that overkill. Try messing with it :)

  5. perfect.

  6. With a small script like this, you could throw it up onto Heroku and let it spin and spin and spin forever, without paying a dime :)

  7. I wrote almost the same thing as a mini-project at work, using Twisted to schedule the posts in the background, rather than sleeping: https://github.com/SpokesmanReview/twitterbot/

  8. I hate to be negative, but there are more than a few things wrong with this code – naked exception catching around a huge clump of lines, unpythonic style – but the worst offender is certainly removing elements from a list currently being iterated over. This will result in python skipping a line from the file, when it iterates to the next element in the list:


    >>> a = [1, 2, 3, 4, 5]
    >>> for x in a:
    ... if x%2 == 0:
    ... a.remove(x)
    ... else:
    ... print x
    ...
    1
    >>> a
    [1, 3, 5]
    >>>

    Other than that – these libraries are so self-explanatory, is there really a need for such an introduction?

    • Thank you for your suggestions.
      The reason why I remove the elements from the list is just to give the bot an ovelray of the Tasmanina Devil ;) I don’t know what you mean by ‘skipping a line’. (This is also the reason why I remove the line on both the cases..)

    • For a trivial app like this, naked exception catching isn’t the worst. I agree with you about the removing elements from a currently looping list though, that’s fraught with error. Better to remove the item from a copy.

    • Self explanatory? Isn’t that the whole point of Python? I love Python’s simplicity whatsoever.

    • What line was skipped from [1,2,3,4,5] ?. In PHP at least, it is safe to remove while looping. PHP makes a copy of the current array unless you specify pass by reference, Good practices are language independent.

    • “is there really a need for such an introduction?”
      As a matter of fact yes! Just because you can understand code, it does not mean that noobs can too!

  9. Good tutorial.

  10. Thanks a lot. Works like a charm.. But the connection closes often and I have to run it again. Can you help me?