dragxd / plugins /weather.py
taslim19
Push entire Ultroid-main project to Hugging Face Space
1f26706
raw
history blame
8.11 kB
# Ultroid ~ UserBot
# Copyright (C) 2023-2024 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
**Get Weather Data using OpenWeatherMap API**
โ Commands Available -
โ€ข `{i}weather` <city name>
Shows the Weather of Cities
โ€ข `{i}air` <city name>
Shows the Air Condition of Cities
"""
import datetime
import time
from datetime import timedelta
import aiohttp
import pytz
from . import async_searcher, get_string, udB, ultroid_cmd
async def get_timezone(offset_seconds, use_utc=False):
offset = timedelta(seconds=offset_seconds)
hours, remainder = divmod(offset.seconds, 3600)
sign = "+" if offset.total_seconds() >= 0 else "-"
timezone = "UTC" if use_utc else "GMT"
if use_utc:
for m in pytz.all_timezones:
tz = pytz.timezone(m)
now = datetime.datetime.now(tz)
if now.utcoffset() == offset:
return f"{m} ({timezone}{sign}{hours:02d})"
else:
for m in pytz.all_timezones:
tz = pytz.timezone(m)
if m.startswith("Australia/"):
now = datetime.datetime.now(tz)
if now.utcoffset() == offset:
return f"{m} ({timezone}{sign}{hours:02d})"
for m in pytz.all_timezones:
tz = pytz.timezone(m)
now = datetime.datetime.now(tz)
if now.utcoffset() == offset:
return f"{m} ({timezone}{sign}{hours:02d})"
return "Timezone not found"
async def getWindinfo(speed: str, degree: str) -> str:
dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
ix = round(degree / (360.00 / len(dirs)))
kmph = str(float(speed) * 3.6) + " km/h"
return f"[{dirs[ix % len(dirs)]}] {kmph}"
async def get_air_pollution_data(latitude, longitude, api_key):
url = f"http://api.openweathermap.org/data/2.5/air_pollution?lat={latitude}&lon={longitude}&appid={api_key}"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.json()
if "list" in data:
air_pollution = data["list"][0]
return air_pollution
else:
return None
@ultroid_cmd(pattern="weather ?(.*)")
async def weather(event):
if event.fwd_from:
return
msg = await event.eor(get_string("com_1"))
x = udB.get_key("OPENWEATHER_API")
if x is None:
await event.eor(
"No API found. Get One from [Here](https://api.openweathermap.org)\nAnd Add it in OPENWEATHER_API Redis Key",
time=8,
)
return
input_str = event.pattern_match.group(1)
if not input_str:
await event.eor("No Location was Given...", time=5)
return
elif input_str == "butler":
await event.eor("search butler,au for australila", time=5)
sample_url = f"https://api.openweathermap.org/data/2.5/weather?q={input_str}&APPID={x}&units=metric"
try:
response_api = await async_searcher(sample_url, re_json=True)
if response_api["cod"] == 200:
country_time_zone = int(response_api["timezone"])
tz = f"{await get_timezone(country_time_zone)}"
sun_rise_time = int(response_api["sys"]["sunrise"]) + country_time_zone
sun_set_time = int(response_api["sys"]["sunset"]) + country_time_zone
await msg.edit(
f"{response_api['name']}, {response_api['sys']['country']}\n\n"
f"โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ€ข\n"
f"โ•ฐโžข **๐–ถ๐–พ๐–บ๐—๐—๐–พ๐—‹:** {response_api['weather'][0]['description']}\n"
f"โ•ฐโžข **๐–ณ๐—‚๐—†๐–พ๐—“๐—ˆ๐—‡๐–พ:** {tz}\n"
f"โ•ฐโžข **๐–ฒ๐—Ž๐—‡๐—‹๐—‚๐—Œ๐–พ:** {time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(sun_rise_time))}\n"
f"โ•ฐโžข **๐–ฒ๐—Ž๐—‡๐—Œ๐–พ๐—:** {time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(sun_set_time))}\n"
f"โ•ฐโžข **๐–ถ๐—‚๐—‡๐–ฝ:** {await getWindinfo(response_api['wind']['speed'], response_api['wind']['deg'])}\n"
f"โ•ฐโžข **๐–ณ๐–พ๐—†๐—‰๐–พ๐—‹๐–บ๐—๐—Ž๐—‹๐–พ:** {response_api['main']['temp']}ยฐC\n"
f"โ•ฐโžข **๐–ฅ๐–พ๐–พ๐—…๐—Œ ๐—…๐—‚๐—„๐–พ:** {response_api['main']['feels_like']}ยฐC\n"
f"โ•ฐโžข **๐–ฌ๐—‚๐—‡๐—‚๐—†๐—Ž๐—†:** {response_api['main']['temp_min']}ยฐC\n"
f"โ•ฐโžข **๐–ฌ๐–บ๐—‘๐—‚๐—†๐—Ž๐—†:** {response_api['main']['temp_max']}ยฐC\n"
f"โ•ฐโžข **๐–ฏ๐—‹๐–พ๐—Œ๐—Œ๐—Ž๐—‹๐–พ:** {response_api['main']['pressure']} hPa\n"
f"โ•ฐโžข **๐–ง๐—Ž๐—†๐—‚๐–ฝ๐—‚๐—๐—’:** {response_api['main']['humidity']}%\n"
f"โ•ฐโžข **๐–ต๐—‚๐—Œ๐—‚๐–ป๐—‚๐—…๐—‚๐—๐—’:** {response_api['visibility']} m\n"
f"โ•ฐโžข **๐–ข๐—…๐—ˆ๐—Ž๐–ฝ๐—Œ:** {response_api['clouds']['all']}%\n"
f"โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ€ข\n\n"
)
else:
await msg.edit(response_api["message"])
except Exception as e:
await event.eor(f"An unexpected error occurred: {str(e)}", time=5)
@ultroid_cmd(pattern="air ?(.*)")
async def air_pollution(event):
if event.fwd_from:
return
msg = await event.eor(get_string("com_1"))
x = udB.get_key("OPENWEATHER_API")
if x is None:
await event.eor(
"No API found. Get One from [Here](https://api.openweathermap.org)\nAnd Add it in OPENWEATHER_API Redis Key",
time=8,
)
return
input_str = event.pattern_match.group(1)
if not input_str:
await event.eor("`No Location was Given...`", time=5)
return
if input_str.lower() == "perth":
geo_url = f"https://geocode.xyz/perth%20au?json=1"
else:
geo_url = f"https://geocode.xyz/{input_str}?json=1"
geo_data = await async_searcher(geo_url, re_json=True)
try:
longitude = geo_data["longt"]
latitude = geo_data["latt"]
except KeyError as e:
LOGS.info(e)
await event.eor("`Unable to find coordinates for the given location.`", time=5)
return
try:
city = geo_data["standard"]["city"]
prov = geo_data["standard"]["prov"]
except KeyError as e:
LOGS.info(e)
await event.eor("`Unable to find city for the given coordinates.`", time=5)
return
air_pollution_data = await get_air_pollution_data(latitude, longitude, x)
if air_pollution_data is None:
await event.eor(
"`Unable to fetch air pollution data for the given location.`", time=5
)
return
await msg.edit(
f"{city}, {prov}\n\n"
f"โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ€ข\n"
f"โ•ฐโžข **๐– ๐–ฐ๐–จ:** {air_pollution_data['main']['aqi']}\n"
f"โ•ฐโžข **๐–ข๐–บ๐—‹๐–ป๐—ˆ๐—‡ ๐–ฌ๐—ˆ๐—‡๐—ˆ๐—‘๐—‚๐–ฝ๐–พ:** {air_pollution_data['components']['co']}ยตg/mยณ\n"
f"โ•ฐโžข **๐–ญ๐—ˆ๐—‚๐—๐—‹๐—ˆ๐—€๐–พ๐—‡ ๐–ฌ๐—ˆ๐—‡๐—ˆ๐—‘๐—‚๐–ฝ๐–พ:** {air_pollution_data['components']['no']}ยตg/mยณ\n"
f"โ•ฐโžข **๐–ญ๐—‚๐—๐—‹๐—ˆ๐—€๐–พ๐—‡ ๐–ฃ๐—‚๐—ˆ๐—‘๐—‚๐–ฝ๐–พ:** {air_pollution_data['components']['no2']}ยตg/mยณ\n"
f"โ•ฐโžข **๐–ฎ๐—“๐—ˆ๐—‡๐–พ:** {air_pollution_data['components']['o3']}ยตg/mยณ\n"
f"โ•ฐโžข **๐–ฒ๐—Ž๐—…๐—‰๐—๐—Ž๐—‹ ๐–ฃ๐—‚๐—ˆ๐—‘๐—‚๐–ฝ๐–พ:** {air_pollution_data['components']['so2']}ยตg/mยณ\n"
f"โ•ฐโžข **๐– ๐—†๐—†๐—ˆ๐—‡๐—‚๐–บ:** {air_pollution_data['components']['nh3']}ยตg/mยณ\n"
f"โ•ฐโžข **๐–ฅ๐—‚๐—‡๐–พ ๐–ฏ๐–บ๐—‹๐—๐—‚๐–ผ๐—…๐–พ๐—Œ (PMโ‚‚.โ‚…):** {air_pollution_data['components']['pm2_5']}\n"
f"โ•ฐโžข **๐–ข๐—ˆ๐–บ๐—‹๐—Œ๐–พ ๐–ฏ๐–บ๐—‹๐—๐—‚๐–ผ๐—…๐–พ๐—Œ (PMโ‚โ‚€):** {air_pollution_data['components']['pm10']}\n"
f"โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ€ข\n\n"
)