Team Ai
Apppublic

azils3/bash

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
weather.py177 linesDownload Raw Back to plugins
1# Ultroid ~ UserBot2# Copyright (C) 2023-2024 TeamUltroid3#4# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >5# PLease read the GNU Affero General Public License in6# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.7 8"""9**Get Weather Data using OpenWeatherMap API**10❍  Commands Available -11 12• `{i}weather` <city name>13    Shows the Weather of Cities14 15• `{i}air` <city name>16    Shows the Air Condition of Cities17"""18 19import datetime20import time21from datetime import timedelta22 23import aiohttp24import pytz25 26from . import async_searcher, get_string, udB, ultroid_cmd27 28 29async def get_timezone(offset_seconds, use_utc=False):30    offset = timedelta(seconds=offset_seconds)31    hours, remainder = divmod(offset.seconds, 3600)32    sign = "+" if offset.total_seconds() >= 0 else "-"33    timezone = "UTC" if use_utc else "GMT"34    if use_utc:35        for m in pytz.all_timezones:36            tz = pytz.timezone(m)37            now = datetime.datetime.now(tz)38            if now.utcoffset() == offset:39                return f"{m} ({timezone}{sign}{hours:02d})"40    else:41        for m in pytz.all_timezones:42            tz = pytz.timezone(m)43            if m.startswith("Australia/"):44                now = datetime.datetime.now(tz)45                if now.utcoffset() == offset:46                    return f"{m} ({timezone}{sign}{hours:02d})"47        for m in pytz.all_timezones:48            tz = pytz.timezone(m)49            now = datetime.datetime.now(tz)50            if now.utcoffset() == offset:51                return f"{m} ({timezone}{sign}{hours:02d})"52        return "Timezone not found"53 54async def getWindinfo(speed: str, degree: str) -> str:55    dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]56    ix = round(degree / (360.00 / len(dirs)))57    kmph = str(float(speed) * 3.6) + " km/h"58    return f"[{dirs[ix % len(dirs)]}] {kmph}"59 60async def get_air_pollution_data(latitude, longitude, api_key):61    url = f"http://api.openweathermap.org/data/2.5/air_pollution?lat={latitude}&lon={longitude}&appid={api_key}"62    async with aiohttp.ClientSession() as session:63        async with session.get(url) as response:64            data = await response.json()65            if "list" in data:66                air_pollution = data["list"][0]67                return air_pollution68            else:69                return None70 71 72@ultroid_cmd(pattern="weather ?(.*)")73async def weather(event):74    if event.fwd_from:75        return76    msg = await event.eor(get_string("com_1"))77    x = udB.get_key("OPENWEATHER_API")78    if x is None:79        await event.eor(80            "No API found. Get One from [Here](https://api.openweathermap.org)\nAnd Add it in OPENWEATHER_API Redis Key",81            time=8,82        )83        return84    input_str = event.pattern_match.group(1)85    if not input_str:86        await event.eor("No Location was Given...", time=5)87        return88    elif input_str == "butler":89        await event.eor("search butler,au for australila", time=5)90    sample_url = f"https://api.openweathermap.org/data/2.5/weather?q={input_str}&APPID={x}&units=metric"91    try:92        response_api = await async_searcher(sample_url, re_json=True)93        if response_api["cod"] == 200:94            country_time_zone = int(response_api["timezone"])95            tz = f"{await get_timezone(country_time_zone)}"96            sun_rise_time = int(response_api["sys"]["sunrise"]) + country_time_zone97            sun_set_time = int(response_api["sys"]["sunset"]) + country_time_zone98            await msg.edit(99                f"{response_api['name']}, {response_api['sys']['country']}\n\n"100                f"╭────────────────•\n"101                f"╰➢ **𝖶𝖾𝖺𝗍𝗁𝖾𝗋:** {response_api['weather'][0]['description']}\n"102                f"╰➢ **𝖳𝗂𝗆𝖾𝗓𝗈𝗇𝖾:** {tz}\n"103                f"╰➢ **𝖲𝗎𝗇𝗋𝗂𝗌𝖾:** {time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(sun_rise_time))}\n"104                f"╰➢ **𝖲𝗎𝗇𝗌𝖾𝗍:** {time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(sun_set_time))}\n"105                f"╰➢ **𝖶𝗂𝗇𝖽:** {await getWindinfo(response_api['wind']['speed'], response_api['wind']['deg'])}\n"106                f"╰➢ **𝖳𝖾𝗆𝗉𝖾𝗋𝖺𝗍𝗎𝗋𝖾:** {response_api['main']['temp']}°C\n"107                f"╰➢ **𝖥𝖾𝖾𝗅𝗌 𝗅𝗂𝗄𝖾:** {response_api['main']['feels_like']}°C\n"108                f"╰➢ **𝖬𝗂𝗇𝗂𝗆𝗎𝗆:** {response_api['main']['temp_min']}°C\n"109                f"╰➢ **𝖬𝖺𝗑𝗂𝗆𝗎𝗆:** {response_api['main']['temp_max']}°C\n"110                f"╰➢ **𝖯𝗋𝖾𝗌𝗌𝗎𝗋𝖾:** {response_api['main']['pressure']} hPa\n"111                f"╰➢ **𝖧𝗎𝗆𝗂𝖽𝗂𝗍𝗒:** {response_api['main']['humidity']}%\n"112                f"╰➢ **𝖵𝗂𝗌𝗂𝖻𝗂𝗅𝗂𝗍𝗒:** {response_api['visibility']} m\n"113                f"╰➢ **𝖢𝗅𝗈𝗎𝖽𝗌:** {response_api['clouds']['all']}%\n"114                f"╰────────────────•\n\n"115            )116        else:117            await msg.edit(response_api["message"])118    except Exception as e:119        await event.eor(f"An unexpected error occurred: {str(e)}", time=5)120 121 122@ultroid_cmd(pattern="air ?(.*)")123async def air_pollution(event):124    if event.fwd_from:125        return126    msg = await event.eor(get_string("com_1"))127    x = udB.get_key("OPENWEATHER_API")128    if x is None:129        await event.eor(130            "No API found. Get One from [Here](https://api.openweathermap.org)\nAnd Add it in OPENWEATHER_API Redis Key",131            time=8,132        )133        return134    input_str = event.pattern_match.group(1)135    if not input_str:136        await event.eor("`No Location was Given...`", time=5)137        return138    if input_str.lower() == "perth":139        geo_url = f"https://geocode.xyz/perth%20au?json=1"140    else:141        geo_url = f"https://geocode.xyz/{input_str}?json=1"142    geo_data = await async_searcher(geo_url, re_json=True)143    try:144        longitude = geo_data["longt"]145        latitude = geo_data["latt"]146    except KeyError as e:147        LOGS.info(e)148        await event.eor("`Unable to find coordinates for the given location.`", time=5)149        return150    try:151        city = geo_data["standard"]["city"]152        prov = geo_data["standard"]["prov"]153    except KeyError as e:154        LOGS.info(e)155        await event.eor("`Unable to find city for the given coordinates.`", time=5)156        return157    air_pollution_data = await get_air_pollution_data(latitude, longitude, x)158    if air_pollution_data is None:159        await event.eor(160            "`Unable to fetch air pollution data for the given location.`", time=5161        )162        return163    await msg.edit(164        f"{city}, {prov}\n\n"165        f"╭────────────────•\n"166        f"╰➢ **𝖠𝖰𝖨:** {air_pollution_data['main']['aqi']}\n"167        f"╰➢ **𝖢𝖺𝗋𝖻𝗈𝗇 𝖬𝗈𝗇𝗈𝗑𝗂𝖽𝖾:** {air_pollution_data['components']['co']}µg/m³\n"168        f"╰➢ **𝖭𝗈𝗂𝗍𝗋𝗈𝗀𝖾𝗇 𝖬𝗈𝗇𝗈𝗑𝗂𝖽𝖾:** {air_pollution_data['components']['no']}µg/m³\n"169        f"╰➢ **𝖭𝗂𝗍𝗋𝗈𝗀𝖾𝗇 𝖣𝗂𝗈𝗑𝗂𝖽𝖾:** {air_pollution_data['components']['no2']}µg/m³\n"170        f"╰➢ **𝖮𝗓𝗈𝗇𝖾:** {air_pollution_data['components']['o3']}µg/m³\n"171        f"╰➢ **𝖲𝗎𝗅𝗉𝗁𝗎𝗋 𝖣𝗂𝗈𝗑𝗂𝖽𝖾:** {air_pollution_data['components']['so2']}µg/m³\n"172        f"╰➢ **𝖠𝗆𝗆𝗈𝗇𝗂𝖺:** {air_pollution_data['components']['nh3']}µg/m³\n"173        f"╰➢ **𝖥𝗂𝗇𝖾 𝖯𝖺𝗋𝗍𝗂𝖼𝗅𝖾𝗌 (PM₂.₅):** {air_pollution_data['components']['pm2_5']}\n"174        f"╰➢ **𝖢𝗈𝖺𝗋𝗌𝖾 𝖯𝖺𝗋𝗍𝗂𝖼𝗅𝖾𝗌 (PM₁₀):** {air_pollution_data['components']['pm10']}\n"175        f"╰────────────────•\n\n"176    )177