· 5 years ago · Jul 16, 2020, 02:42 PM
1# Copyright (C) 2019 The Raphielscape Company LLC.
2#
3# Licensed under the Raphielscape Public License, Version 1.c (the "License");
4# you may not use this file except in compliance with the License.
5#
6""" Userbot module for getting the weather of a city. """
7
8import json
9from requests import get
10from datetime import datetime
11from pytz import country_timezones as c_tz
12from pytz import timezone as tz
13from pytz import country_names as c_n
14
15from userbot import CMD_HELP, WEATHER_DEFCITY
16from userbot import OPEN_WEATHER_MAP_APPID as OWM_API
17from userbot.events import register
18
19# ===== CONSTANT =====
20if WEATHER_DEFCITY:
21 DEFCITY = WEATHER_DEFCITY
22else:
23 DEFCITY = None
24# ====================
25
26
27async def get_tz(con):
28 """ Get time zone of the given country. """
29 """ Credits: @aragon12 and @zakaryan2004. """
30 for c_code in c_n:
31 if con == c_n[c_code]:
32 return tz(c_tz[c_code][0])
33 try:
34 if c_n[con]:
35 return tz(c_tz[con][0])
36 except KeyError:
37 return
38
39
40@register(outgoing=True, pattern="^\.weather(?: |$)(.*)")
41async def get_weather(weather):
42 """ For .weather command, gets the current weather of a city. """
43
44 if not OWM_API:
45 await weather.edit(
46 "`Get an API key from` https://openweathermap.org/ `first.`")
47 return
48
49 APPID = OWM_API
50 result = None
51
52 if not weather.pattern_match.group(1):
53 CITY = DEFCITY
54 if not CITY:
55 await weather.edit(
56 "`Please specify a city or set one as default using the WEATHER_DEFCITY config variable.`"
57 )
58 return
59 else:
60 CITY = weather.pattern_match.group(1)
61
62 timezone_countries = {
63 timezone: country
64 for country, timezones in c_tz.items() for timezone in timezones
65 }
66
67 if "," in CITY:
68 newcity = CITY.split(",")
69 if len(newcity[1]) == 2:
70 CITY = newcity[0].strip() + "," + newcity[1].strip()
71 else:
72 country = await get_tz((newcity[1].strip()).title())
73 try:
74 countrycode = timezone_countries[f'{country}']
75 except KeyError:
76 await weather.edit("`Invalid country.`")
77 return
78 CITY = newcity[0].strip() + "," + countrycode.strip()
79
80 url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
81 request = get(url)
82 result = json.loads(request.text)
83
84 if request.status_code != 200:
85 await weather.edit(f"`Invalid country.`")
86 return
87
88 cityname = result['name']
89 curtemp = result['main']['temp']
90 humidity = result['main']['humidity']
91 min_temp = result['main']['temp_min']
92 max_temp = result['main']['temp_max']
93 desc = result['weather'][0]
94 desc = desc['main']
95 country = result['sys']['country']
96 sunrise = result['sys']['sunrise']
97 sunset = result['sys']['sunset']
98 wind = result['wind']['speed']
99 winddir = result['wind']['deg']
100
101 ctimezone = tz(c_tz[country][0])
102 time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
103 fullc_n = c_n[f"{country}"]
104
105 dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
106
107 div = (360 / len(dirs))
108 funmath = int((winddir + (div / 2)) / div)
109 findir = dirs[funmath % len(dirs)]
110 kmph = str(wind * 3.6).split(".")
111 mph = str(wind * 2.237).split(".")
112
113 def fahrenheit(f):
114 temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
115 return temp[0]
116
117 def celsius(c):
118 temp = str((c - 273.15)).split(".")
119 return temp[0]
120
121 def sun(unix):
122 xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")
123 return xx
124
125 await weather.edit(
126 f"**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
127 +
128 f"**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
129 +
130 f"**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
131 + f"**Humidity:** `{humidity}%`\n" +
132 f"**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
133 f"**Sunrise:** `{sun(sunrise)}`\n" +
134 f"**Sunset:** `{sun(sunset)}`\n\n\n" + f"**{desc}**\n" +
135 f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
136
137
138CMD_HELP.update({
139 "weather":
140 ".weather <city> or .weather <city>, <country name/code>\
141 \nUsage: Gets the weather of a city."
142})