summaryrefslogtreecommitdiff
path: root/modules/weather.py
blob: 60dc183c6c306aec69aee6a686cd382be1799dcf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#-*- coding: utf-8 -*-

info = {
	'author': 'Atle H. Havsø',
	'title': 'WolframAlpha Weather',
	'description': 'WolframAlpha weather search',
}

import urllib2
import xml.etree.ElementTree as xml


server = "http://api.wolframalpha.com/v2/query?"


class Module:
	def __init__(self, bot):
		self.appid = config.get('module/weather', 'api_key')
		self.location = config.get('module/weather', 'location')
		self.irc = bot
		self.irc.register_keyword('!weather', self)
	
	def keyword(self, nick, channel, kw, msg):
		target = channel if not channel == self.irc.nickname else nick.split('!')[0]
		args = msg.split()
		if len(args) == 0:
			self.irc.msg(target, 'Usage: !weather search')
			return
		results = self.search(' '.join(args))
		if results:
			self.irc.msg(target, results.encode('utf-8'))



	def search(self, input):
		query = server + "appid=" + self.appid + "&input=weather%20" + input + "&format=plaintext&location=" + self.location
		try:
			result = urllib2.urlopen(query)
			result = result.read()
			result = self.parseXml(result)
		except:
			result = 'Error: Try again'
		
		return result
	
	def parseXml(self, result):
		root = xml.XML(result)
		data = []
		for pod in root:
			for subpod in pod:
				for plain in subpod:
					if plain.text != None: data.append(plain.text)
		result = data[0]
		result += '\n' + "Today: " + data[3].replace('\n', ' - ')
		result += '\n' + "Tonight: " + data[4].replace('\n', ' - ')
		return result


if __name__ == '__main__':
	import sys
	m = Module(None)
	search = ' '.join(sys.argv[1:])
	result = m.search(search)
	print(result.encode("utf-8"))