Deal more gracefully with errors and allow city and state as well

master
mutantmonkey 2010-12-06 17:53:04 -05:00
parent 6bd9a15343
commit c56aa15867
1 changed files with 12 additions and 7 deletions

View File

@ -6,24 +6,29 @@ author: mutantmonkey <mutantmonkey@gmail.com>
import random import random
from urllib2 import urlopen from urllib import quote as urlquote
from urllib2 import urlopen, HTTPError
import lxml.html import lxml.html
def tfw(phenny, input): def tfw(phenny, input):
zipcode = input.group(2) zipcode = input.group(2)
try: try:
zipcode = int(zipcode) req = urlopen("http://thefuckingweather.com/?zipcode=%s" % urlquote(zipcode))
except ValueError: except HTTPError:
phenny.say("Sorry, .tfw only supports zip codes") phenny.say("THE INTERNET IS FUCKING BROKEN. Please try again later.")
return return
req = urlopen("http://thefuckingweather.com/?zipcode=%d" % zipcode)
doc = lxml.html.parse(req) doc = lxml.html.parse(req)
location = doc.getroot().find_class('small')[0].text_content() location = doc.getroot().find_class('small')[0].text_content()
weather = doc.getroot().get_element_by_id('content') try:
weather = doc.getroot().get_element_by_id('content')
except KeyError:
phenny.say("Unknown location")
return
main = weather.find_class('large') main = weather.find_class('large')
# temperature is everything up to first <br /> # temperature is everything up to first <br />
@ -41,7 +46,7 @@ def tfw(phenny, input):
response = "%s %s - %s - %s" % (temp, comment, remark, location) response = "%s %s - %s - %s" % (temp, comment, remark, location)
phenny.say(response) phenny.say(response)
tfw.rule = (['tfw'], r'(\d*)') tfw.rule = (['tfw'], r'(.*)')
if __name__ == '__main__': if __name__ == '__main__':
print __doc__.strip() print __doc__.strip()