How to Make Your Own Twitter Bot - Python Implementation
Following up on my post last week about using Twitter to track eating and weight, some of you voiced some interest in creating your own Twitter bot. This post covers how you can do that.
The Gist of It
Creating my own Twitter bot was pretty straightforward (much more than I thought it'd be), mostly because Twitter provides an API and the resources to make it that way.
I wanted something really simple that I could play around with. I just wanted to be able to send a direct message to my Twitter bot, and from there, it would store my data. OK, so here are the basic steps I took:
- Create Twitter account for bot
- Turn on email notification for direct messages only
- Check email periodically for new direct messages
- Parse direct messages and store in database
Create a Twitter Account (and Email Address)
The first step is easy. Create a Twitter account specifically for your bot. The account name should be short and easy to remember. Make sure you enter an IMAP email address that is only for your bot. You could put in a general purpose email address, but it'll make your life a lot easier if the email address was specifically for Twitter.
Turn on Email Notifications
Once you've setup your bot account, turn on email notification via the Twitter options menu. For now, tell Twitter to only send you notifications when your bot receives direct messages and not when someone new follows.
Check Email and Do Something with Messages
Here's where the actual code comes in. Here's the general framework. I've left out some details that will be specific to your own purposes.
from imaplib import * from email.Parser import Parser import datetime, time, email, email.Utils import re # Connect to email server server = IMAP4("__EMAIL_SERVER.COM__") server.login("__EMAIL_ACCOUNT_NAME__", "__EMAIL_PASSWORD__") r = server.select("INBOX") # Find only new mail (i.e. new direct messages) r, data = server.search(None, "(NEW)") # If there are new direct messages: if len(data[0]) > 0: p = Parser() # Loop through new emails for num in data[0].split(): # Who email is from (Should be one line, broken for display only) r, data = server.fetch(num, '(BODY[HEADER.FIELDS (DATE SUBJECT FROM X-TwitterEmailType X-TwitterSenderScreenName X-TwitterCreatedAt X-TwitterRecipientScreenName)])') msg = p.parsestr(data[0][1]) who = msg.__getitem__('From') matchemail = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}') email_addy = matchemail.findall(who)[0] # Twitter username twitter_un = msg.__getitem__('X-TwitterSenderScreenName') # If the email is a direct message sent from Twitter if msg.__getitem__('X-TwitterEmailType') == 'direct_message': # When direct message sent, convert to epoch seconds twitter_time = msg.__getitem__('X-TwitterCreatedAt').strip() time_tuple = email.Utils.parsedate(twitter_time) epoch_seconds = time.mktime(time_tuple) # Get body of email sent by Twitter r, data = server.fetch(num, '(RFC822.TEXT)') body = data[0][1] twitter_dm = body.split("\r\n\r\n")[0].strip() # Do something with the twitter direct message... # Parse it... # Store it in a database?... # Logout of email server server.logout()
I run this script every 30 minutes with a cron. You could of course run it more frequently. The important part of this code though is that Twitter attaches its own special headers (e.g. X-TwitterEmailType). If you wanted your bot to automatically follow users that followed it, you could check the EmailType and then use the Twitter API to follow a Twitter user. For my simple purposes though, I only cared about direct messages.
That's all. There is of course plenty of room for improvement. Like I said, you could make this useful to lots of users by making your bot automatically follow those who follow it. Users can only direct message another Twitter user, if he is following. I would also delete emails that have already been read and stored somewhere so that the INBOX doesn't pile up. Yup.
Did I miss anything?
Like what you see? Subscribe to the FlowingData RSS feed to stay updated on what's new in data visualization.
- Subscribe to FlowingData Feed
- Leave a comment



FlowingData explores how statisticians, designers, and computer scientists are using data to help us understand more about ourselves and our surroundings. 




Comments
Nov 5, 2008, 4:25 am
Nov 5, 2008, 5:19 am
Nov 5, 2008, 8:27 am
Nov 5, 2008, 11:57 am
Nov 5, 2008, 12:09 pm
Nov 5, 2008, 12:20 pm
Nov 5, 2008, 12:38 pm
Nov 5, 2008, 2:27 pm
Nov 5, 2008, 2:36 pm
Nov 5, 2008, 4:09 pm
Nov 5, 2008, 9:57 pm
Nov 20, 2008, 3:14 pm
Dec 10, 2008, 8:57 pm
Dec 11, 2008, 12:48 am
Dec 11, 2008, 2:59 am
Dec 11, 2008, 10:30 am
Trackbacks/Pings
Add Your Comment