summaryrefslogtreecommitdiff
path: root/modules/traffic.py
blob: b315660bc54169a59a80cde2d852eeccdfc86d74 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# -*- coding: utf8 -*-

info = {
	'author': 'Jon Bergli Heier',
	'title': 'Traffic data',
	'description': 'Traffic data from Statens Vegvesen',
}

import urllib2, urllib
from lxml import etree

counties = {
	'Akershus': 2,
	'Aust-Agder': 9,
	'Buskerud': 6,
	'Finnmark': 20,
	'Hedmark': 4,
	'Hordaland': 12,
	u'Møre og Romsdal': 15,
	u'Nord-Trøndelag': 17,
	'Nordland': 18,
	'Oppland': 5,
	'Oslo': 3,
	'Rogaland': 11,
	'Sogn og Fjordane': 14,
	u'Sør-Trøndelag': 16,
	'Telemark': 8,
	'Troms': 19,
	'Vest-Agder': 10,
	'Vestfold': 7,
	u'Østfold': 1,
}

class InvalidCountyException(Exception): pass

class Module:
	def __init__(self, bot):
		self.irc = bot
		if self.irc:
			self.irc.register_keyword('!traffic', self)

	def traffic(self, args):
		if len(args) == 2:
			rn, c = args
		elif args[0][-1].isdigit():
			rn = args[0]
			c = None
		else:
			rn = None
			c = args[0]
		if c:
			c = c.decode('utf8').capitalize()
			if not c in counties:
				raise InvalidCountyException()

		if rn:
			if rn.lower().startswith('e'):
				rt = 'Ev'
			elif rn.lower().startswith('r'):
				rt = 'Rv'
			else:
				rt = 'Alle'
		else:
			rt = None

		while rn and not rn[0].isdigit():
			rn = rn[1:]

		if rt and rn:
			url = 'http://www.vegvesen.no/trafikk/xml/search.xml?searchFocus.roadTypes=%s&searchFocus.roadNumber=%s' % (rt, rn)
		elif c:
			url = 'http://www.vegvesen.no/trafikk/xml/search.xml?searchFocus.counties=%d' % counties[c]
		u = urllib2.urlopen(url)

		xml = etree.parse(u)

		results = []
		for message in xml.xpath('/searchresult/result-array/result/messages/message'):
			if (rt and c and c.lower() in (x.text.lower() for x in message.xpath('actualCounties/string'))) or not c or not rt:
				if len(results) == 5:
					if rt and rn:
						results.append('More results: http://www.vegvesen.no/Trafikkinformasjon/Reiseinformasjon/Trafikkmeldinger?%s' % urllib.urlencode({
							'type': 'veg',
							'vegkategorier': rt,
							'vegnummer': '6',
							}))
					else:
						results.append('More results: http://www.vegvesen.no/Trafikkinformasjon/Reiseinformasjon/Trafikkmeldinger?%s' % urllib.urlencode({
							'type': 'fylke',
							'fylke': counties[c],
							}))
					break
				results.append('\002%s\002 - %s' % (message.find('heading').text, message.find('ingress').text))
		return results

	def keyword(self, nick, channel, kw, msg):
		if not len(msg):
			self.irc.msg(channel if not channel == self.irc.nickname else nick.split('!')[0], 'Usage: !traffic [ROADNO] [COUNTY]')
			return

		try:
			for line in self.traffic(msg.split()):
				self.irc.msg(nick.split('!')[0], line.encode('utf8'))
		except InvalidCountyException:
			self.irc.msg(channel if not channel == self.irc.nickname else nick.split('!')[0], 'Invalid county.')

if __name__ == '__main__':
	import sys
	m = Module(None)
	print '\n'.join(m.traffic(sys.argv[1:]))