h/plugins/weather.py

48 lines
1.5 KiB
Python
Raw Normal View History

"weather, thanks to google"
from lxml import etree
import urllib
from util import hook
@hook.command
2010-02-02 04:42:34 +00:00
def weather(inp, nick='', server='', reply=None, db=None):
2010-03-01 02:32:41 +00:00
".weather <location> [dontsave] -- gets weather data from Google"
2010-02-02 04:42:34 +00:00
loc = inp
dontsave = loc.endswith(" dontsave")
if dontsave:
loc = loc[:-9].strip().lower()
2010-02-02 04:42:34 +00:00
db.execute("create table if not exists weather(nick primary key, loc)")
2010-03-01 02:32:41 +00:00
if not loc: # blank line
2010-02-02 04:42:34 +00:00
loc = db.execute("select loc from weather where nick=lower(?)",
(nick,)).fetchone()
if not loc:
return weather.__doc__
loc = loc[0]
data = urllib.urlencode({'weather': loc.encode('utf-8')})
url = 'http://www.google.com/ig/api?' + data
w = etree.parse(url).find('weather')
if w.find('problem_cause') is not None:
return "Couldn't fetch weather data for '%s', try using a zip or " \
2010-02-02 04:42:34 +00:00
"postal code." % inp
info = dict((e.tag, e.get('data')) for e in w.find('current_conditions'))
info['city'] = w.find('forecast_information/city').get('data')
info['high'] = w.find('forecast_conditions/high').get('data')
info['low'] = w.find('forecast_conditions/low').get('data')
2010-02-02 04:42:34 +00:00
reply('%(city)s: %(condition)s, %(temp_f)sF/%(temp_c)sC (H:%(high)sF'\
', L:%(low)sF), %(humidity)s, %(wind_condition)s.' % info)
2010-02-02 04:42:34 +00:00
if inp and not dontsave:
db.execute("insert or replace into weather(nick, loc) values (?,?)",
(nick.lower(), loc))
db.commit()