dragon-bot/app/weather.py
2017-09-21 18:40:46 -07:00

77 lines
3.0 KiB
Python

import requests
from pyowm import OWM
from pyowm import exceptions
days_from_ind = {0: 'Today', 1: 'Tomorrow', 2: 'Day after tomorrow'}
emojis = {'clear sky': ':sunny:', 'scattered clouds': ':partly_sunny:',
'light rain': ':white_sun_rain_cloud:', 'overcast clouds': ':cloud:',
'broken clouds': ':white_sun_cloud:', 'moderate rain': ':cloud_with_rain:',
'light snow': ':cloud_snow:', 'few clouds': ':white_sun_small_cloud:'}
openweathermap = OWM('593e0e182f9278a10443da354c4014db')
def parse_loc(message):
if len(message.split()) > 1:
try:
res = get_weather(' '.join(message.split()[1:]))
except exceptions.api_call_error.APICallError:
res = '```Please input a valid location: !weather [location]```'
return res
return '```Please input a valid location: !weather [location]```'
def get_weather(message):
"""
get_weather(location)
Returns the weather forecast for the selected location. Uses PythonOWM to
make life super easy.
TODO: Replace basic code block with nice looking, bold text w/ emojis
"""
try:
forecaster = openweathermap.three_hours_forecast(message)
forecast = forecaster.get_forecast()
reg = forecast.get(0)
location = forecast.get_location().get_name()
indicator = int(reg.get_reference_time(timeformat='iso')[11:13]) // 3
curr_stat = '{}{}{}{}{}'.format(' \n***Status in ', location, ':*** *',
reg.get_detailed_status().title(), '*\n')
curr_temp = '{}{}{}'.format('**Current Temperature:** *',
str(reg.get_temperature('fahrenheit').get('temp')),
'F*\n\n__**3 day forecast:**__\n')
forecast_str = '{}{}'.format(curr_stat, curr_temp)
ind = 0
for i in range((4 - indicator) % 8, int((3 * len(forecast)) / 5), 8):
high, low = 0, 100000
for j in range(0, 8):
if (i + j < (3 * len(forecast)) / 5):
day = forecast.get(i + j)
else:
break
temps = day.get_temperature('fahrenheit')
h = temps.get('temp_max')
l = temps.get('temp_min')
print(forecast.get(i + j).get_detailed_status())
if high < h:
high = h
if low > l:
low = l
day = '{}{}{}'.format('***', days_from_ind.get(ind), '***\n')
weather_stat = '{}{}{}{}{}'.format('**Status:** *',
forecast.get(i).get_detailed_status().title(),
'* ', emojis.get(forecast.get(i).get_detailed_status()), '\n')
high_temp = '{}{}{}'.format('**High:** *', str(high), 'F*\n')
low_temp = '{}{}{}'.format('**Low:** *', str(low), 'F*\n\n')
forecast_str = '{}{}{}{}{}'.format(
forecast_str, day, weather_stat, high_temp, low_temp)
ind += 1
return forecast_str
except exceptions.not_found_error.NotFoundError:
return 'Please input a valid location'