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.
This commit is contained in:
dasemu committed 2026-03-17 17:46:02 +01:00
1 parent 5e2a22340f
commit 61b4d8334d
3 files changed
+200

No files matched your search

+66
View File
@@ -8,7 +8,9 @@ Three scheduled tasks:
from __future__ import annotations
import asyncio
import logging
import os
from datetime import date, datetime, timezone
from typing import Any
@@ -226,6 +228,9 @@ def run_extended_task() -> None:
# Webcam snapshot + crowd analysis
_collect_daily_crowd_density(store)
# Send daily prediction notification to subscribers
_send_daily_notifications(store)
# ---------------------------------------------------------------------------
# Training task (Sunday 21h)
@@ -273,6 +278,67 @@ def _collect_daily_crowd_density(store: SQLiteStore) -> None:
logger.error("Daily crowd collection failed for %s: %s", station_id, exc)
async def _send_notifications_async(store: SQLiteStore) -> None:
"""Send the next-day prediction to all active notification subscribers."""
from telegram import Bot
from telegram.constants import ParseMode
from bot.telegram_bot import (
format_daily_predictions,
load_predictions_for_date,
prediction_dates_window,
)
token = os.environ.get("TELEGRAM_BOT_TOKEN")
if not token:
logger.warning("No TELEGRAM_BOT_TOKEN set, skipping notifications.")
return
bot = Bot(token=token)
subscribers = store.get_active_subscribers()
if not subscribers:
logger.info("No active subscribers for notifications.")
return
tomorrow_dates = prediction_dates_window(start_offset=1, length=1)
if not tomorrow_dates:
return
predictions = load_predictions_for_date(tomorrow_dates[0], store=store)
if predictions is None:
logger.warning("No predictions available for tomorrow notification.")
return
message = "\U0001f4e2 <b>Predicción diaria</b>\n\n" + format_daily_predictions(
predictions
)
for sub in subscribers:
chat_id = sub["telegram_chat_id"]
try:
await bot.send_message(
chat_id=chat_id, text=message, parse_mode=ParseMode.HTML
)
except Exception as exc:
logger.error("Failed to send notification to %s: %s", chat_id, exc)
if "Forbidden" in str(exc) or "blocked" in str(exc).lower():
store.unsubscribe_notifications(chat_id)
logger.info("Deactivated subscription for blocked user %s", chat_id)
def _send_daily_notifications(store: SQLiteStore) -> None:
"""Send daily prediction notifications to all subscribers."""
logger.info("Sending daily notification to subscribers.")
try:
asyncio.run(_send_notifications_async(store))
except RuntimeError:
# If an event loop is already running (e.g. inside FastAPI/uvicorn),
# schedule the coroutine on the existing loop instead.
loop = asyncio.get_event_loop()
loop.create_task(_send_notifications_async(store))
def _scrape_daily_actuals(store: SQLiteStore, scraper: StationScraper) -> None:
"""Scrape today's actual station data and save to historical_actuals."""
logger.info("Scraping today's actual station data.")