Spaces:
Runtime error

ai-tester-platform / scripts /setup_uptime_robot.py
BattleFiven's picture
deploy: round 6 save_intermediate light (sha 05316bb)
ed86a97
Raw History Blame Contribute Delete
8.28 kB
"""Setup UptimeRobot monitor + email alert for the production /health.
Idempotent: re-runs are safe — existing monitor / contact with the same
name are reused, not duplicated.
Usage::
UPTIMEROBOT_API_KEY=u123456-... \
UPTIMEROBOT_ALERT_EMAIL=you@example.com \
python scripts/setup_uptime_robot.py
# Override the target URL or interval:
python scripts/setup_uptime_robot.py \
--url https://your-app.onrender.com/health \
--interval 300 \
--name "AI Tester Health"
UptimeRobot API docs: https://uptimerobot.com/api/
Free tier limits (as of writing):
- 50 HTTP(s) monitors
- 5-minute minimum interval (300 s)
- 1 free email alert contact (additional cost extra)
Why this script exists: UptimeRobot account creation requires email
verification (cannot be automated by an agent), but everything after
sign-in is API-driven. This script handles the post-signup wiring.
"""
from __future__ import annotations
import argparse
import os
import sys
import urllib.parse
from typing import Any, Dict, Optional
from urllib.error import HTTPError
from urllib.request import Request, urlopen
API_BASE = "https://api.uptimerobot.com/v2"
# Monitor types per UptimeRobot API.
TYPE_HTTP = 1
# Alert contact types.
CONTACT_TYPE_EMAIL = 2
def _post(api_key: str, path: str, params: Dict[str, str]) -> Dict[str, Any]:
"""POST form-urlencoded body, return parsed JSON."""
body = urllib.parse.urlencode(
{"api_key": api_key, "format": "json", **params}
).encode("utf-8")
req = Request(
f"{API_BASE}/{path.lstrip('/')}",
method="POST",
data=body,
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
"Cache-Control": "no-cache",
},
)
with urlopen(req, timeout=20) as response:
import json
return json.loads(response.read().decode("utf-8"))
def find_alert_contact(api_key: str, email: str) -> Optional[int]:
res = _post(api_key, "getAlertContacts", {})
if res.get("stat") != "ok":
return None
for contact in res.get("alert_contacts", []) or []:
if (
int(contact.get("type", 0)) == CONTACT_TYPE_EMAIL
and (contact.get("value") or "").strip().lower() == email.strip().lower()
):
return int(contact.get("id"))
return None
def create_alert_contact(api_key: str, email: str, friendly_name: str) -> Optional[int]:
res = _post(
api_key,
"newAlertContact",
{
"type": str(CONTACT_TYPE_EMAIL),
"value": email,
"friendly_name": friendly_name,
},
)
if res.get("stat") != "ok":
# UptimeRobot returns stat=fail with an "error" object containing
# type/message; surface it.
err = res.get("error") or {}
msg = err.get("message") or err.get("type") or "unknown error"
# Common case: contact already exists or pending verification.
if "already exists" in msg.lower() or "duplicate" in msg.lower():
return find_alert_contact(api_key, email)
print(f" ! create alert contact failed: {msg}")
return None
return int((res.get("alertcontact") or {}).get("id") or 0) or None
def find_monitor(api_key: str, friendly_name: str) -> Optional[int]:
res = _post(api_key, "getMonitors", {"search": friendly_name})
if res.get("stat") != "ok":
return None
for monitor in res.get("monitors", []) or []:
if (monitor.get("friendly_name") or "").strip() == friendly_name.strip():
return int(monitor.get("id"))
return None
def create_or_update_monitor(
api_key: str,
friendly_name: str,
url: str,
interval_seconds: int,
alert_contact_id: Optional[int],
) -> Optional[int]:
# Format alert_contacts as "{id}_0_0" per UptimeRobot docs (threshold/recurrence
# both 0 = use account defaults).
alert_contacts_param = f"{alert_contact_id}_0_0" if alert_contact_id else ""
existing = find_monitor(api_key, friendly_name)
if existing:
params = {
"id": str(existing),
"interval": str(interval_seconds),
"url": url,
"alert_contacts": alert_contacts_param,
}
res = _post(api_key, "editMonitor", params)
else:
params = {
"friendly_name": friendly_name,
"url": url,
"type": str(TYPE_HTTP),
"interval": str(interval_seconds),
"alert_contacts": alert_contacts_param,
}
res = _post(api_key, "newMonitor", params)
if res.get("stat") != "ok":
err = res.get("error") or {}
print(f" ! monitor save failed: {err.get('message') or err}")
return None
return int((res.get("monitor") or {}).get("id") or existing or 0) or None
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"--api-key",
default=os.getenv("UPTIMEROBOT_API_KEY", ""),
help="UptimeRobot Main API Key (or env UPTIMEROBOT_API_KEY).",
)
parser.add_argument(
"--alert-email",
default=os.getenv("UPTIMEROBOT_ALERT_EMAIL", ""),
help="Email for down/up alerts (or env UPTIMEROBOT_ALERT_EMAIL).",
)
parser.add_argument(
"--url",
default="https://ai-tester-platform.onrender.com/health",
help="URL to monitor.",
)
parser.add_argument(
"--name",
default="AI Tester Platform Health",
help="Friendly name for the monitor.",
)
parser.add_argument(
"--interval",
type=int,
default=300,
help="Polling interval in seconds (free tier minimum is 300).",
)
parser.add_argument(
"--skip-alert",
action="store_true",
help="Don't create / wire up an email alert contact.",
)
args = parser.parse_args()
if not args.api_key:
print("ERROR: provide --api-key or set UPTIMEROBOT_API_KEY", file=sys.stderr)
return 2
contact_id: Optional[int] = None
if not args.skip_alert:
if not args.alert_email:
print(
"WARN: no alert email — pass --alert-email or "
"set UPTIMEROBOT_ALERT_EMAIL to receive notifications. "
"Continuing without alerts.",
file=sys.stderr,
)
else:
contact_id = find_alert_contact(args.api_key, args.alert_email)
if contact_id:
print(f" ✓ reusing alert contact id={contact_id} ({args.alert_email})")
else:
contact_id = create_alert_contact(
args.api_key,
args.alert_email,
friendly_name=f"AI Tester alerts ({args.alert_email})",
)
if contact_id:
print(
f" ✓ created alert contact id={contact_id} "
f"({args.alert_email}). Check inbox to confirm — "
"UptimeRobot requires verification before sending alerts."
)
monitor_id = create_or_update_monitor(
api_key=args.api_key,
friendly_name=args.name,
url=args.url,
interval_seconds=max(args.interval, 300),
alert_contact_id=contact_id,
)
if not monitor_id:
print("ERROR: monitor save failed (see messages above).", file=sys.stderr)
return 1
print()
print("=" * 60)
print("UptimeRobot setup complete ✓")
print("=" * 60)
print(f" monitor id: {monitor_id}")
print(f" url: {args.url}")
print(f" interval: {args.interval} seconds")
print(f" alert email: {args.alert_email or '(none)'}")
print()
print("Dashboard: https://uptimerobot.com/dashboard")
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except HTTPError as exc:
body = ""
try:
body = exc.read().decode("utf-8", errors="ignore")[:300]
except Exception:
body = str(exc)
print(f"HTTP {exc.code}: {body}", file=sys.stderr)
sys.exit(1)