myircbot/plugins/weather.py
2025-05-29 22:58:53 +02:00

66 lines
2.0 KiB
Python
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import requests
import logging
# Configurar el logger principal
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s"
)
API_KEY = os.getenv("WEATHER_API_KEY")
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
def fetch_weather(city):
"""Obtiene el clima de una ciudad desde OpenWeather."""
if not API_KEY:
logging.error("[WEATHER] No se encontró WEATHER_API_KEY en el entorno.")
return "Error: La API Key no está configurada."
params = {
"q": city,
"appid": API_KEY,
"units": "metric", # °C
"lang": "es"
}
try:
response = requests.get(BASE_URL, params=params, timeout=10)
data = response.json()
if response.status_code == 200 and "main" in data:
temp = data["main"].get("temp", "N/A")
desc = data["weather"][0].get("description", "N/A").capitalize()
humidity = data["main"].get("humidity", "N/A")
wind_speed = data["wind"].get("speed", "N/A")
return (
f" Clima en {city}: {temp}°C, {desc}\n"
f" Humedad: {humidity}%\n"
f" Viento: {wind_speed} m/s"
)
elif response.status_code == 404:
logging.warning(f"[WEATHER] Ciudad no encontrada: {city}")
return f"No se encontró información del clima para '{city}'."
else:
logging.error(f"[WEATHER] Error en la API. Código: {response.status_code}, data: {data}")
return "Error al obtener los datos del clima."
except requests.exceptions.RequestException as e:
logging.exception("[WEATHER] Error conectando con OpenWeather.")
return f"Error al conectar con OpenWeather: {e}"
def run(sender, *args):
if not args:
return help()
ciudad = " ".join(args)
return fetch_weather(ciudad)
def help():
return """.weather <ciudad> - Muestra el clima actual.
Ejemplo: .weather Madrid"""