Spaces:
Runtime error

File size: 8,277 Bytes
ed86a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"""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)