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)
+62 -30
View File
@@ -248,7 +248,8 @@ class SQLiteStore:
) -> dict[str, Any] | None:
"""Return the latest stored prediction payload for *run_kind*."""
with self.connect() as conn:
run = conn.execute(
return self._load_prediction_payload(
conn,
"""
SELECT id, generated_at, prediction_date, run_kind
FROM prediction_runs
@@ -257,39 +258,30 @@ class SQLiteStore:
LIMIT 1
""",
(run_kind,),
).fetchone()
)
if run is None:
return None
def load_predictions_for_date(
self,
*,
prediction_date: date | str,
run_kind: str = PUBLISHED_RUN_KIND,
) -> dict[str, Any] | None:
"""Return the latest stored prediction payload for a specific date."""
if isinstance(prediction_date, date):
prediction_date = prediction_date.isoformat()
station_rows = conn.execute(
with self.connect() as conn:
return self._load_prediction_payload(
conn,
"""
SELECT station_id, station_name, open_probability, km_open,
crowd_level, weather_summary, rule_overrides_json,
prediction_source
FROM prediction_stations
WHERE run_id = ?
ORDER BY station_id
SELECT id, generated_at, prediction_date, run_kind
FROM prediction_runs
WHERE run_kind = ? AND prediction_date = ?
ORDER BY generated_at DESC, id DESC
LIMIT 1
""",
(run["id"],),
).fetchall()
payload = {
"generated_at": run["generated_at"],
"prediction_date": run["prediction_date"],
"stations": {},
}
for row in station_rows:
payload["stations"][row["station_id"]] = {
"station_name": row["station_name"],
"open_probability": row["open_probability"],
"km_open": row["km_open"],
"crowd_level": row["crowd_level"],
"weather_summary": row["weather_summary"],
"rule_overrides": json.loads(row["rule_overrides_json"] or "[]"),
"prediction_source": row["prediction_source"],
}
return payload
(run_kind, str(prediction_date)),
)
def save_training_run(
self,
@@ -615,6 +607,46 @@ class SQLiteStore:
"""
)
def _load_prediction_payload(
self,
conn: sqlite3.Connection,
run_query: str,
params: Sequence[Any],
) -> dict[str, Any] | None:
"""Load a prediction payload from a prediction-runs query."""
run = conn.execute(run_query, tuple(params)).fetchone()
if run is None:
return None
station_rows = conn.execute(
"""
SELECT station_id, station_name, open_probability, km_open,
crowd_level, weather_summary, rule_overrides_json,
prediction_source
FROM prediction_stations
WHERE run_id = ?
ORDER BY station_id
""",
(run["id"],),
).fetchall()
payload = {
"generated_at": run["generated_at"],
"prediction_date": run["prediction_date"],
"stations": {},
}
for row in station_rows:
payload["stations"][row["station_id"]] = {
"station_name": row["station_name"],
"open_probability": row["open_probability"],
"km_open": row["km_open"],
"crowd_level": row["crowd_level"],
"weather_summary": row["weather_summary"],
"rule_overrides": json.loads(row["rule_overrides_json"] or "[]"),
"prediction_source": row["prediction_source"],
}
return payload
@staticmethod
def _normalise_dataframe(df: pd.DataFrame) -> pd.DataFrame:
"""Convert unsupported pandas cell types to SQLite-safe values."""
+41
View File
@@ -30,6 +30,47 @@ def test_prediction_run_roundtrip(tmp_path):
assert loaded == payload
def test_load_predictions_for_date_ignores_newer_other_dates(tmp_path):
"""Date-specific loads must not be displaced by a newer run for tomorrow."""
store = SQLiteStore(tmp_path / "skipredictor.db")
today_payload = {
"generated_at": "2026-03-13T06:00:00+00:00",
"prediction_date": "2026-03-13",
"stations": {
"pajares": {
"station_name": "Valgrande-Pajares",
"open_probability": 0.79,
"km_open": 10.1,
"crowd_level": "low",
"weather_summary": "Temp 0-5 C",
"rule_overrides": [],
"prediction_source": "ml",
}
},
}
tomorrow_payload = {
"generated_at": "2026-03-13T07:00:00+00:00",
"prediction_date": "2026-03-14",
"stations": {
"pajares": {
"station_name": "Valgrande-Pajares",
"open_probability": 0.88,
"km_open": 7.4,
"crowd_level": "medium",
"weather_summary": "Temp 2-7 C",
"rule_overrides": ["Warm rain expected."],
"prediction_source": "hybrid",
}
},
}
store.save_prediction_run(today_payload)
store.save_prediction_run(tomorrow_payload)
loaded = store.load_predictions_for_date(prediction_date="2026-03-13")
assert loaded == today_payload
def test_feature_importances_replace_latest_values(tmp_path):
"""Saving importances twice for the same target must replace older rows."""
store = SQLiteStore(tmp_path / "skipredictor.db")
+188
View File
@@ -0,0 +1,188 @@
"""Unit tests for bot-side prediction selection rules."""
from __future__ import annotations
import sys
import types
from datetime import datetime
from zoneinfo import ZoneInfo
telegram_module = types.ModuleType("telegram")
class _Update:
ALL_TYPES = object()
telegram_module.Update = _Update
constants_module = types.ModuleType("telegram.constants")
class _ParseMode:
HTML = "HTML"
constants_module.ParseMode = _ParseMode
ext_module = types.ModuleType("telegram.ext")
class _ApplicationBuilder:
def token(self, token: str):
return self
def build(self):
return types.SimpleNamespace(
add_handler=lambda *args, **kwargs: None,
run_polling=lambda *args, **kwargs: None,
)
class _Application:
@staticmethod
def builder():
return _ApplicationBuilder()
class _CommandHandler:
def __init__(self, *args, **kwargs) -> None:
self.args = args
self.kwargs = kwargs
class _ContextTypes:
DEFAULT_TYPE = object
ext_module.Application = _Application
ext_module.CommandHandler = _CommandHandler
ext_module.ContextTypes = _ContextTypes
sys.modules.setdefault("telegram", telegram_module)
sys.modules.setdefault("telegram.constants", constants_module)
sys.modules.setdefault("telegram.ext", ext_module)
from bot import telegram_bot
class FakeStore:
"""In-memory stand-in for SQLiteStore used in selection tests."""
def __init__(self, by_date: dict[str, dict], latest: dict | None = None) -> None:
self.by_date = by_date
self.latest = latest
self.db_path = "/tmp/fake.db"
self.requested_dates: list[str] = []
def load_predictions_for_date(self, *, prediction_date: str, run_kind: str):
self.requested_dates.append(prediction_date)
return self.by_date.get(prediction_date)
def load_latest_predictions(self, *, run_kind: str):
return self.latest
def test_load_predictions_prefers_today_before_ten():
"""Before 10:00 local time the bot should prefer today's run."""
today_payload = {"prediction_date": "2026-03-13", "stations": {}}
tomorrow_payload = {"prediction_date": "2026-03-14", "stations": {}}
store = FakeStore(
{
"2026-03-13": today_payload,
"2026-03-14": tomorrow_payload,
}
)
loaded = telegram_bot.load_predictions(
now=datetime(2026, 3, 13, 9, 30, tzinfo=ZoneInfo("Europe/Madrid")),
store=store,
)
assert loaded == today_payload
assert store.requested_dates == ["2026-03-13"]
def test_load_predictions_prefers_tomorrow_after_ten():
"""From 10:00 onwards the bot should prefer tomorrow's run."""
today_payload = {"prediction_date": "2026-03-13", "stations": {}}
tomorrow_payload = {"prediction_date": "2026-03-14", "stations": {}}
store = FakeStore(
{
"2026-03-13": today_payload,
"2026-03-14": tomorrow_payload,
}
)
loaded = telegram_bot.load_predictions(
now=datetime(2026, 3, 13, 10, 0, tzinfo=ZoneInfo("Europe/Madrid")),
store=store,
)
assert loaded == tomorrow_payload
assert store.requested_dates == ["2026-03-14"]
def test_load_predictions_falls_back_when_preferred_dates_are_missing():
"""If the preferred dates are absent, fall back to the latest published run."""
fallback_payload = {"prediction_date": "2026-03-16", "stations": {}}
store = FakeStore({}, latest=fallback_payload)
loaded = telegram_bot.load_predictions(
now=datetime(2026, 3, 13, 8, 0, tzinfo=ZoneInfo("Europe/Madrid")),
store=store,
)
assert loaded == fallback_payload
assert store.requested_dates == ["2026-03-13", "2026-03-14"]
def test_prediction_dates_window_returns_consecutive_dates():
"""Window helpers must return consecutive dates from the requested offset."""
dates = telegram_bot.prediction_dates_window(
start_offset=1,
length=3,
now=datetime(2026, 3, 13, 8, 0, tzinfo=ZoneInfo("Europe/Madrid")),
)
assert dates == ["2026-03-14", "2026-03-15", "2026-03-16"]
def test_format_daily_predictions_includes_all_three_stations():
"""Daily overview messages must include the three configured stations."""
payload = {
"prediction_date": "2026-03-14",
"stations": {
"pajares": {
"open_probability": 0.85,
"km_open": 15.2,
"crowd_level": "medium",
"weather_summary": "Nevadas débiles",
"rule_overrides": [],
"prediction_source": "hybrid",
},
"sanisidro": {
"open_probability": 0.55,
"km_open": 12.8,
"crowd_level": "high",
"weather_summary": "Viento moderado",
"rule_overrides": [],
"prediction_source": "ml",
},
"fuentes": {
"open_probability": 0.35,
"km_open": 2.0,
"crowd_level": "low",
"weather_summary": "Lluvia a media mañana",
"rule_overrides": ["Cota de nieve alta."],
"prediction_source": "rules",
},
},
}
text = telegram_bot.format_daily_predictions(payload)
assert "Valgrande-Pajares" in text
assert "San Isidro" in text
assert "Fuentes de Invierno" in text
assert "2026-03-14" in text