retweet.py
Tonight, instead of being at the Dutch Pinball Open as I should have been (curseth be thee, o weak flu-ridden body), I whipped up a little script to retweet everything on twitter that has the hashtag #revspace on the revspace twitter feed. Just for your enjoyment, here is the script. It probably has some caveats (eg. looping forever when authentication fails), and almost no error handling at all, but it suffices for now.
#
# retweet.py - retweet based on hashtag
# Copyright (C) 2009 Koen Martens
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
import json
import urllib
import os
import sys
hashtag = '#revspace'
user = 'revspacenl'
password = 'foobarbaz'
class MyUrlOpener(urllib.FancyURLopener):
def set_user(self,user):
self.user=user
def set_password(self,password):
self.password=password
def prompt_user_passwd(self,host,realm):
print 'auth host '+host+' realm '+realm
return (self.user, self.password)
def get_searchurl(hashtag):
if (os.path.exists('refresh.'+hashtag)):
file = open('refresh.'+hashtag)
refresh_url = file.readline()
file.close()
return refresh_url
return 'http://search.twitter.com/search.json?q=' + urllib.quote(hashtag)
def search(searchurl):
sock = urllib.urlopen( searchurl )
response = json.load( sock )
sock.close()
return response
def save_refreshurl(hashtag,refresh_url):
file = open('refresh.'+hashtag,'w');
file.write(refresh_url+'\n');
file.close()
def update_status(user,password,tweet):
data = urllib.urlencode( { 'status': tweet } )
try:
opener = MyUrlOpener()
opener.set_user(user)
opener.set_password(password)
sock = opener.open( 'http://twitter.com/statuses/update.json',data )
response = json.load( sock )
sock.close
except:
sys.stderr.write( "Unexpected error:" + sys.exc_info()[0] )
searchurl = get_searchurl(hashtag)
print 'Search url: '+searchurl
response = search(searchurl)
for result in response['results']:
if result['from_user'] != user:
tweet = 'RT @'+result['from_user']+': '+result['text']
print tweet
update_status(user,password,tweet)
save_refreshurl(hashtag,'http://search.twitter.com/search.json'+response['refresh_url'])
