diff --git a/plugins/twitter.py b/plugins/twitter.py index da002c1..28fabe6 100644 --- a/plugins/twitter.py +++ b/plugins/twitter.py @@ -3,7 +3,8 @@ twitter.py: written by Scaevolus 2009 retrieves most recent tweets """ -import urllib +import re +import urllib2 from lxml import etree from util import hook @@ -22,21 +23,42 @@ def unescape_xml(string): @hook.command -def twitter(input): - ".twitter - gets most recent tweet from " - if not input.strip(): +def twitter(inp): + ".twitter / - gets last tweet from /gets tweet " + inp = inp.strip() + if not inp: return twitter.__doc__ - url = "http://twitter.com/statuses/user_timeline/%s.xml?count=1" \ - % urllib.quote(input) + getting_id = False + if re.match('^\d+$', inp): + getting_id = True + url = 'http://twitter.com/statuses/show/%s.xml' % inp + elif re.match('^\w{,15}$', inp): + url = 'http://twitter.com/statuses/user_timeline/%s.xml?count=1' % inp + else: + return 'error: invalid username' + try: - tweet = etree.parse(url) - except IOError: - return 'error' + xml = urllib2.urlopen(url).read() + except urllib2.HTTPError, e: + errors = {400 : 'bad request (ratelimited?)', + 401: 'tweet is private', + 404: 'invalid user/id', + 500: 'twitter is broken', + 502: 'twitter is down ("getting upgraded")', + 503: 'twitter is overloaded (lol, RoR)'} + if e.code == 404: + return 'error: invalid ' + ['username', 'tweet id'][getting_id] + if e.code in errors: + return 'error: ' + errors[e.code] + return 'error: unknown' - if tweet.find('error') is not None: - return "can't find that username" + tweet = etree.fromstring(xml) + + if not getting_id: + tweet = tweet.find('status') + if tweet is None: + return 'error: user has no tweets' - tweet = tweet.find('status') return unescape_xml(': '.join(tweet.find(x).text for x in 'created_at user/screen_name text'.split()))