From 3b2221b0d2d31ea69264a3d473d6e96ffc19420d Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Thu, 16 Jul 2026 17:59:07 +0200 Subject: [PATCH] feat(alerts): Telegram admin alerts for purchases + ops issues MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - config: TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID + telegram_configured - alerts: send_telegram(); send_admin_alert now pushes to Telegram + email (so existing proxy-out-of-credits and high-failure alerts hit Telegram too) - billing webhook: alert on new subscription, trial→paid conversion, and top-up - .env.cloud.example documents the Telegram vars Verified end-to-end: alert delivered to the admin group via the same send_admin_alert path the webhook uses. Token stays in gitignored .env. --- .env.cloud.example | 7 +++++++ cloud/alerts.py | 27 +++++++++++++++++++++++++-- cloud/billing.py | 32 ++++++++++++++++++++++++++++++++ cloud/config.py | 13 +++++++++++++ 4 files changed, 77 insertions(+), 2 deletions(-) diff --git a/.env.cloud.example b/.env.cloud.example index e26b537..71fc8f0 100644 --- a/.env.cloud.example +++ b/.env.cloud.example @@ -23,6 +23,13 @@ EMAIL_FROM=OpenShorts # Operational alerts (proxy out of credits / high failure rate) are emailed here. ADMIN_EMAIL=you@example.com +# Telegram admin alerts (optional) — instant pings for purchases, cancellations, +# proxy-out-of-credits and high failure rate. Create a bot with @BotFather to get +# the token, then message your bot and read the chat id from: +# https://api.telegram.org/bot/getUpdates +TELEGRAM_BOT_TOKEN= +TELEGRAM_CHAT_ID= + # Google OAuth (optional; magic link works without it) GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= diff --git a/cloud/alerts.py b/cloud/alerts.py index 7d40cfb..be18a30 100644 --- a/cloud/alerts.py +++ b/cloud/alerts.py @@ -33,11 +33,34 @@ def _cooldown_ok(kind: str) -> bool: return True +async def send_telegram(text: str): + """Push a plain-text message to the admin's Telegram chat. No-op if unset. + + Best-effort: never raises — an alert failing must not break a webhook or job. + """ + if not settings.telegram_configured: + return + try: + import httpx + url = f"https://api.telegram.org/bot{settings.telegram_bot_token}/sendMessage" + payload = {"chat_id": settings.telegram_chat_id, "text": text, + "disable_web_page_preview": True} + async with httpx.AsyncClient(timeout=10) as client: + await client.post(url, json=payload) + except Exception as e: + print(f"⚠️ Telegram alert failed: {e}") + + async def send_admin_alert(subject: str, body: str): + """Notify the admin via every configured channel (email + Telegram).""" + # Telegram first — instant, and configured independently of email. + await send_telegram(f"{subject}\n\n{body}") + to = settings.admin_email if not to or not settings.smtp_configured: - print(f"⚠️ [ADMIN ALERT] {subject}\n{body[:500]}" - + ("" if to else " (set ADMIN_EMAIL + SMTP_* to email these)")) + if not settings.telegram_configured: + print(f"⚠️ [ADMIN ALERT] {subject}\n{body[:500]}" + + ("" if to else " (set ADMIN_EMAIL + SMTP_* or TELEGRAM_* to receive these)")) return html = f"
{body}
" await send_email(to, f"[OpenShorts] {subject}", html) diff --git a/cloud/billing.py b/cloud/billing.py index b80b483..17561a2 100644 --- a/cloud/billing.py +++ b/cloud/billing.py @@ -243,6 +243,7 @@ async def _apply_topup(session_obj: dict): minutes = int((session_obj.get("metadata") or {}).get("minutes") or 0) if minutes <= 0: return + buyer_email = None async with database.session() as s: async with s.begin(): existing = (await s.execute( @@ -259,6 +260,15 @@ async def _apply_topup(session_obj: dict): user_id=user_id, stripe_session_id=session_id, minutes_total=minutes, minutes_consumed=0, )) + buyer_email = (await s.execute( + select(User.email).where(User.id == user_id) + )).scalar_one_or_none() + + from .alerts import send_admin_alert + await send_admin_alert( + "💰 Top-up purchased", + f"{buyer_email or 'A user'} bought +{minutes} minutes.", + ) def _sub_item(sub_obj: dict): @@ -315,6 +325,12 @@ async def _upsert_subscription(sub_obj: dict, event_created: datetime): # Detect the moment the user hits "cancel" (False -> True). was_canceling = bool(row.cancel_at_period_end) if row else False just_canceled = now_canceling and not was_canceling + # Purchase signals: brand-new subscription, and trial -> paid conversion. + is_new_sub = row is None + prev_status = row.status if row else None + buyer_email = (await s.execute( + select(User.email).where(User.id == user_id) + )).scalar_one_or_none() end_dt = _ts(end) values = dict( stripe_subscription_id=sub_obj["id"], @@ -332,6 +348,22 @@ async def _upsert_subscription(sub_obj: dict, event_created: datetime): for k, v in values.items(): setattr(row, k, v) + # Purchase alert: someone just subscribed (trial started or paid outright). + now_status = sub_obj["status"] + if is_new_sub: + from .alerts import send_admin_alert + label = "trial started — card on file" if now_status == "trialing" else now_status + await send_admin_alert( + "🎉 New subscriber", + f"{buyer_email or 'A user'} started the {plan} ({interval}) plan.\nStatus: {label}.", + ) + elif prev_status == "trialing" and now_status == "active": + from .alerts import send_admin_alert + await send_admin_alert( + "💳 Trial converted to paid", + f"{buyer_email or 'A user'} is now a paying {plan} ({interval}) subscriber. 🎉", + ) + # Churn alert to the admin the moment a subscription is set to cancel. if just_canceled: from .alerts import send_admin_alert diff --git a/cloud/config.py b/cloud/config.py index 12645f5..0e727b6 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -138,6 +138,19 @@ class Settings: # Where operational alerts (proxy out of credits, high failure rate) go. return os.environ.get("ADMIN_EMAIL", "") + # Telegram (optional) — real-time admin alerts (purchases, churn, outages) + @property + def telegram_bot_token(self) -> str: + return os.environ.get("TELEGRAM_BOT_TOKEN", "") + + @property + def telegram_chat_id(self) -> str: + return os.environ.get("TELEGRAM_CHAT_ID", "") + + @property + def telegram_configured(self) -> bool: + return bool(self.telegram_bot_token and self.telegram_chat_id) + # Google OAuth @property def google_client_id(self) -> str: