forked from cacoyle/sopel-weather
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwz.py
81 lines (58 loc) · 2.08 KB
/
wz.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
import sopel.module
here_url = "https://geocoder.api.here.com/6.2/geocode.json"
here_app_id = ""
here_app_code = ""
darksky_url = "https://api.darksky.net/forecast"
darksky_key = ""
def unix_to_localtime(t, tz="US/Eastern"):
"""
Convert unix timestamp to local time.
"""
from datetime import datetime
from pytz import timezone
import pytz
utc = pytz.utc
tz = timezone(tz)
timestamp = datetime.utcfromtimestamp(t)
return(utc.localize(timestamp).astimezone(tz).strftime("%H:%M:%S"))
def get_temp_by_zip(zipcode):
"""
"""
import requests
location = requests.get(
here_url,
params={
"app_id": here_app_id,
"app_code": here_app_code,
"postalcode": zipcode
}
)
location_match = None
for result in location.json()["Response"]["View"][-1]["Result"]:
if result["Location"]["Address"]["Country"] in ["USA", "CAN"]:
location_match = result
break
else:
return(f"Unable to find a proper match for {zipcode}")
city = location_match["Location"]["Address"]["City"]
state = location_match["Location"]["Address"]["State"]
gps_loc = location_match["Location"]["NavigationPosition"][-1]
darksky_data = requests.get(
f"{darksky_url}/{darksky_key}/{gps_loc['Latitude']},{gps_loc['Longitude']}"
)
current = darksky_data.json()["currently"]
forecast = darksky_data.json()["daily"]["data"]
return(
f"{city}, {state} Conditions: {current['summary']} | "
f"Temp: {current['temperature']} | "
f"High: {forecast[0]['temperatureHigh']}, Low: {forecast[0]['temperatureLow']} | "
f"Humidity: {current['humidity']*100:.2f}% | "
f"Sunrise: {unix_to_localtime(forecast[0]['sunriseTime'])}, "
f"Sunset: {unix_to_localtime(forecast[0]['sunsetTime'])} | "
f"Today's Forecast: {forecast[0]['summary']}"
)
@sopel.module.commands('wz')
def weatherbot(bot, trigger):
bot.say(get_temp_by_zip(trigger.group(2)))
if __name__ == "__main__":
print(get_temp_by_zip('K4R1E5'))