""" Telegram bot for the ski predictor system. Serves next-day predictions for three ski stations in northern Spain: - Valgrande-Pajares (/pajares) - San Isidro (/sanisidro) - Fuentes de Invierno (/fuentes) The bot reads predictions from the JSON file generated by the daily pipeline at data/processed/predictions_latest.json. Usage: Set the TELEGRAM_BOT_TOKEN environment variable and run: python -m bot.telegram_bot or call main() directly. """ import json import logging import os from pathlib import Path from telegram import Update from telegram.constants import ParseMode from telegram.ext import Application, CommandHandler, ContextTypes # --------------------------------------------------------------------------- # Logging # --------------------------------------------------------------------------- logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO, ) logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Paths # --------------------------------------------------------------------------- # Resolve project root relative to this file regardless of cwd. _PROJECT_ROOT = Path(__file__).resolve().parent.parent PREDICTIONS_FILE = _PROJECT_ROOT / "data" / "processed" / "predictions_latest.json" # --------------------------------------------------------------------------- # Station metadata (mirrors config/stations.yaml without adding a runtime # dependency on pyyaml inside the bot module itself). # --------------------------------------------------------------------------- STATIONS = { "pajares": { "name": "Valgrande-Pajares", "max_km": 22.0, }, "sanisidro": { "name": "San Isidro", "max_km": 31.0, }, "fuentes": { "name": "Fuentes de Invierno", "max_km": 8.6, }, } # --------------------------------------------------------------------------- # Prediction loading # --------------------------------------------------------------------------- def load_predictions() -> dict | None: """Load the latest predictions from the JSON file produced by the pipeline. Returns the parsed dictionary on success, or None if the file is missing or cannot be decoded. """ if not PREDICTIONS_FILE.exists(): logger.warning("Predictions file not found: %s", PREDICTIONS_FILE) return None try: with PREDICTIONS_FILE.open(encoding="utf-8") as fh: data = json.load(fh) logger.info("Predictions loaded from %s", PREDICTIONS_FILE) return data except json.JSONDecodeError as exc: logger.error("Failed to decode predictions file: %s", exc) return None # --------------------------------------------------------------------------- # Message formatting # --------------------------------------------------------------------------- _CROWD_LABELS = { "low": "Bajo", "medium": "Medio", "high": "Alto", } def _crowd_label(raw: str) -> str: """Translate a crowd level key to its Spanish display label.""" return _CROWD_LABELS.get(str(raw).lower(), raw.capitalize()) def _open_label(probability: float) -> str: """Return a human-readable open/closed label based on probability.""" if probability >= 0.70: return "Abierta" if probability >= 0.40: return "Probable apertura" return "Cerrada" def format_station_prediction(station_key: str, prediction: dict) -> str: """Build the Telegram Markdown message for a single station prediction. Args: station_key: One of 'pajares', 'sanisidro', 'fuentes'. prediction: Sub-dictionary for this station from predictions_latest.json. Returns: Formatted string ready to be sent with ParseMode.MARKDOWN_V2 (uses MarkdownV2 escaping where needed). """ meta = STATIONS[station_key] station_name = meta["name"] max_km = meta["max_km"] open_prob: float = prediction.get("station_open_probability", 0.0) km_open: float = prediction.get("km_open_prediction", 0.0) crowd_raw: str = prediction.get("crowd_level_prediction", "unknown") # Weather sub-dict is optional; provide sensible defaults. weather: dict = prediction.get("weather_forecast", {}) temp_min: float | None = weather.get("temperature_min") temp_max: float | None = weather.get("temperature_max") snowfall: float | None = weather.get("snowfall_cm") wind_speed: float | None = weather.get("wind_speed_kmh") wind_gust: float | None = weather.get("wind_gust_kmh") source: str = prediction.get("source", "prediccion hibrida (reglas + ML)") open_pct = int(round(open_prob * 100)) open_str = f"{_open_label(open_prob)} ({open_pct}% probabilidad)" crowd_str = _crowd_label(crowd_raw) km_str = f"{km_open:.1f} / {max_km:.1f}" # Build weather block only with available data. weather_lines: list[str] = [] if temp_min is not None and temp_max is not None: weather_lines.append(f"Temperatura: {temp_min:.0f}C / {temp_max:.0f}C") elif temp_max is not None: weather_lines.append(f"Temperatura maxima: {temp_max:.0f}C") if snowfall is not None: weather_lines.append(f"Nieve: {snowfall:.0f}cm nuevos") if wind_speed is not None and wind_gust is not None: weather_lines.append( f"Viento: {wind_speed:.0f} km/h (rachas {wind_gust:.0f} km/h)" ) elif wind_speed is not None: weather_lines.append(f"Viento: {wind_speed:.0f} km/h") weather_block = "" if weather_lines: weather_block = "\n*Tiempo previsto:*\n" + "\n".join(weather_lines) + "\n" message = ( f"*{station_name} \\- Prediccion para manana*\n" f"\n" f"Estado: {open_str}\n" f"Km esquiables: {km_str}\n" f"Nivel de afluencia: {crowd_str}\n" f"{weather_block}" f"\n_Fuente: {source}_" ) return message def _no_prediction_message(station_name: str) -> str: """Return a friendly error message when prediction data is unavailable.""" return ( f"Lo siento, no hay prediccion disponible para *{station_name}* en este " f"momento\\.\n\n" f"_El pipeline de datos se ejecuta diariamente\\. " f"Intentalo de nuevo mas tarde\\._" ) def _unavailable_message() -> str: """Return a message when the predictions file cannot be loaded at all.""" return ( "No se han podido cargar las predicciones\\.\n\n" "_Asegurate de que el pipeline diario se ha ejecutado correctamente\\. " "Intentalo de nuevo mas tarde\\._" ) # --------------------------------------------------------------------------- # Command handlers # --------------------------------------------------------------------------- async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Handle the /start command with a welcome message.""" text = ( "*Bienvenido al bot de prediccion de estaciones de esqui* \\!\n\n" "Este bot te informa sobre las condiciones previstas para el dia " "siguiente en tres estaciones de esqui del norte de Espana:\n\n" " \\- *Valgrande\\-Pajares*\n" " \\- *San Isidro*\n" " \\- *Fuentes de Invierno*\n\n" "Las predicciones combinan reglas operacionales y modelos de " "aprendizaje automatico basados en datos meteorologicos\\.\n\n" "Escribe /help para ver los comandos disponibles\\." ) await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN_V2) async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Handle the /help command with a list of available commands.""" text = ( "*Comandos disponibles:*\n\n" "/pajares \\— Prediccion para Valgrande\\-Pajares\n" "/sanisidro \\— Prediccion para San Isidro\n" "/fuentes \\— Prediccion para Fuentes de Invierno\n" "/all \\— Predicciones para las tres estaciones\n" "/help \\— Mostrar esta ayuda\n" ) await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN_V2) async def _send_station( update: Update, station_key: str, ) -> None: """Fetch and send the prediction for a single station. Args: update: Telegram Update object. station_key: One of 'pajares', 'sanisidro', 'fuentes'. """ station_name = STATIONS[station_key]["name"] predictions = load_predictions() if predictions is None: text = _unavailable_message() await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN_V2) return station_pred = predictions.get(station_key) if not station_pred: logger.warning("No prediction entry for station '%s'", station_key) text = _no_prediction_message(station_name) await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN_V2) return try: text = format_station_prediction(station_key, station_pred) except Exception as exc: # noqa: BLE001 logger.exception("Error formatting prediction for '%s': %s", station_key, exc) text = _no_prediction_message(station_name) await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN_V2) async def cmd_pajares(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Handle the /pajares command — prediction for Valgrande-Pajares.""" logger.info("User %s requested /pajares", update.effective_user.id) await _send_station(update, "pajares") async def cmd_sanisidro(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Handle the /sanisidro command — prediction for San Isidro.""" logger.info("User %s requested /sanisidro", update.effective_user.id) await _send_station(update, "sanisidro") async def cmd_fuentes(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Handle the /fuentes command — prediction for Fuentes de Invierno.""" logger.info("User %s requested /fuentes", update.effective_user.id) await _send_station(update, "fuentes") async def cmd_all(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Handle the /all command — predictions for all three stations.""" logger.info("User %s requested /all", update.effective_user.id) for station_key in ("pajares", "sanisidro", "fuentes"): await _send_station(update, station_key) # --------------------------------------------------------------------------- # Bot entry point # --------------------------------------------------------------------------- def main() -> None: """Build and start the Telegram bot using long-polling. Reads the bot token from the TELEGRAM_BOT_TOKEN environment variable. Raises: EnvironmentError: If TELEGRAM_BOT_TOKEN is not set. """ token = os.environ.get("TELEGRAM_BOT_TOKEN") if not token: raise EnvironmentError( "La variable de entorno TELEGRAM_BOT_TOKEN no esta definida. " "Configura el token del bot antes de iniciar." ) logger.info("Iniciando bot de prediccion de esqui...") app = Application.builder().token(token).build() app.add_handler(CommandHandler("start", cmd_start)) app.add_handler(CommandHandler("help", cmd_help)) app.add_handler(CommandHandler("pajares", cmd_pajares)) app.add_handler(CommandHandler("sanisidro", cmd_sanisidro)) app.add_handler(CommandHandler("fuentes", cmd_fuentes)) app.add_handler(CommandHandler("all", cmd_all)) logger.info("Bot listo. Esperando mensajes...") app.run_polling(allowed_updates=Update.ALL_TYPES) if __name__ == "__main__": main()