phenny/modules/tfw.py

87 lines
2.2 KiB
Python
Raw Normal View History

2011-10-19 18:56:04 -04:00
#!/usr/bin/python3
"""
tfw.py - the fucking weather module
author: mutantmonkey <mutantmonkey@gmail.com>
"""
2011-09-22 14:17:27 -04:00
from urllib.parse import quote as urlquote
from urllib.error import HTTPError
import web
import lxml.html
2011-04-04 16:37:27 -04:00
def tfw(phenny, input, fahrenheit=False, celsius=False):
""".tfw <city/zip> - Show the fucking weather at the specified location."""
zipcode = input.group(2)
if not zipcode:
# default to Blacksburg, VA
zipcode = "24060"
2010-12-06 17:39:08 -05:00
2011-04-04 16:37:27 -04:00
if fahrenheit:
celsius_param = ""
2011-04-04 16:37:27 -04:00
else:
celsius_param = "&CELSIUS=yes"
2010-12-06 17:39:08 -05:00
try:
req = web.get("http://thefuckingweather.com/?zipcode=%s%s" % (urlquote(zipcode), celsius_param))
2011-09-22 14:17:27 -04:00
except (HTTPError, IOError):
phenny.say("THE INTERNET IS FUCKING BROKEN. Please try again later.")
2010-12-06 17:39:08 -05:00
return
doc = lxml.html.fromstring(req)
location = doc.find_class('small')[0].text_content()
try:
weather = doc.get_element_by_id('content')
except KeyError:
phenny.say("Unknown location")
return
main = weather.find_class('large')
# temperature is everything up to first <br />
2011-04-04 16:37:27 -04:00
tempt = ""
for c in main[0].text:
2011-11-06 01:42:19 -05:00
if c.isdigit() or c == '-':
2011-04-04 16:37:27 -04:00
tempt += c
temp = int(tempt)
2011-09-22 14:17:27 -04:00
deg = chr(176)
2011-04-04 16:37:27 -04:00
# add units and convert if necessary
if fahrenheit:
temp = "%d%cF?!" % (temp, deg)
elif celsius:
temp = "%d%cC?!" % (temp, deg)
else:
tempev = (temp + 273.15) * 8.617343e-5 * 1000
temp = "%f meV?!" % tempev
# parse comment (broken by <br />, so we have do it this way)
comments = main[0].xpath('text()')
if len(comments) > 2:
comment = "%s %s" % (comments[1], comments[2])
else :
comment = comments[1]
# remark is in its own div, so we have it easy
remark = weather.get_element_by_id('remark').text_content()
response = "%s %s - %s - %s" % (temp, comment, remark, location)
phenny.say(response)
tfw.rule = (['tfw'], r'(.*)')
2011-04-04 16:37:27 -04:00
def tfwf(phenny, input):
""".tfwf <city/zip> - The fucking weather, in fucking degrees Fahrenheit."""
return tfw(phenny, input, fahrenheit=True)
tfwf.rule = (['tfwf'], r'(.*)')
def tfwc(phenny, input):
2011-04-04 16:37:27 -04:00
""".tfwc <city/zip> - The fucking weather, in fucking degrees celsius."""
return tfw(phenny, input, celsius=True)
tfwc.rule = (['tfwc'], r'(.*)')
if __name__ == '__main__':
2011-09-22 14:17:27 -04:00
print(__doc__.strip())