feat(bot): add horizon commands

This commit is contained in:
dasemu committed 2026-03-13 08:40:55 +01:00
1 parent 00efa356c3
commit 2a34054399
4 files changed
+566 -45

No files matched your search

+275 -15
View File
@@ -1,12 +1,13 @@
"""
Telegram bot for the ski predictor system.
Serves next-day predictions for three ski stations in northern Spain:
- Valgrande-Pajares (/pajares)
- San Isidro (/sanisidro)
Serves published predictions for three ski stations in northern Spain:
- Valgrande-Pajares (/pajares)
- San Isidro (/sanisidro)
- Fuentes de Invierno (/fuentes)
The bot reads the latest published prediction run from SQLite.
The bot reads published prediction runs from SQLite and supports both
single-station queries and multi-station horizon commands.
Usage:
Set the TELEGRAM_BOT_TOKEN environment variable and run:
@@ -16,7 +17,18 @@ Usage:
import logging
import os
import sys
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
from zoneinfo import ZoneInfo
# 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
@@ -34,6 +46,10 @@ logging.basicConfig(
)
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 (mirrors config/stations.yaml without adding a runtime
# dependency on pyyaml inside the bot module itself).
@@ -53,19 +69,77 @@ STATIONS = {
"max_km": 8.6,
},
}
STATION_ORDER = ("pajares", "sanisidro", "fuentes")
DISPLAY_TIMEZONE = ZoneInfo("Europe/Madrid")
SAME_DAY_PREDICTION_CUTOFF_HOUR = 10
# ---------------------------------------------------------------------------
# Prediction loading
# ---------------------------------------------------------------------------
def load_predictions() -> dict | None:
"""Load the latest published predictions from SQLite.
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 load_predictions(
*,
now: datetime | None = None,
store: SQLiteStore | None = None,
) -> dict | None:
"""Load the published predictions most relevant for the current hour.
Returns the parsed dictionary on success, or None if no published
prediction run exists yet.
"""
store = SQLiteStore()
store = store or SQLiteStore()
for prediction_date in _preferred_prediction_dates(now):
data = store.load_predictions_for_date(
prediction_date=prediction_date,
run_kind=PUBLISHED_RUN_KIND,
)
if data is not None:
logger.info(
"Predicciones cargadas desde SQLite (%s) para %s",
store.db_path,
prediction_date,
)
return data
data = store.load_latest_predictions(run_kind=PUBLISHED_RUN_KIND)
if data is None:
logger.warning(
@@ -74,7 +148,38 @@ def load_predictions() -> dict | None:
)
return None
logger.info("Predicciones cargadas desde SQLite (%s)", store.db_path)
logger.info(
"Predicciones cargadas desde SQLite (%s) como fallback (%s)",
store.db_path,
data.get("prediction_date"),
)
return data
def load_predictions_for_date(
prediction_date: str,
*,
store: SQLiteStore | None = None,
) -> dict | None:
"""Load the latest published predictions for a specific target date."""
store = store or SQLiteStore()
data = store.load_predictions_for_date(
prediction_date=prediction_date,
run_kind=PUBLISHED_RUN_KIND,
)
if data is None:
logger.info(
"No hay predicción publicada en SQLite (%s) para %s",
store.db_path,
prediction_date,
)
return None
logger.info(
"Predicciones cargadas desde SQLite (%s) para %s",
store.db_path,
prediction_date,
)
return data
@@ -115,7 +220,7 @@ 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 para mañana"
return f"{station_name} - Predicción vigente"
def format_station_prediction(
@@ -159,7 +264,9 @@ def format_station_prediction(
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"
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"
@@ -175,6 +282,35 @@ def format_station_prediction(
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 (
@@ -194,6 +330,24 @@ def _unavailable_message() -> str:
)
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
# ---------------------------------------------------------------------------
@@ -203,8 +357,10 @@ 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 las condiciones previstas para el día "
"siguiente en tres estaciones de esquí del norte de España:\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"
@@ -222,7 +378,11 @@ async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"/pajares — Predicción para Valgrande-Pajares\n"
"/sanisidro — Predicción para San Isidro\n"
"/fuentes — Predicción para Fuentes de Invierno\n"
"/all — Predicciones para las tres estaciones\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"
"/help — Mostrar esta ayuda\n"
)
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
@@ -267,6 +427,59 @@ async def _send_station(
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)
@@ -288,8 +501,51 @@ async def cmd_fuentes(update: Update, context: ContextTypes.DEFAULT_TYPE) -> Non
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)
for station_key in ("pajares", "sanisidro", "fuentes"):
await _send_station(update, station_key)
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),
)
# ---------------------------------------------------------------------------
@@ -321,6 +577,10 @@ def main() -> None:
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))
logger.info("Bot listo. Esperando mensajes...")
app.run_polling(allowed_updates=Update.ALL_TYPES)