twitter.py: error detection & search by tweet id. closes #2

This commit is contained in:
Ryan Hitchman 2009-07-10 00:41:09 -06:00
parent 5d4c321169
commit 382ff8a27a
1 changed files with 34 additions and 12 deletions

View File

@ -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 <user> - gets most recent tweet from <user>"
if not input.strip():
def twitter(inp):
".twitter <user>/<id> - gets last tweet from <user>/gets tweet <id>"
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()))