Files
weather_bot/weather.py
2026-03-26 10:15:41 +03:00

65 lines
3.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import aiohttp
async def get_coords_by_city(city_name: str):
"""Ищет координаты по названию города."""
url = f"https://geocoding-api.open-meteo.com/v1/search?name={city_name}&count=1&language=ru&format=json"
async with aiohttp.ClientSession() as session:
try:
# Добавили таймаут 5 секунд
async with session.get(url, timeout=5) as response:
if response.status != 200:
return None, None, None
data = await response.json()
results = data.get("results")
if not results:
return None, None, None
city_data = results[0]
return city_data.get("latitude"), city_data.get("longitude"), city_data.get("name", city_name)
except Exception:
return None, None, None
async def get_daily_weather_summary(lat: float, lon: float) -> str:
"""Получает текущую погоду и сводку на день по координатам."""
url = (
f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}"
f"&current=temperature_2m"
f"&daily=temperature_2m_max,temperature_2m_min,precipitation_probability_max"
f"&timezone=auto&forecast_days=1"
)
async with aiohttp.ClientSession() as session:
try:
async with session.get(url, timeout=5) as response:
if response.status != 200:
return "Не удалось получить данные о погоде от сервера."
data = await response.json()
current = data.get("current", {})
daily = data.get("daily", {})
if not daily or not current:
return "Ошибка парсинга данных о погоде."
current_temp = current.get("temperature_2m", "N/A")
temp_max = daily["temperature_2m_max"][0]
temp_min = daily["temperature_2m_min"][0]
precip_prob = daily["precipitation_probability_max"][0]
temp_diff = round(temp_max - temp_min, 1)
summary = (
f"🌤 **Погода на сегодня:**\n\n"
f"🌡 **Сейчас:** {current_temp}°C\n"
f"📊 **Дневная норма:** от {temp_min}°C до {temp_max}°C\n"
f"📉 **Перепад температур за день:** {temp_diff}°C\n"
f"🌧 **Макс. вероятность осадков:** {precip_prob}%\n\n"
f"Одевайтесь по погоде и хорошего дня!"
)
return summary
except Exception as e:
return "Служба погоды временно недоступна."