From ee8465b61eb82b9ba65f86e03dbfda10668b7551 Mon Sep 17 00:00:00 2001 From: Verum Date: Fri, 28 Feb 2025 13:30:19 +0700 Subject: [PATCH] =?UTF-8?q?1.4=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D1=8C=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=B3=D0=BE=D0=B4=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotCode/routers/commands/user_cmd/__init__.py | 2 + .../routers/commands/user_cmd/weather_cmd.py | 16 ++++++++ BotCode/utils/__init__.py | 3 +- BotCode/utils/weather_api.py | 41 +++++++++++++++++++ ProjectsFiles/configs/primoenv.py | 1 + 5 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 BotCode/routers/commands/user_cmd/weather_cmd.py create mode 100644 BotCode/utils/weather_api.py diff --git a/BotCode/routers/commands/user_cmd/__init__.py b/BotCode/routers/commands/user_cmd/__init__.py index 4c0e652..1900db8 100644 --- a/BotCode/routers/commands/user_cmd/__init__.py +++ b/BotCode/routers/commands/user_cmd/__init__.py @@ -6,6 +6,7 @@ from aiogram import Router from .start_cmd import start_cmd from .start_time_cmd import start_time_cmd from .help_cmd import help_cmd +from .weather_cmd import weather_cmd # Объявление роутера и настройка экспорта модулей __all__ = ("router",) @@ -16,6 +17,7 @@ router = Router(name="user_cmd_router") router.include_routers( help_cmd.router, start_time_cmd.router, + weather_cmd.router, ) router.include_routers(start_cmd.router) diff --git a/BotCode/routers/commands/user_cmd/weather_cmd.py b/BotCode/routers/commands/user_cmd/weather_cmd.py new file mode 100644 index 0000000..3bb41d7 --- /dev/null +++ b/BotCode/routers/commands/user_cmd/weather_cmd.py @@ -0,0 +1,16 @@ +# BotCode/routers/commands/user_cmd/start_time_cmd.py + +from aiogram import types +from BotLibrary import CommandHandler +from BotCode.utils import get_weather + +__all__ = ("weather_cmd",) + +weather_cmd = CommandHandler( + name="weather", + description="Погода", + keywords=["weather", "gjujlf", "цуферук", "погода"], + callbackdata=["keywords"], + media="command", + func=[get_weather], +) diff --git a/BotCode/utils/__init__.py b/BotCode/utils/__init__.py index 37236b5..6e759f0 100644 --- a/BotCode/utils/__init__.py +++ b/BotCode/utils/__init__.py @@ -2,9 +2,10 @@ # Инициализация пакета utils, для работы с механиками from aiogram import Router +from .weather_api import get_weather # Объявление роутера и настройка экспорта модулей -__all__ = ("router",) +__all__ = ("router", "get_weather") router = Router(name="utils_head_router") # Идет самым последним, если другие роутеры не сработали diff --git a/BotCode/utils/weather_api.py b/BotCode/utils/weather_api.py new file mode 100644 index 0000000..0c808c8 --- /dev/null +++ b/BotCode/utils/weather_api.py @@ -0,0 +1,41 @@ +import aiohttp +from ProjectsFiles import weather_api_key + + +async def get_weather(message, *args) -> str: + # Извлекаем город из сообщения + command_parts = message.text.split(maxsplit=1) + print(command_parts[1]) + if len(command_parts) > 1: + city = command_parts[1] + else: + return "Пожалуйста, укажите город." + + # Обработка города + city = city.lower().capitalize() + + # URL для запроса к API + url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={weather_api_key}&units=metric&lang=ru" + + try: + async with aiohttp.ClientSession() as session: + async with session.get(url) as response: + data = await response.json() + + if data["cod"] != 200: + return "Город не найден. Попробуйте еще раз." + + weather = data["weather"][0]["description"] + temp = data["main"]["temp"] + humidity = data["main"]["humidity"] + wind = data["wind"]["speed"] + + weather_today: str = (f"Погода {city}\n" + f"☁️Погода: {weather}\n" + f"🌡Температура: {temp}°C\n" + f"💧Влажность: {humidity}%\n" + f"💨Скорость ветра: {wind} м/с") + await message.answer(weather_today) + return weather_today + except Exception as e: + return f"Произошла ошибка при получении данных о погоде: {str(e)}" diff --git a/ProjectsFiles/configs/primoenv.py b/ProjectsFiles/configs/primoenv.py index 7998cf9..476b36d 100644 --- a/ProjectsFiles/configs/primoenv.py +++ b/ProjectsFiles/configs/primoenv.py @@ -15,6 +15,7 @@ bot2_token = getenv("BOT2_TOKEN") # Ключи от API api_key = getenv("API_KEY") web_api_key = getenv("WEB_API_KEY") +weather_api_key = getenv("WEATHER_API") # Хранилище сессии телеграмма tg_api_uid = getenv("TG_API_UID")