forked from andrewtryder/WorldTime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.py
More file actions
274 lines (230 loc) · 8.94 KB
/
plugin.py
File metadata and controls
274 lines (230 loc) · 8.94 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
###
# Copyright (c) 2014, spline
# Copyright © MMXXIV, Barry Suridge
# All rights reserved.
###
# my libs
import json
import time
try:
import pendulum
except ImportError as ie:
raise ImportError(f"Cannot import module: {ie}")
# supybot libs
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
import supybot.world as world
import supybot.conf as conf
import supybot.log as log
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization("WorldTime")
except ImportError:
_ = lambda x: x
filename = conf.supybot.directories.data.dirize("WorldTime.json")
HEADERS = {
"User-Agent": "Limnoria-WorldTime/1.0 (Supybot/Limnoria %s; +https://github.com/andrewtryder/WorldTime)"
% conf.version
}
REQUEST_TIMEOUT = 10
class WorldTime(callbacks.Plugin):
"""Look up the current local time and timezone for any location.
Uses the Google Geocoding and Time Zone APIs. Requires a Google
Maps API key to be configured via 'config plugins.worldtime.mapsapikey'.
Users can store their location with the 'set' command and then call
'worldtime' without arguments."""
threaded = True
###############################
# DATABASE HANDLING FUNCTIONS #
###############################
def __init__(self, irc):
self.__parent = super(WorldTime, self)
self.__parent.__init__(irc)
self.db = {}
self._loadDb()
world.flushers.append(self._flushDb)
def _loadDb(self):
"""Loads the (flatfile) database mapping ident@hosts to timezones."""
try:
with open(filename, "r", encoding="utf-8") as f:
self.db = json.load(f)
except FileNotFoundError:
log.info("WorldTime: Database file not found, initializing empty database.")
self.db = {}
except json.JSONDecodeError as e:
log.warning(f"WorldTime: Error decoding JSON database: {e}")
except Exception as e:
log.warning(f"WorldTime: Unable to load database: {e}")
def _flushDb(self):
"""Flushes the (flatfile) database mapping ident@hosts to timezones."""
try:
with open(filename, "w", encoding="utf-8") as f:
json.dump(self.db, f, indent=4)
except Exception as e:
log.warning(f"WorldTime: Unable to write database: {e}")
def die(self):
self._flushDb()
world.flushers.remove(self._flushDb)
self.__parent.die()
##################
# TIME FUNCTIONS #
##################
def _converttz(self, msg, outputTZ):
"""Convert current time to a readable string in a given timezone."""
try:
dt = pendulum.now(outputTZ)
outstrf = self.registryValue("format", msg.args[0])
return dt.strftime(outstrf)
except Exception as e:
log.info(f"WorldTime: ERROR: _converttz: {e}")
##############
# GAPI STUFF #
##############
def _getlatlng(self, location):
api_key = self.registryValue("mapsAPIkey")
location = utils.web.urlquote(location)
url = (
"https://maps.googleapis.com/maps/api/geocode/json?"
"address=%s&key=%s" % (location, api_key)
)
try:
response = utils.web.getUrl(url, headers=HEADERS, timeout=REQUEST_TIMEOUT)
except utils.web.Error as e:
log.debug(f"WorldTime: Error fetching URL: {e}")
return None
try:
result = json.loads(response.decode())
if result["status"] == "OK":
lat = str(result["results"][0]["geometry"]["location"]["lat"])
lng = str(result["results"][0]["geometry"]["location"]["lng"])
place = result["results"][0]["formatted_address"]
ll = f"{lat},{lng}"
return {"place": place, "ll": ll}
else:
log.error(f"_getlatlng: Status not OK. Result: {result}")
except Exception as e:
log.error(f"_getlatlng: {e}")
def _gettime(self, latlng):
api_key = self.registryValue("mapsAPIkey")
latlng = utils.web.urlquote(latlng)
url = (
"https://maps.googleapis.com/maps/api/timezone/json?location="
f"{latlng}×tamp={int(time.time())}&key={api_key}"
)
try:
response = utils.web.getUrl(url, headers=HEADERS, timeout=REQUEST_TIMEOUT)
except utils.web.Error as e:
log.debug(f"WorldTime: Error fetching URL: {e}")
return None
try:
result = json.loads(response.decode("utf-8"))
if result["status"] == "OK":
return result
else:
log.error(f"WorldTime: _gettime: Status not OK. Result: {result}")
except Exception as e:
log.info(f"WorldTime: _gettime: {e}")
###################
# PUBLIC FUNCTION #
###################
def worldtime(self, irc, msg, args, opts, location):
"""[--nick <nick>] [<location>]
Query GAPIs for <location> and attempt to figure out local time. [<location>]
is only required if you have not yet set a location for yourself using the 'set'
command. If --nick is given, try looking up the location for <nick>.
"""
opts = dict(opts)
if not self.registryValue("mapsAPIkey"):
irc.error(
"No Google Maps API key configured. Set one with: "
"config plugins.worldtime.mapsapikey <key>",
prefixNick=False,
Raise=True,
)
if not location:
try:
nick = opts.get("nick", None)
if nick:
if nick in irc.state.nicksToHostmasks:
host = irc.state.nickToHostmask(nick)
else:
irc.error(
f"Nickname '{nick}' not found in the bot's state.",
prefixNick=False,
Raise=True,
)
return
else:
host = msg.prefix
ih = host.split("!")[1]
location = self.db.get(ih)
if not location:
irc.error(
f"No location for {ircutils.bold('*!' + ih)} is set. "
"Use the 'set' command to set a location for your current hostmask, "
"or call 'worldtime' with <location> as an argument.",
prefixNick=False,
Raise=True,
)
except (KeyError, IndexError):
irc.error(
"Unable to resolve nickname or hostmask. Ensure the nick is in the channel "
"or the bot has seen the user before.",
prefixNick=False,
Raise=True,
)
# first, grab lat and long for user location
gc = self._getlatlng(location)
if not gc:
irc.error(
f"I could not find the location for: {location}.",
prefixNick=False,
Raise=True,
)
# next, grab the localtime for that location w/lat+long
ll = self._gettime(gc["ll"])
if not ll:
irc.error(
f"I could not find the local timezone for: {location}.",
prefixNick=False,
Raise=True,
)
# if we're here, we have localtime zone
lt = self._converttz(msg, ll["timeZoneId"])
if lt:
s = f"{ircutils.bold(gc['place'])} :: Current local time is: {lt} ({ll['timeZoneName']})"
if self.registryValue("disableANSI", msg.args[0]):
s = ircutils.stripFormatting(s)
irc.reply(s, prefixNick=False)
else:
irc.error(
"Something went wrong during conversion to timezone.",
prefixNick=False,
Raise=True,
)
worldtime = wrap(worldtime, [getopts({"nick": "nick"}), additional("text")])
def set(self, irc, msg, args, timezone):
"""<location>
Sets the location for your current ident@host to <location>."""
ih = msg.prefix.split("!")[1]
self.db[ih] = timezone
irc.replySuccess()
set = wrap(set, ["text"])
def unset(self, irc, msg, args):
"""takes no arguments.
Unsets the location for your current ident@host."""
ih = msg.prefix.split("!")[1]
try:
del self.db[ih]
irc.replySuccess()
except KeyError:
irc.error(
f"No entry for {ircutils.bold('*!' + ih)} exists.",
prefixNick=False,
Raise=True,
)
Class = WorldTime
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: