Files
skipredictor/bot/telegram_bot.py
T
dasemu 61b4d8334d feat(bot): add daily push notification subscription system
Add /suscribir and /desuscribir commands to the Telegram bot so users
can opt in to receive the next-day prediction automatically at 20:00
when the extended task fires. Subscribers are persisted in a new
notification_subscribers SQLite table with soft-delete semantics.
2026-03-17 17:46:02 +01:00

687 lines
23 KiB
Python

"""
Telegram bot for the ski predictor system.
Serves published predictions for three ski stations in northern Spain:
- Valgrande-Pajares (/pajares)
- San Isidro (/sanisidro)
- Fuentes de Invierno (/fuentes)
The bot reads forecasts from the ``current_forecasts`` / ``past_forecasts``
tables in SQLite and supports both single-station queries and multi-station
horizon commands.
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
import sys
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
from zoneinfo import ZoneInfo
import yaml
# Ensure the project root is importable when the bot is launched as a script
# (e.g. ``python bot/telegram_bot.py`` from start.sh or systemd).
_BOT_DIR = Path(__file__).resolve().parent
_PROJECT_ROOT = _BOT_DIR.parent
if str(_PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(_PROJECT_ROOT))
from telegram import Update
from telegram.constants import ParseMode
from telegram.ext import Application, CommandHandler, ContextTypes
from storage import SQLiteStore
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO,
)
logger = logging.getLogger(__name__)
# Avoid logging full Telegram API URLs, which include the bot token.
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
# ---------------------------------------------------------------------------
# Station metadata
# ---------------------------------------------------------------------------
_STATIONS_YAML = _PROJECT_ROOT / "config" / "stations.yaml"
def _load_station_metadata() -> dict[str, dict[str, Any]]:
"""Load bot-visible station metadata from the shared YAML config."""
with _STATIONS_YAML.open("r", encoding="utf-8") as fh:
raw = yaml.safe_load(fh) or {}
stations = raw.get("stations") or {}
return {
station_id: {
"name": station_cfg["name"],
"max_km": float(station_cfg["max_km_skiable"]),
}
for station_id, station_cfg in stations.items()
}
STATIONS = _load_station_metadata()
STATION_ORDER = tuple(STATIONS.keys())
DISPLAY_TIMEZONE = ZoneInfo("Europe/Madrid")
SAME_DAY_PREDICTION_CUTOFF_HOUR = 10
# ---------------------------------------------------------------------------
# Prediction loading
# ---------------------------------------------------------------------------
def _display_now(now: datetime | None = None) -> datetime:
"""Return the current local datetime used for prediction selection."""
if now is None:
return datetime.now(DISPLAY_TIMEZONE)
if now.tzinfo is None:
return now.replace(tzinfo=DISPLAY_TIMEZONE)
return now.astimezone(DISPLAY_TIMEZONE)
def _preferred_prediction_dates(now: datetime | None = None) -> list[str]:
"""Return preferred prediction dates ordered by current local time."""
local_now = _display_now(now)
today = local_now.date()
tomorrow = today + timedelta(days=1)
if local_now.hour < SAME_DAY_PREDICTION_CUTOFF_HOUR:
return [today.isoformat(), tomorrow.isoformat()]
return [tomorrow.isoformat(), today.isoformat()]
def prediction_dates_window(
*,
start_offset: int,
length: int,
now: datetime | None = None,
) -> list[str]:
"""Return a consecutive list of prediction dates from today."""
if length <= 0:
return []
base_date = _display_now(now).date()
return [
(base_date + timedelta(days=start_offset + offset)).isoformat()
for offset in range(length)
]
def _forecasts_to_payload(
rows: list[dict[str, Any]],
prediction_date: str | None = None,
) -> dict[str, Any] | None:
"""Convert flat forecast rows into the nested payload the bot expects.
Returns a dict with ``prediction_date`` and ``stations`` keys, or None
when *rows* is empty.
"""
if not rows:
return None
stations: dict[str, dict[str, Any]] = {}
first_date = prediction_date
for row in rows:
if prediction_date is not None and row["prediction_date"] != prediction_date:
continue
if first_date is None:
first_date = row["prediction_date"]
stations[row["station_id"]] = {
"station_name": row["station_id"],
"open_probability": row.get("open_probability"),
"km_open": row.get("km_open"),
"crowd_level": row.get("crowd_level"),
"weather_summary": row.get("weather_summary"),
"rule_overrides": json.loads(row["rule_notes_json"] or "[]")
if isinstance(row.get("rule_notes_json"), str)
else (row.get("rule_notes_json") or []),
"prediction_source": row.get("prediction_source"),
}
if not stations:
return None
return {
"generated_at": rows[0].get("generated_at"),
"prediction_date": first_date,
"stations": stations,
}
def load_predictions(
*,
now: datetime | None = None,
store: SQLiteStore | None = None,
) -> dict | None:
"""Load the predictions most relevant for the current hour.
Queries ``current_forecasts`` for the preferred prediction dates, falling
back to whatever is available.
"""
store = store or SQLiteStore()
all_rows = store.load_current_forecasts()
if not all_rows:
logger.warning(
"No hay ninguna predicción en current_forecasts (%s)",
store.db_path,
)
return None
for prediction_date in _preferred_prediction_dates(now):
payload = _forecasts_to_payload(all_rows, prediction_date)
if payload is not None:
logger.info(
"Predicciones cargadas desde current_forecasts (%s) para %s",
store.db_path,
prediction_date,
)
return payload
# Fallback: return the earliest date available in current_forecasts
payload = _forecasts_to_payload(all_rows, all_rows[0]["prediction_date"])
logger.info(
"Predicciones cargadas desde current_forecasts (%s) como fallback (%s)",
store.db_path,
payload.get("prediction_date") if payload else None,
)
return payload
def load_predictions_for_date(
prediction_date: str,
*,
store: SQLiteStore | None = None,
) -> dict | None:
"""Load the current forecasts for a specific target date."""
store = store or SQLiteStore()
all_rows = store.load_current_forecasts()
payload = _forecasts_to_payload(all_rows, prediction_date)
if payload is None:
logger.info(
"No hay predicción en current_forecasts (%s) para %s",
store.db_path,
prediction_date,
)
return None
logger.info(
"Predicciones cargadas desde current_forecasts (%s) para %s",
store.db_path,
prediction_date,
)
return payload
# ---------------------------------------------------------------------------
# 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 _extract_station_predictions(payload: dict[str, Any]) -> dict[str, dict[str, Any]]:
"""Return the per-station prediction map."""
stations = payload.get("stations")
if isinstance(stations, dict):
return stations
return {}
def _message_title(station_name: str, prediction_date: str | None) -> str:
"""Return the station header including the prediction date when known."""
if prediction_date:
return f"{station_name} - Predicción para {prediction_date}"
return f"{station_name} - Predicción vigente"
def format_station_prediction(
station_key: str,
prediction: dict[str, Any],
prediction_date: str | None = None,
) -> str:
"""Build the Telegram HTML message for a single station prediction.
Args:
station_key: One of 'pajares', 'sanisidro', 'fuentes'.
prediction: Sub-dictionary for this station from SQLite.
prediction_date: ISO date string for the prediction target day.
Returns:
Formatted string ready to be sent with ParseMode.HTML.
"""
meta = STATIONS[station_key]
station_name = meta["name"]
max_km = meta["max_km"]
open_prob = float(prediction.get("open_probability", 0.0))
km_open = float(prediction.get("km_open", 0.0))
crowd_raw = str(prediction.get("crowd_level", "unknown"))
weather_summary = prediction.get("weather_summary")
source = str(
prediction.get("prediction_source", "predicción híbrida (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}"
weather_block = ""
if weather_summary:
weather_block = f"\n<b>Tiempo previsto:</b>\n{weather_summary}\n"
overrides = prediction.get("rule_overrides") or []
reasons_block = ""
if overrides:
reasons_block = (
"\n<b>Notas:</b>\n" + "\n".join(f"• {reason}" for reason in overrides) + "\n"
)
message = (
f"<b>{_message_title(station_name, prediction_date)}</b>\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"{reasons_block}"
f"\n<i>Fuente: {source}</i>"
)
return message
def format_daily_predictions(payload: dict[str, Any]) -> str:
"""Build a single message containing the three stations for one day."""
prediction_date = payload.get("prediction_date")
station_predictions = _extract_station_predictions(payload)
sections: list[str] = []
for station_key in STATION_ORDER:
station_prediction = station_predictions.get(station_key)
if station_prediction:
sections.append(
format_station_prediction(
station_key,
station_prediction,
prediction_date,
)
)
continue
station_name = STATIONS[station_key]["name"]
sections.append(
(
f"<b>{_message_title(station_name, prediction_date)}</b>\n\n"
"No hay predicción disponible para esta estación."
)
)
return "\n\n".join(sections)
def _no_prediction_message(station_name: str) -> str:
"""Return a friendly error message when prediction data is unavailable."""
return (
f"Lo siento, no hay predicción disponible para <b>{station_name}</b> en este "
f"momento.\n\n"
f"<i>El pipeline de datos se ejecuta diariamente. "
f"Inténtalo de nuevo más tarde.</i>"
)
def _unavailable_message() -> str:
"""Return a message when published predictions cannot be loaded at all."""
return (
"No se han podido cargar las predicciones.\n\n"
"<i>Asegúrate de que el pipeline diario se ha ejecutado correctamente. "
"Inténtalo de nuevo más tarde.</i>"
)
def _missing_prediction_dates_message(prediction_dates: list[str]) -> str:
"""Return a message describing missing published dates."""
if len(prediction_dates) == 1:
return (
f"No hay predicción publicada para <b>{prediction_dates[0]}</b>.\n\n"
"<i>Inténtalo de nuevo más tarde cuando el pipeline haya generado "
"ese horizonte.</i>"
)
dates = "\n".join(f"• {prediction_date}" for prediction_date in prediction_dates)
return (
"Faltan predicciones publicadas para estas fechas:\n\n"
f"{dates}\n\n"
"<i>Inténtalo de nuevo más tarde cuando el pipeline haya generado "
"estos horizontes.</i>"
)
# ---------------------------------------------------------------------------
# Command handlers
# ---------------------------------------------------------------------------
async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle the /start command with a welcome message."""
text = (
"<b>¡Bienvenido al bot de predicción de estaciones de esquí!</b>\n\n"
"Este bot te informa sobre la predicción vigente para tres "
"estaciones de esquí del norte de España.\n"
"Hasta las 10:00 muestra preferentemente la predicción del mismo "
"día; después, la del día siguiente.\n\n"
" - <b>Valgrande-Pajares</b>\n"
" - <b>San Isidro</b>\n"
" - <b>Fuentes de Invierno</b>\n\n"
"Las predicciones combinan reglas operacionales y modelos de "
"aprendizaje automático basados en datos meteorológicos.\n\n"
"Escribe /help para ver los comandos disponibles."
)
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle the /help command with a list of available commands."""
text = (
"<b>Comandos disponibles:</b>\n\n"
"/pajares — Predicción para Valgrande-Pajares\n"
"/sanisidro — Predicción para San Isidro\n"
"/fuentes — Predicción para Fuentes de Invierno\n"
"/all — Predicción vigente para las tres estaciones\n"
"/hoy — Predicción de hoy para las tres estaciones\n"
"/manana — Predicción de mañana para las tres estaciones\n"
"/tresdias — Predicción de hoy y los dos días siguientes\n"
"/semana — Predicción de los próximos siete días\n"
"/suscribir — Recibir la predicción diaria a las 20:00\n"
"/desuscribir — Dejar de recibir la predicción diaria\n"
"/help — Mostrar esta ayuda\n"
)
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
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.HTML)
return
station_predictions = _extract_station_predictions(predictions)
station_pred = station_predictions.get(station_key)
if not station_pred:
logger.warning("No hay entrada de predicción para la estación '%s'", station_key)
text = _no_prediction_message(station_name)
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
return
try:
text = format_station_prediction(
station_key,
station_pred,
predictions.get("prediction_date"),
)
except Exception as exc: # noqa: BLE001
logger.exception("Error al formatear la predicción para '%s': %s", station_key, exc)
text = _no_prediction_message(station_name)
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
async def _send_prediction_day(
update: Update,
prediction_date: str,
*,
store: SQLiteStore,
) -> bool:
"""Send the three-station prediction for *prediction_date* when available."""
predictions = load_predictions_for_date(prediction_date, store=store)
if predictions is None:
return False
await update.message.reply_text(
format_daily_predictions(predictions),
parse_mode=ParseMode.HTML,
)
return True
async def _send_prediction_window(
update: Update,
*,
prediction_dates: list[str],
) -> None:
"""Send all available predictions in a date window and summarize gaps."""
store = SQLiteStore()
missing_dates: list[str] = []
sent_any = False
for prediction_date in prediction_dates:
sent = await _send_prediction_day(
update,
prediction_date,
store=store,
)
if sent:
sent_any = True
continue
missing_dates.append(prediction_date)
if not sent_any and prediction_dates:
await update.message.reply_text(
_missing_prediction_dates_message(prediction_dates),
parse_mode=ParseMode.HTML,
)
return
if missing_dates:
await update.message.reply_text(
_missing_prediction_dates_message(missing_dates),
parse_mode=ParseMode.HTML,
)
async def cmd_pajares(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle the /pajares command — prediction for Valgrande-Pajares."""
logger.info("El usuario %s solicitó /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("El usuario %s solicitó /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("El usuario %s solicitó /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("El usuario %s solicitó /all", update.effective_user.id)
predictions = load_predictions()
if predictions is None:
await update.message.reply_text(_unavailable_message(), parse_mode=ParseMode.HTML)
return
await update.message.reply_text(
format_daily_predictions(predictions),
parse_mode=ParseMode.HTML,
)
async def cmd_hoy(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle the /hoy command — three-station prediction for today."""
logger.info("El usuario %s solicitó /hoy", update.effective_user.id)
await _send_prediction_window(
update,
prediction_dates=prediction_dates_window(start_offset=0, length=1),
)
async def cmd_manana(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle the /manana command — three-station prediction for tomorrow."""
logger.info("El usuario %s solicitó /manana", update.effective_user.id)
await _send_prediction_window(
update,
prediction_dates=prediction_dates_window(start_offset=1, length=1),
)
async def cmd_tresdias(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle the /tresdias command — three-station predictions for 3 days."""
logger.info("El usuario %s solicitó /tresdias", update.effective_user.id)
await _send_prediction_window(
update,
prediction_dates=prediction_dates_window(start_offset=0, length=3),
)
async def cmd_semana(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle the /semana command — three-station predictions for 7 days."""
logger.info("El usuario %s solicitó /semana", update.effective_user.id)
await _send_prediction_window(
update,
prediction_dates=prediction_dates_window(start_offset=0, length=7),
)
async def cmd_suscribir(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle the /suscribir command -- subscribe to daily notifications."""
chat_id = update.effective_chat.id
username = update.effective_user.username if update.effective_user else None
logger.info("El usuario %s solicitó /suscribir", chat_id)
store = SQLiteStore()
is_new = store.subscribe_notifications(chat_id, username)
if is_new:
text = (
"Te has suscrito a las notificaciones diarias.\n"
"Recibirás la predicción de mañana cada día a las 20:00."
)
else:
text = "Ya estás suscrito a las notificaciones diarias."
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
async def cmd_desuscribir(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle the /desuscribir command -- unsubscribe from daily notifications."""
chat_id = update.effective_chat.id
logger.info("El usuario %s solicitó /desuscribir", chat_id)
store = SQLiteStore()
was_subscribed = store.unsubscribe_notifications(chat_id)
if was_subscribed:
text = "Has cancelado tu suscripción a las notificaciones diarias."
else:
text = "No estabas suscrito a las notificaciones diarias."
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
# ---------------------------------------------------------------------------
# Bot entry point
# ---------------------------------------------------------------------------
def create_bot_application(token: str | None = None) -> Application:
"""Build the Telegram Application with all handlers registered.
When *token* is None the ``TELEGRAM_BOT_TOKEN`` env var is used.
The returned Application has NOT been started yet — callers can either
use ``app.run_polling()`` (standalone) or manage the lifecycle manually
(in-process with FastAPI).
"""
token = token or os.environ.get("TELEGRAM_BOT_TOKEN")
if not token:
raise EnvironmentError(
"La variable de entorno TELEGRAM_BOT_TOKEN no está definida. "
"Configura el token del bot antes de iniciar."
)
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))
app.add_handler(CommandHandler("hoy", cmd_hoy))
app.add_handler(CommandHandler("manana", cmd_manana))
app.add_handler(CommandHandler("tresdias", cmd_tresdias))
app.add_handler(CommandHandler("semana", cmd_semana))
app.add_handler(CommandHandler("suscribir", cmd_suscribir))
app.add_handler(CommandHandler("desuscribir", cmd_desuscribir))
return app
def main() -> None:
"""Build and start the Telegram bot using long-polling (standalone mode).
Reads the bot token from the TELEGRAM_BOT_TOKEN environment variable.
"""
logger.info("Iniciando bot de predicción de esquí...")
app = create_bot_application()
logger.info("Bot listo. Esperando mensajes...")
app.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()