Code Your Own Python Twitter Bot in Ten Minutes

20
Twitter bot in Python - Source code pic

Creative Commons Attribution 4.0 International License.

With ample libraries around, creating a twitter bot in Python is a quick and easy thing to do. In this edition of Geekswipe, we explore one such library, Twython, and build a twitter bot in less than ten minutes.

Setup

As this shows up in the web as one of the most common python beginner projects, I’ve updated the article with instructions on installation and setup for the beginners.

Installing Python

At this point, it is useless to use Python 2. It will be deprecated soon. Download and install Python 3 from here.

As a learner, trying out the nuances of Python with simple projects like a twitter bot, I recommend you install Python inside a virtual environment.

Step 1: Create a folder ‘twitter bot’, and cd to the folder (or if your on Windows, Shift + Right click and select Open command window here.). Create a virtual environment venv with Python 3 and activate it.

Installing Twython

Normally, we could use the requests library and make the API calls to Twitter and do all the bot stuff. Since this titled as ‘make a quick twitter bot’ using a library like Twython makes sense. If you are learning Python, I recommend you try to rebuild this bot with requests or go through Twython’s source code. Twython is a powerful Python Twitter API library.

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.

Twitter bot

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 any errors. Also, you don’t want to flood Twitter servers with hundreds of API requests in a short time. So let’s import the `time` module to add a sleep timer for our bot.

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

For your bot to authenticate with Twitter and use your account, you will need the API credentials. Create a new app on Twitter and copy the tokens generated and paste it above. Also make sure that your application has both read and write permission (you will need to verify your mobile number for this).

Initialize a Twython instance with your credentials by creating an object reference `twitter`.

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

Liners.txt

Create a new text file liners.txt, and paste some oneliners or jokes from the interwebs. Make sure you have enough lines. Our bot is going to read from this fille and tweet it automatically. We will also remove the lines that are longer than 280 characters or the ones that are already tweeted, so when the bot crashes, or restarts, you don’t have to tweet the old jokes.

The loop


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

for line in buff[:]:
	line = line.strip(r'\n')
	if len(line)<=280 and len(line)>0:
		print ("Tweeting...")
		try:
			twitter.update_status(status=line)
		except TwythonError as e:
			print (e)
		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 - Too long for a tweet!")
		continue
print ("No more lines to tweet...")

The above stuff is self-explanatory. We are reading all the lines from the liners.txt, iterating through each lines, and based on the character length (if it is below 280), we make the bot tweet it. And then we put the bot to sleep for 15 minutes. Also, we are removing any lines that are above Twitter’s character limit of 280. We are also removing the lines the lines that are already tweeted. If you want to preserve the contents of the liners.txt, just remove buff.remove(line) or the entire inner with loops. Or check the github repo linked below for a modified script that retains a copy of skipped and tweeted lines.

Here is the complete code for your reference:


"""
Name: Funzoned Twitter Bot
Description: A Twitter bot that tweets one liners every fifteen minutes.
"""

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)

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...")
		try:
			twitter.update_status(status=line)
		except TwythonError as e:
			print (e)
		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 - Too long for a tweet!")
		continue
print ("No more lines to tweet...") # When you see this... Well, go find some new tweets...

Hello bot

Time to wake up your bot to make some noise on Twitter. Make sure your liners.txt is filled with terrible … ahem … good jokes! Open the command window inside your directory and activate your venv. Type python MyTwitterBot.py and hit enter. Now head over to your twitter account and make sure if the bot is alive. Funzoned bot is alive here.

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

Further tweaks

Perhaps you can expand this bot to make it do more interesting stuff.

  • Expand the twitter bot to automatically fetch jokes, quotes, or other weird stuff when the liners.txt turns empty.
  • Instead of using time.sleep(900) create a cron job (Linux) or a scheduled task (Windows).
  • Rewrite the twitter bot with requests library or anyother request handling libraries for Python.
  • Reverse the bot! Instead of tweeting, try fetching tweets and do a sentiment analysis on the tweets.

You can fork the twitter bot’s code from here.

This post was first published on October 11, 2014.

Avatar

Karthikeyan KC

Aeronautical engineer, dev, science fiction author, gamer, and an explorer. I am the creator of Geekswipe. I love writing about physics, aerospace, astronomy, and python. I created Swyde. Currently working on Arclind Mindspace.

Leave a Reply

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

20 Responses

  1. Avatar Thomas Morgan

    Hi Artik,

    Thanks for this post. Do you know how long it takes to get credentials from Twitter?

    Thanks,

    Thomas

  2. Avatar Marco Massenzio

    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!

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

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

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

  6. perfect.

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

  8. 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/

  9. Avatar Aengus Walton

    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?

    • Appreciate the feedback! The skipping a line doesn’t make a difference as the tweet is sent before all that and the list integrity is still maintained at the end in the script. Updated the rest of the code!

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

      I agree. The library and the bot is self-explanatory for programmers! But a lot of beginners who read this might disagree with you.

    • 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!

  10. Good tutorial.

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

Related