Code Your Own Python Twitter Bot in Ten Minutes
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.
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.
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.
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
I recommend using the mighty Sublime Text for the beginners when working with Python.
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)
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.
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...
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! :)
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
- 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.