Change location.py to use geocoding, change weather.py in line with it

This commit is contained in:
jesopo 2019-04-28 12:11:23 +01:00
parent 795a9a91af
commit cbed30ed62
2 changed files with 41 additions and 15 deletions

View file

@ -1,16 +1,25 @@
from src import ModuleManager, utils
import pytz
_lower_timezones = {}
for tz in pytz.all_timezones:
if "/" in tz:
_lower_timezones[tz.split("/", 1)[1].lower()] = tz
_lower_timezones[tz.lower()] = tz
URL_OPENCAGE = "https://api.opencagedata.com/geocode/v1/json"
def _find_tz(s):
return _lower_timezones.get(s.lower(), None)
@utils.export("set", {"setting": "location", "help": "Set your location",
"validate": _find_tz})
class Module(ModuleManager.BaseModule):
pass
def on_load(self):
self.exports.add("set", {"setting": "location",
"help": "Set your location", "validate": self._get_location,
"human": lambda x: "%s, %s" % (x["city"], x["country"])})
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"]
continent = result["components"]["continent"]
country = result["components"]["country"]
city = result["components"]["city"]
print("yes")
return {"timezone": timezone, "continent": continent,
"country": country, "city": city}

View file

@ -5,15 +5,32 @@ from src import ModuleManager, utils
URL_WEATHER = "http://api.openweathermap.org/data/2.5/weather"
class Module(ModuleManager.BaseModule):
@utils.hook("received.command.weather", min_args=1, usage="<location>")
def _user_location(self, user):
user_location = user.get_setting("location", None)
if not user_location == None:
return "%s, %s" % (user_location["city"], user_location["country"])
@utils.hook("received.command.weather", usage="<location>")
def weather(self, event):
"""
:help: Get current weather data for a provided location
:usage: <location>
:help: Get current weather for you or someone else
:usage: [nickname]
"""
api_key = self.bot.config["openweathermap-api-key"]
location = None
if event["args"]:
target_user = event["server"].get_user(event["args_split"][0])
location = self._user_location(target_user)
if location == None:
raise utils.EventError("%s doesn't have a location set")
else:
location = self._user_location(event["user"])
if location == None:
raise utils.EventError("You don't have a location set")
page = utils.http.request(URL_WEATHER, get_params={
"q": event["args"], "units": "metric",
"q": location, "units": "metric",
"APPID": api_key},
json=True)
if page: