-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
OpenWeatherMap.py
68 lines (57 loc) · 1.93 KB
/
OpenWeatherMap.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
import requests
from core.base.model.Intent import Intent
from core.base.model.AliceSkill import AliceSkill
from core.dialog.model.DialogSession import DialogSession
from core.util.Decorators import IntentHandler
class OpenWeatherMap(AliceSkill):
@IntentHandler('GetWeather')
@IntentHandler('AnswerCity', requiredState='answeringCity')
def getWeather(self, session: DialogSession):
if not self.getConfig('apiKey'):
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk('noApiKey')
)
return
city = session.slotRawValue('City') or self.getConfig('baseLocation')
if 'when' not in session.slots:
data = self._queryData(city=city)
if not data:
self.continueDialog(
sessionId=session.sessionId,
text=self.randomTalk('notFound', replace=[city]),
intentFilter=[Intent('AnswerCity')],
slot='CityNames',
currentDialogState='answeringCity'
)
else:
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk('currentWeather',
replace=[
city,
round(float(data['main']['temp']), 1),
data['weather'][0]['description']
]
)
)
else:
# TODO
self.endSession(sessionId=session.sessionId)
def _queryData(self, city: str, now: bool = True) -> dict:
"""
Queries data from open weather map api
:param city: string
:param now: timestamp
:return: dict()
"""
try:
api = 'weather' if now else 'forecast'
req = requests.get(url=f'https://api.openweathermap.org/data/2.5/{api}?q={city}&appid={self.getConfig("apiKey")}&lang={self.LanguageManager.activeLanguage}&units={self.getConfig("units")}')
if req.status_code != 200:
self.logWarning('API not reachable')
return dict()
return req.json()
except Exception as e:
self.logWarning(f'Open weather map api call failed: {e}')
return {}