chore: migrate pogoda to wttr.in, fix bot stop, add on_command_error

This commit is contained in:
deadzilla 2026-05-24 22:55:49 +05:00
parent 89f17d53d8
commit 5dc6c54bf6
2 changed files with 68 additions and 68 deletions

31
bot.py
View File

@ -5,6 +5,8 @@ import threading
import discord import discord
from discord.ext import commands from discord.ext import commands
from discord.ext.commands import CommandNotFound
from discord.ext.commands import CommandNotFound
from dotenv import load_dotenv from dotenv import load_dotenv
from commands import ALL_COMMANDS from commands import ALL_COMMANDS
@ -28,6 +30,20 @@ async def on_ready():
print(f" Загружен: {cog}") print(f" Загружен: {cog}")
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, CommandNotFound):
return
print(f"Ошибка команды: {error}")
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, CommandNotFound):
return
print(f"Ошибка команды: {error}")
@bot.command(name="msg") @bot.command(name="msg")
async def msg(ctx, *, text: str): async def msg(ctx, *, text: str):
"""Повторяет текст после !msg""" """Повторяет текст после !msg"""
@ -41,19 +57,13 @@ def console_input():
if cmd == "stop": if cmd == "stop":
print("\nОстановка бота...") print("\nОстановка бота...")
stop_event.set() stop_event.set()
try: asyncio.run_coroutine_threadsafe(bot.close(), bot.loop).result()
bot.loop.stop()
except (AttributeError, RuntimeError):
pass
break break
elif cmd: elif cmd:
print(f"Неизвестная команда: {cmd}") print(f"Неизвестная команда: {cmd}")
except EOFError: except EOFError:
stop_event.set() stop_event.set()
try: asyncio.run_coroutine_threadsafe(bot.close(), bot.loop).result()
bot.loop.stop()
except (AttributeError, RuntimeError):
pass
break break
@ -71,9 +81,6 @@ if __name__ == "__main__":
bot.run(token) bot.run(token)
except KeyboardInterrupt: except KeyboardInterrupt:
print("\nОстановка бота...") print("\nОстановка бота...")
try:
bot.loop.stop()
except (AttributeError, RuntimeError):
pass
stop_event.set() stop_event.set()
asyncio.run_coroutine_threadsafe(bot.close(), bot.loop).result()
sys.exit(0) sys.exit(0)

View File

@ -7,81 +7,74 @@ class Pogoda(commands.Cog):
"""Команда !pogoda — прогноз погоды для Магнитогорска""" """Команда !pogoda — прогноз погоды для Магнитогорска"""
def __init__(self): def __init__(self):
self.api_url = "https://api.open-meteo.com/v1/forecast" self.api_url = "https://wttr.in/Magnitogorsk?format=j1&lang=ru"
self.lat = 53.41
self.lon = 59.06
@commands.command(name="pogoda") @commands.command(name="pogoda")
async def pogoda(self, ctx): async def pogoda(self, ctx):
params = {
"latitude": self.lat,
"longitude": self.lon,
"current": "temperature_2m,weather_code,relative_humidity_2m,wind_speed_10m,pressure_msl",
"timezone": "Asia/Yekaterinburg",
}
try: try:
response = requests.get(self.api_url, params=params, timeout=10) response = requests.get(self.api_url, timeout=10)
response.raise_for_status() response.raise_for_status()
data = response.json() data = response.json()
except requests.RequestException as e: except requests.RequestException as e:
await ctx.send(f"Ошибка при получении данных: {e}") await ctx.send(f"Ошибка при получении данных: {e}")
return return
current = data.get("current", {}) current = data.get("current_condition", [{}])[0]
if not current: if not current:
await ctx.send("Не удалось получить данные о погоде.") await ctx.send("Не удалось получить данные о погоде.")
return return
temp = current.get("temperature_2m", "") temp = current.get("temp_C", "")
weather_code = current.get("weather_code", "") feels_like = current.get("FeelsLikeC", "")
humidity = current.get("relative_humidity_2m", "") description = self._translate_weather(current.get("weatherDesc", [{}])[0].get("value", ""))
wind = current.get("wind_speed_10m", "") humidity = current.get("humidity", "")
pressure = current.get("pressure_msl", "") wind_kmh = current.get("windspeedKmph", "")
wind = round(int(wind_kmh) / 3.6, 1) if wind_kmh != "" else ""
pressure_mb = current.get("pressure", "")
description = self._get_weather_description(weather_code) pressure_mm = self._pressure_to_mmhg(pressure_mb)
pressure_mm = self._pressure_to_mmhg(pressure)
await ctx.send( await ctx.send(
f"🌡 Температура: {temp}°C\n" f"[TEMP] Температура: {temp}°C (ощущается как {feels_like}°C)\n"
f"📝 Описание: {description}\n" f"[DESC] Описание: {description}\n"
f"💧 Влажность: {humidity}%\n" f"[HUMID] Влажность: {humidity}%\n"
f"💨 Ветер: {wind} км/ч\n" f"[WIND] Ветер: {wind} м/с\n"
f"🌍 Давление: {pressure_mm} мм рт. ст." f"[PRESS] Давление: {pressure_mm} мм рт. ст."
) )
def _get_weather_description(self, code): def _translate_weather(self, en):
descriptions = { mapping = {
0: "Ясно", "Sunny": "Ясно",
1: "Преимущественно ясно", "Clear": "Ясно",
2: "Переменная облачность", "Partly cloudy": "Переменная облачность",
3: "Пасмурно", "Cloudy": "Облачно",
45: "Туман", "Overcast": "Пасмурно",
48: "Изморозь", "Mist": "Туман",
51: "Лёгкая морось", "Fog": "Туман",
53: "Морось", "Patchy rain nearby": "Местами дождь",
55: "Сильная морось", "Light rain": "Небольшой дождь",
61: "Небольшой дождь", "Moderate rain": "Умеренный дождь",
63: "Дождь", "Heavy rain": "Сильный дождь",
65: "Сильный дождь", "Patchy snow nearby": "Местами снег",
66: "Ледяной дождь", "Light snow": "Небольшой снег",
67: "Сильный ледяной дождь", "Heavy snow": "Сильный снег",
71: "Небольшой снег", "Patchy sleet nearby": "Местами слякоть",
73: "Снег", "Blowing snow": "Метель",
75: "Сильный снег", "Thundery outbreaks in nearby": "Гроза вблизи",
77: "Снежная крупа", "Moderate or heavy snow in area": "Снег",
80: "Небольшой ливень", "Moderate or heavy rain in area": "Дождь",
81: "Ливень", "Moderate or heavy freezing rain in area": "Ледяной дождь",
82: "Сильный ливень", "Moderate or heavy sleet in area": "Слякоть",
85: "Небольшой снегопад", "Ice pellets": "Ледяные кристаллы",
86: "Сильный снегопад", "Haze": "Дымка",
95: "Гроза", "Foggy": "Туманно",
96: "Гроза с градом",
99: "Сильная гроза с градом",
} }
return descriptions.get(code, "Неизвестно") for key, value in mapping.items():
if key.lower() in en.lower():
return value
return en
def _pressure_to_mmhg(self, hpa): def _pressure_to_mmhg(self, mb):
if hpa == "": if mb == "":
return "" return ""
return round(hpa * 0.750062, 1) return round(int(mb) * 0.750062, 1)