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.")
+40
View File
@@ -430,6 +430,8 @@ async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"/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)
@@ -595,6 +597,42 @@ async def cmd_semana(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None
)
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
# ---------------------------------------------------------------------------
@@ -627,6 +665,8 @@ def create_bot_application(token: str | None = None) -> Application:
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
+94
View File
@@ -595,6 +595,92 @@ class SQLiteStore:
return df
# ------------------------------------------------------------------
# Notification subscribers
# ------------------------------------------------------------------
def subscribe_notifications(self, chat_id: int, username: str | None) -> bool:
"""Subscribe a Telegram chat to daily notifications.
Returns True if newly subscribed, False if already active.
Reactivates a previously unsubscribed chat.
"""
with self.connect() as conn:
row = conn.execute(
"SELECT active FROM notification_subscribers WHERE telegram_chat_id = ?",
(chat_id,),
).fetchone()
if row is not None:
if row["active"]:
return False
conn.execute(
"""
UPDATE notification_subscribers
SET active = 1, telegram_username = ?, subscribed_at = ?
WHERE telegram_chat_id = ?
""",
(username, self._now_iso(), chat_id),
)
return True
conn.execute(
"""
INSERT INTO notification_subscribers
(telegram_chat_id, telegram_username, subscribed_at, active)
VALUES (?, ?, ?, 1)
""",
(chat_id, username, self._now_iso()),
)
return True
def unsubscribe_notifications(self, chat_id: int) -> bool:
"""Unsubscribe a Telegram chat from daily notifications.
Returns True if the chat was actively subscribed, False otherwise.
"""
with self.connect() as conn:
row = conn.execute(
"SELECT active FROM notification_subscribers WHERE telegram_chat_id = ?",
(chat_id,),
).fetchone()
if row is None or not row["active"]:
return False
conn.execute(
"UPDATE notification_subscribers SET active = 0 WHERE telegram_chat_id = ?",
(chat_id,),
)
return True
def is_subscribed(self, chat_id: int) -> bool:
"""Return True when the chat has an active notification subscription."""
with self.connect() as conn:
row = conn.execute(
"SELECT active FROM notification_subscribers WHERE telegram_chat_id = ?",
(chat_id,),
).fetchone()
return row is not None and bool(row["active"])
def get_active_subscribers(self) -> list[dict]:
"""Return all active notification subscribers."""
with self.connect() as conn:
rows = conn.execute(
"""
SELECT telegram_chat_id, telegram_username
FROM notification_subscribers
WHERE active = 1
""",
).fetchall()
return [
{
"telegram_chat_id": row["telegram_chat_id"],
"telegram_username": row["telegram_username"],
}
for row in rows
]
# ------------------------------------------------------------------
# Private helpers
# ------------------------------------------------------------------
@@ -687,6 +773,14 @@ class SQLiteStore:
created_at TEXT NOT NULL,
last_login_at TEXT
);
CREATE TABLE IF NOT EXISTS notification_subscribers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
telegram_chat_id INTEGER NOT NULL UNIQUE,
telegram_username TEXT,
subscribed_at TEXT NOT NULL,
active INTEGER NOT NULL DEFAULT 1
);
"""
)