This repository has been archived by the owner on Apr 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 64
/
weather.py
100 lines (82 loc) · 3.91 KB
/
weather.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
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
# -*- coding: future_fstrings -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2019 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import logging
import pyowm
import math
from .. import loader, utils
from ..utils import escape_html as eh
logger = logging.getLogger(__name__)
def register(cb):
cb(WeatherMod())
def deg_to_text(deg):
if deg is None:
return _("unknown")
return ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW",
"SW", "WSW", "W", "WNW", "NW", "NNW"][round(deg / 22.5) % 16]
def round_to_sf(n, digits):
return round(n, digits - 1 - int(math.floor(math.log10(abs(n)))))
class WeatherMod(loader.Module):
"""Checks the weather
Get an API key at https://openweathermap.org/appid"""
def __init__(self):
self.config = loader.ModuleConfig("DEFAULT_LOCATION", None, "OpenWeatherMap City ID",
"API_KEY", None, "API Key from https://openweathermap.org/appid",
"TEMP_UNITS", "celsius", "Temperature unit as English")
self.name = _("Weather")
self._owm = None
def config_complete(self):
self._owm = pyowm.OWM(self.config["API_KEY"])
async def weathercmd(self, message):
""".weather [location]"""
if self.config["API_KEY"] is None:
await message.edit(_("<code>Please provide an API key via the configuration mode.</code>"))
return
args = utils.get_args_raw(message)
func = None
if not args:
func = self._owm.weather_at_id
args = [self.config["DEFAULT_LOCATION"]]
else:
try:
args = [int(args)]
func = self._owm.weather_at_id
except ValueError:
coords = utils.get_args_split_by(message, ",")
if len(coords) == 2:
try:
args = [int(coord.strip()) for coord in coords]
func = self._owm.weather_at_coords
except ValueError:
pass
if func is None:
func = self._owm.weather_at_place
args = [args]
logger.debug(func)
logger.debug(args)
w = await utils.run_sync(func, *args)
logger.debug(_("Weather at {args} is {w}").format(args=args, w=w))
try:
weather = w.get_weather()
temp = weather.get_temperature(self.config["TEMP_UNITS"])
except ValueError:
await message.edit(_("<code>Invalid temperature units provided. Please reconfigure the module.</code>"))
return
ret = _("<code>Weather in {loc} is {w} with a high of {high} and a low of {low}, "
+ "averaging at {avg} with {humid}% humidity and a {ws}mph {wd} wind.")
ret = ret.format(loc=eh(w.get_location().get_name()), w=eh(w.get_weather().get_detailed_status().lower()),
high=eh(temp["temp_max"]), low=eh(temp["temp_min"]), avg=eh(temp["temp"]),
humid=eh(weather.get_humidity()),
ws=eh(round_to_sf(weather.get_wind("miles_hour")["speed"], 3)),
wd=eh(deg_to_text(weather.get_wind().get("deg", None))))
await message.edit(ret)