aboutsummaryrefslogtreecommitdiff
path: root/modules/location.py
blob: 1858a91582cecd66cb95616c82b20366379121e7 (about) (plain) (blame)
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
#--depends-on config
#--require-config opencagedata-api-key

import typing
from src import ModuleManager, utils

URL_OPENCAGE = "https://api.opencagedata.com/geocode/v1/json"

class Module(ModuleManager.BaseModule):
    def on_load(self):
        setting = utils.FunctionSetting(self._get_location, "location",
            "Set your location", example="London, GB")
        self.exports.add("set", setting)
        self.exports.add("get-location", self._get_location)

    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"]
            lat = result["geometry"]["lat"]
            lon = result["geometry"]["lng"]

            name_parts = []
            components = result["components"]
            for part in ["town", "city", "state", "country"]:
                if part in components:
                    name_parts.append(components[part])

            if not name_parts:
                name_parts.append(result["formatted"])

            name = ", ".join(name_parts)

            return {"timezone": timezone, "lat": lat, "lon": lon, "name": name}