feat(alerts): Telegram admin alerts for purchases + ops issues

- 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.
This commit is contained in:
juancarlos.cavero 2026-07-16 17:59:07 +02:00
parent 0f8e19f119
commit 3b2221b0d2
4 changed files with 77 additions and 2 deletions

View file

@ -23,6 +23,13 @@ EMAIL_FROM=OpenShorts <info@yourdomain.com>
# 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<TOKEN>/getUpdates
TELEGRAM_BOT_TOKEN=
TELEGRAM_CHAT_ID=
# Google OAuth (optional; magic link works without it)
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=

View file

@ -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:
if not settings.telegram_configured:
print(f"⚠️ [ADMIN ALERT] {subject}\n{body[:500]}"
+ ("" if to else " (set ADMIN_EMAIL + SMTP_* to email these)"))
+ ("" if to else " (set ADMIN_EMAIL + SMTP_* or TELEGRAM_* to receive these)"))
return
html = f"<pre style='font:13px/1.5 monospace;white-space:pre-wrap'>{body}</pre>"
await send_email(to, f"[OpenShorts] {subject}", html)

View file

@ -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

View file

@ -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: