-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeoip.py
73 lines (60 loc) · 2.11 KB
/
geoip.py
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
#
# !locate [nick ...] Do a geoip look up for the given nicknames
# !geoip [host/ip ...] Do a geoip look up for the given ips or hosts
#
import json, urllib
from halibot import HalModule, HalConfigurer
class GeoIP(HalModule):
class Configurer(HalConfigurer):
def configure(self):
self.optionString('endpoint', prompt='API Endpoint', default='https://freegeoip.net/json/')
class NoHostnameException(Exception):
pass
def init(self):
pass
def queryHost(self, ip):
endpoint = self.config['endpoint']
rq = urllib.request.urlopen(endpoint + ip)
return json.loads(rq.read())
def queryNick(self, nick, agent):
if hasattr(agent, 'whois'):
hostname = agent.whois(nick)['hostname']
if '/' in hostname: # Invalid in hostnames
raise GeoIP.NoHostnameException()
try:
return self.queryHost(hostname)
except urllib.error.HTTPError as e:
raise GeoIP.NoHostnameException()
else:
raise GeoIP.NoHostnameException()
return None
def formatQuery(self, name, q):
if q != None:
# Format the result in a human-readable way
arr = [n for n in [q['city'], q['region_name'], q['country_name']] if n != '']
return name + ' is located in ' + ', '.join(arr)
else:
return 'Cannot locate ' + name
def receive(self, msg):
args = [a for a in msg.body.split(' ') if a != '']
if len(args) > 1:
if args[0] == '!locate':
if len(args) == 1:
args.append(msg.author)
for name in args[1:]:
originObj = msg.origin.split('/')[0] # TODO probably should have a message function for this
try:
q = self.queryNick(name, self._hal.objects[originObj])
self.reply(msg, body=self.formatQuery(name, q))
except GeoIP.NoHostnameException as e:
self.reply(msg, body='Cannot retrieve the hostname for ' + name)
if args[0] == '!geoip':
if len(args) > 1:
for host in args[1:]:
try:
q = self.queryHost(host)
self.reply(msg, body=self.formatQuery(host, q))
except urllib.error.HTTPError as e:
self.reply(msg, body='Cannot retrieve the location of ' + host)
else:
self.reply(msg, body='The !geoip command requires an argument')