2019-05-25 20:40:06 +00:00
|
|
|
#--depends-on config
|
|
|
|
|
2019-06-28 22:16:05 +00:00
|
|
|
import typing
|
2019-04-28 09:50:35 +00:00
|
|
|
from src import ModuleManager, utils
|
|
|
|
|
2019-04-28 11:11:23 +00:00
|
|
|
URL_OPENCAGE = "https://api.opencagedata.com/geocode/v1/json"
|
2019-04-28 09:50:35 +00:00
|
|
|
|
2019-06-28 22:16:05 +00:00
|
|
|
class LocationSetting(utils.Setting):
|
|
|
|
_func = None
|
|
|
|
def parse(self, value: str) -> typing.Any:
|
|
|
|
return self._func(value)
|
|
|
|
|
2019-04-28 09:50:35 +00:00
|
|
|
class Module(ModuleManager.BaseModule):
|
2019-04-28 11:11:23 +00:00
|
|
|
def on_load(self):
|
2019-06-28 22:16:05 +00:00
|
|
|
setting = LocationSetting("location", "Set your location",
|
|
|
|
example="London, GB")
|
|
|
|
setting._func = self._get_location
|
|
|
|
self.exports.add("set", setting)
|
2019-07-16 15:42:13 +00:00
|
|
|
self.exports.add("get-location", self._get_location)
|
2019-04-28 11:11:23 +00:00
|
|
|
|
|
|
|
def _get_location(self, s):
|
|
|
|
page = utils.http.request(URL_OPENCAGE, get_params={
|
|
|
|
"q": s, "key": self.bot.config["opencagedata-api-key"], "limit": "1"
|
|
|
|
}, json=True)
|
|
|
|
if page and page.data["results"]:
|
|
|
|
result = page.data["results"][0]
|
|
|
|
timezone = result["annotations"]["timezone"]["name"]
|
2019-04-28 14:38:26 +00:00
|
|
|
lat = result["geometry"]["lat"]
|
|
|
|
lon = result["geometry"]["lng"]
|
2019-06-18 15:50:46 +00:00
|
|
|
|
|
|
|
name_parts = []
|
|
|
|
components = result["components"]
|
2019-06-30 09:41:25 +00:00
|
|
|
for part in ["town", "city", "state", "country"]:
|
|
|
|
if part in components:
|
|
|
|
name_parts.append(components[part])
|
2019-06-18 15:50:46 +00:00
|
|
|
|
|
|
|
if not name_parts:
|
|
|
|
name_parts.append(result["formatted"])
|
|
|
|
|
|
|
|
name = ", ".join(name_parts)
|
2019-04-28 11:11:23 +00:00
|
|
|
|
2019-06-18 15:36:22 +00:00
|
|
|
return {"timezone": timezone, "lat": lat, "lon": lon, "name": name}
|