nxy/bot/plugins/weather.py

45 lines
1.7 KiB
Python
Raw Normal View History

2017-05-28 10:27:50 +00:00
# -*- coding: utf-8 -*-
import irc3
import requests
from docopt import Dict as DocOptDict
from irc3.plugins.command import command
from irc3.utils import IrcString
from . import Plugin
@irc3.plugin
class Weather(Plugin):
requires = ['irc3.plugins.command']
2017-05-30 10:44:44 +00:00
URL = 'https://query.yahooapis.com/v1/public/yql?format=json&q=' \
'select * from weather.forecast where u="c" and woeid in ' \
'(select woeid from geo.places(1) where text="{}")'
2017-05-28 10:27:50 +00:00
@command
def weather(self, mask: IrcString, target: IrcString, args: DocOptDict):
2017-05-30 10:44:44 +00:00
"""Gets the weather from Yahoo weather API.
2017-05-28 10:27:50 +00:00
%%weather <location>...
"""
2017-05-30 10:44:44 +00:00
req = requests.get(self.URL.format(' '.join(args['<location>'])))
2017-05-28 10:27:50 +00:00
data = req.json()
if 'error' in data:
2017-06-30 18:14:02 +00:00
return '\x02[Weather]\x0F Error'
elif not data['query']['results']:
return '\x02[Weather]\x0F Location not found'
else:
res = data['query']['results']['channel']
return '\x02[Weather]\x0F {city}, {region}, {country}: ' \
'\x02{temp}°{unit_temp} {text}\x0F, ' \
'\x02{direction} {speed} {unit_speed}\x0F' \
.format(city=res['location']['city'],
region=res['location']['region'].strip(),
country=res['location']['country'],
temp=res['item']['condition']['temp'],
text=res['item']['condition']['text'],
2017-07-07 00:11:20 +00:00
direction='↑↗→↘↓↙←↖'[round(int(res['wind']['direction']) / 45) % 8],
2017-06-30 18:14:02 +00:00
speed=res['wind']['speed'],
unit_temp=res['units']['temperature'],
unit_speed=res['units']['speed'])