Automatically Respond to Twitter Messages
I was a bit hesitant to post this script since it is such a powerful marketing tool that it could be used very badly in the hands of a spammer. The basic premise is to directly respond to someone’s tweet if they mention your product or service. So for example I might want to have a tweet that goes out directly to someone who mentions twitter and python in a tweet and let them know about this blog. This will accomplish the same thing as the TwitterHawk service except you won’t have to pay per tweet.
To do this I had a choice. I could use a service like TweetBeep.com and then write a script that responded to the emails in my inbox, or I could use the Twitter Search API directly. The search API is so dead simple that I wanted to try that route.
The other thing to consider is that I don’t want to send a tweet to the same person more than once so I need to keep a list of twitter users that I have responded to. I used pickle to persist that list of usernames to disk so that it sticks around between uses.
The query functionality provided by the Twitter Search API is pretty cool and provides much more power than I have used in this script. For example it is possible to geo-target, lookup hashtags, or reply tweets. You can check out the full spec at http://apiwiki.twitter.com/Twitter-API-Documentation
Lastly, to keep it a bit simpler I’m ignoring the pagination in the search results and this script will only respond to the first page worth of results. Adding a loop per page would be pretty straight forward but I didn’t want to clutter up the code.
Example Usage:
>>> import tweetBack >>> tweetBack.tweet_back('python twitter', 'Here is a blog with some good Python scripts you might find interesting http://halotis.com', 'twitter_username', 'twitter_password') @nooble sent message @ichiro_j sent message @Ghabrie1 sent message .....
Here’s the Python Code:
#!/usr/bin/env python # -*- coding: utf-8 -*- # (C) 2009 HalOtis Marketing # written by Matt Warren # http://halotis.com/ try: import json as simplejson except: import simplejson # http://undefined.org/python/#simplejson import twitter #http://code.google.com/p/python-twitter/ import urllib import pickle TWITTER_USER = 'username' TWITTER_PASSWORD = 'password' USER_LIST_FILE = 'tweetback.pck' #read stored list of twitter users that have been responded to already in a file try: f = open(USER_LIST_FILE, 'r') user_list = pickle.load(f) except: user_list = [] def search_results(query): url = 'http://search.twitter.com/search.json?q=' + '+'.join(query.split()) return simplejson.load(urllib.urlopen(url)) def tweet_back(query, tweet_reply, username=TWITTER_USER, password=TWITTER_PASSWORD): results = search_results(query) api = twitter.Api(username, password) try: for result in results['results']: if result['from_user'] not in user_list: api.PostUpdate('@' + result['from_user'] + ' ' + tweet_reply) print '@' + result['from_user'] + ' sent message' user_list.append(result['from_user']) except: print 'Failed to post update. may have gone over the twitter API limit.. please wait and try again' #write the user_list to disk f = open(USER_LIST_FILE, 'w') pickle.dump(user_list, f) if __name__=='__main__': tweet_back('python twitter', 'Here is a blog with some good Python scripts you might find interesting http://halotis.com')
Update: thanks tante for the simplejson note.
More from halotis.com
Related posts:
- Targeting Twitter Trends Script
- Google Translate API Python Script
- Scrape Technorati Search Results in Python
- Scrape Advertisements from Google Search Results with Python
- Sending Email from Python using Gmail



for python 2.6 don’t use `simplejson` but just `json` (simplejson was moved to the standardlib in python 2.6), this reduces unnecessary dependencies. Do a conditional import:
try:
import json as simplejson
except:
import simplejson
No further code changes needed.
Thanks for the input. I updated the script.
Automatically Respond to Twitter Messages – I was a bit hesitant to post this script since it is such a powerful ma.. http://bit.ly/Sd6y3
This comment was originally posted on Twitter
Automatically Respond to Twitter Messages in Python…
Matt Warren has come up with a very elegant script to automatically tweet back to anyone who mentions certain keywords. Check it out here.
……
Awesome!
This comment was originally posted on Reddit
Any connection with the recent DOS? ;)
This comment was originally posted on Reddit
TwitSH
This comment was originally posted on Reddit
Similar to a script I made to control a server though twitter (and thus your cellphone by tweeting through SMS) http://fluxtrap.blogspot.com/2009/05/smstwitter-control-of-your-server.html
This comment was originally posted on Reddit
Or: "how to not parse query parameters"
This comment was originally posted on Reddit
I recommend being reaaaally careful with what terms you use to trigger the response, and what the response says. I received one of these responses. From the wording it sounded like a human pointing me to this blog because of something relevant to my particular tweet. When I discovered that it was just a robot trying to get me to visit the site in general, my gratitude for the link turned to annoyance at the spam.
So, Matt, I suggest you reword the response you use with this script. If the message doesn’t imply direct relevance, it will be more clearly an ad, and it would set clearer expectations.
I was hesitant to post this code for that exact reason. However WRT the tweet I sent you – I did write the message myself and I was following these exact steps to post tweets before deciding to automate it. I tried to make it as natural as possible because nobody wants to get spam in twitter. I think this blog is pretty valuable to anyone looking to do something with twitter and python and there’s nothing wrong with letting people know about it.
Thank you for the reply, Matt.
I am having a hard time getting the sensitivity of the responses lower.
I used a random string of characters and tested it with my personal account, I did not receive a response. I then decided to use something I thought would not be triggered by ANYONE… “Fluffy Pandas” Believe it or not, sent about 10 messages out at once…
When I looked to see what may have triggered it, I noticed that one of the users being referenced had panda in the name… How would I adapt this code to specifically look for a phrase sent to the twitter account used in the code?
you can try a number of things to fine tune the search results.
use phrase= rather than q= to do a phrase match
use a geocode to get local tweeters: for example: geocode=40.757929%2C-73.985506%2C25km
add a language filter. ex: lang=en
use a since or until operator to limit the time. ex: since=2009-10-14
the full API Documentation is at http://apiwiki.twitter.com/Twitter-Search-API-Method%3A-search
Automatically Respond to Twitter Messages – I was a bit hesitant to post this script since it is such a powerful ma.. http://bit.ly/1hibzW
This comment was originally posted on Twitter