h/plugins/weather.py

69 lines
1.9 KiB
Python
Raw Normal View History

2008-06-09 11:59:56 +00:00
"weather, thanks to google"
2009-04-03 04:18:43 +00:00
import os
import codecs
import thread
2009-03-15 03:06:36 +00:00
import urllib
from lxml import etree
2008-06-09 11:59:56 +00:00
import hook
2009-04-03 04:18:43 +00:00
lock = thread.allocate_lock()
stalk = {}
2009-04-03 04:18:43 +00:00
def load_stalk(filename, mtimes={}):
if not os.path.exists(filename):
return {}
mtime = os.stat(filename).st_mtime
if mtimes.get(filename, 0) != mtime:
mtimes[filename] = mtime
return dict(x.strip().split(None, 1) for x in
2009-04-03 04:18:43 +00:00
codecs.open(filename, 'r', 'utf-8'))
2009-04-03 04:18:43 +00:00
def save_stalk(filename, houses):
out = codecs.open(filename, 'w', 'utf-8')
out.write('\n'.join('%s %s' % x for x in sorted(houses.iteritems()))) #heh
2009-04-03 04:18:43 +00:00
out.flush()
out.close()
@hook.command
2008-06-09 11:59:56 +00:00
def weather(bot, input):
2009-03-15 04:14:07 +00:00
".weather <location> -- queries the google weather API for weather data"
2009-04-03 04:18:43 +00:00
global stalk
2009-03-15 03:06:36 +00:00
2009-04-03 04:18:43 +00:00
filename = os.path.join(bot.persist_dir, 'weather')
if not stalk:
with lock:
stalk = load_stalk(filename)
2009-04-03 04:18:43 +00:00
nick = input.nick.lower()
loc = input.inp.strip().lower()
if not loc: # blank line
loc = stalk.get(nick, '')
if not loc:
return weather.__doc__
2009-03-15 03:06:36 +00:00
data = urllib.urlencode({'weather': loc.encode('utf-8')})
2009-03-15 03:06:36 +00:00
url = 'http://www.google.com/ig/api?' + data
w = etree.parse(url).find('weather')
2009-03-15 03:06:36 +00:00
if w.find('problem_cause') is not None:
return "Couldn't fetch weather data for '%s', try using a zip or " \
"postal code." % input.inp
2009-03-15 03:06:36 +00:00
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')
2009-04-03 04:18:43 +00:00
bot.reply('%(city)s: %(condition)s, %(temp_f)sF/%(temp_c)sC (H:%(high)sF'\
', L:%(low)sF), %(humidity)s, %(wind_condition)s.' % info)
if loc != stalk.get(nick, ''):
with lock:
stalk[nick] = loc
save_stalk(filename, stalk)