moatlight 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
moatlight/__init__.py ADDED
@@ -0,0 +1,176 @@
1
+ """Moatlight API client. Standard library only.
2
+
3
+ Writes carry an Idempotency-Key that stays the same across retries, and network errors, 429 and 5xx are
4
+ retried (Retry-After honoured), so a retry can never start a second report.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import random
10
+ import time
11
+ import urllib.error
12
+ import urllib.parse
13
+ import urllib.request
14
+ import uuid
15
+ from typing import Any, Dict, Iterator, List, Optional
16
+
17
+ __version__ = "1.1.0"
18
+ DEFAULT_BASE_URL = "https://www.moatlight.com"
19
+ __all__ = ["Moatlight", "MoatlightError", "DEFAULT_BASE_URL", "__version__"]
20
+
21
+
22
+ class MoatlightError(Exception):
23
+ """An API error: HTTP status plus the code, message and hint from the JSON error body."""
24
+
25
+ def __init__(self, status: int, code: str, message: str, hint: Optional[str] = None,
26
+ retry_after: Optional[int] = None, body: Any = None) -> None:
27
+ super().__init__(f"{code}: {message}")
28
+ self.status, self.code, self.message, self.hint = status, code, message, hint
29
+ self.retry_after, self.body = retry_after, body
30
+
31
+
32
+ class Moatlight:
33
+ def __init__(self, token: Optional[str] = None, base_url: str = DEFAULT_BASE_URL,
34
+ max_retries: int = 3, timeout: float = 60.0) -> None:
35
+ self.token = token
36
+ self.base_url = base_url.rstrip("/")
37
+ self.max_retries = max_retries
38
+ self.timeout = timeout
39
+ #: RateLimit headers of the last answer: {"limit", "remaining", "reset_seconds"}
40
+ self.last_rate_limit: Dict[str, Optional[int]] = {}
41
+
42
+ # ---- transport ----
43
+ def request(self, path: str, method: str = "GET", query: Optional[Dict[str, Any]] = None,
44
+ body: Any = None, idempotency_key: Optional[str] = None) -> Any:
45
+ url = self.base_url + path
46
+ params = {k: v for k, v in (query or {}).items() if v is not None}
47
+ if params:
48
+ url += "?" + urllib.parse.urlencode(params)
49
+ headers = {"Accept": "application/json", "User-Agent": f"moatlight-python/{__version__}"}
50
+ if self.token:
51
+ headers["Authorization"] = f"Bearer {self.token}"
52
+ data = None
53
+ if body is not None:
54
+ data = json.dumps(body).encode()
55
+ headers["Content-Type"] = "application/json"
56
+ if method == "POST":
57
+ headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
58
+ attempt = 0
59
+ while True:
60
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
61
+ try:
62
+ with urllib.request.urlopen(req, timeout=self.timeout) as res:
63
+ self._rate(res.headers)
64
+ text = res.read().decode()
65
+ return json.loads(text) if text else None
66
+ except urllib.error.HTTPError as e:
67
+ self._rate(e.headers)
68
+ text = e.read().decode()
69
+ try:
70
+ payload = json.loads(text)
71
+ except ValueError:
72
+ payload = None
73
+ retry_after = int(e.headers.get("Retry-After") or 0) or None
74
+ if (e.code == 429 or e.code >= 500) and attempt < self.max_retries:
75
+ time.sleep(min(retry_after, 60) if retry_after else _backoff(attempt))
76
+ attempt += 1
77
+ continue
78
+ err = (payload or {}).get("error", {}) if isinstance(payload, dict) else {}
79
+ raise MoatlightError(e.code, err.get("code", f"http_{e.code}"), err.get("message", e.reason),
80
+ err.get("hint"), retry_after, payload) from None
81
+ except (urllib.error.URLError, TimeoutError, ConnectionError):
82
+ if attempt >= self.max_retries:
83
+ raise
84
+ time.sleep(_backoff(attempt))
85
+ attempt += 1
86
+
87
+ def _rate(self, h: Any) -> None:
88
+ def num(k: str) -> Optional[int]:
89
+ v = h.get(k)
90
+ return int(v) if v is not None and str(v).isdigit() else None
91
+ self.last_rate_limit = {"limit": num("RateLimit-Limit"), "remaining": num("RateLimit-Remaining"),
92
+ "reset_seconds": num("RateLimit-Reset")}
93
+
94
+ # ---- public ----
95
+ def get_product(self, fields: Optional[str] = None) -> Dict[str, Any]:
96
+ return self.request("/api/v1/product", query={"fields": fields})
97
+
98
+ def get_pricing(self, fields: Optional[str] = None) -> Dict[str, Any]:
99
+ return self.request("/api/v1/pricing", query={"fields": fields})
100
+
101
+ def get_sample_report(self) -> Dict[str, Any]:
102
+ return self.request("/api/v1/sample-report")
103
+
104
+ def list_faq(self, limit: Optional[int] = None, cursor: Optional[str] = None) -> Dict[str, Any]:
105
+ return self.request("/api/v1/faq", query={"limit": limit, "cursor": cursor})
106
+
107
+ # ---- account (OAuth token) ----
108
+ def get_account(self, fields: Optional[str] = None) -> Dict[str, Any]:
109
+ return self.request("/api/v1/me", query={"fields": fields})
110
+
111
+ def list_reports(self, limit: Optional[int] = None, cursor: Optional[str] = None) -> Dict[str, Any]:
112
+ return self.request("/api/v1/reports", query={"limit": limit, "cursor": cursor})
113
+
114
+ def all_reports(self, limit: int = 50) -> Iterator[Dict[str, Any]]:
115
+ """Every report, newest first, following next_cursor for you."""
116
+ cursor = None
117
+ while True:
118
+ page = self.list_reports(limit=limit, cursor=cursor)
119
+ yield from page["reports"]
120
+ cursor = page.get("next_cursor")
121
+ if not cursor:
122
+ return
123
+
124
+ def create_report(self, website: str, country: Optional[str] = None, language: Optional[str] = None,
125
+ idempotency_key: Optional[str] = None) -> Dict[str, Any]:
126
+ body = {"website": website, **({"country": country} if country else {}), **({"language": language} if language else {})}
127
+ return self.request("/api/v1/reports", "POST", body=body, idempotency_key=idempotency_key)
128
+
129
+ def get_report(self, report_id: str, fields: Optional[str] = None) -> Dict[str, Any]:
130
+ return self.request(f"/api/v1/reports/{urllib.parse.quote(report_id, safe='')}", query={"fields": fields})
131
+
132
+ def batch_get_reports(self, report_ids: List[str]) -> Dict[str, Any]:
133
+ return self.request("/api/v1/reports/batch", "POST", body={"report_ids": report_ids})
134
+
135
+ def start_report(self, report_id: str, question_ids: Optional[List[str]] = None,
136
+ idempotency_key: Optional[str] = None) -> Dict[str, Any]:
137
+ body = {"question_ids": question_ids} if question_ids else {}
138
+ return self.request(f"/api/v1/reports/{urllib.parse.quote(report_id, safe='')}/start", "POST", body=body,
139
+ idempotency_key=idempotency_key)
140
+
141
+ def get_report_actions(self, report_id: str) -> Dict[str, Any]:
142
+ return self.request(f"/api/v1/reports/{urllib.parse.quote(report_id, safe='')}/actions")
143
+
144
+ def get_agent_readiness(self, report_id: str) -> Dict[str, Any]:
145
+ return self.request(f"/api/v1/reports/{urllib.parse.quote(report_id, safe='')}/agent-readiness")
146
+
147
+ def scan_agent_readiness(self, report_id: str, force: bool = False,
148
+ idempotency_key: Optional[str] = None) -> Dict[str, Any]:
149
+ return self.request(f"/api/v1/reports/{urllib.parse.quote(report_id, safe='')}/agent-readiness/scan", "POST",
150
+ body={"force": force}, idempotency_key=idempotency_key)
151
+
152
+ def wait_for_report(self, report_id: str, until: Optional[List[str]] = None, timeout: float = 300.0) -> Dict[str, Any]:
153
+ """Poll until the report reaches one of the stages in `until` (default: needs_confirmation, finished, failed)."""
154
+ until = until or ["needs_confirmation", "finished", "analysis_failed", "failed"]
155
+ deadline = time.time() + timeout
156
+ while True:
157
+ r = self.get_report(report_id)
158
+ if r.get("stage") in until:
159
+ return r
160
+ if time.time() > deadline:
161
+ raise TimeoutError(f"Timed out waiting for report {report_id} (stage {r.get('stage')}).")
162
+ time.sleep(r.get("poll_after_seconds") or 5)
163
+
164
+ # ---- sandbox: made-up data, no login ----
165
+ def sandbox_create_report(self, website: str) -> Dict[str, Any]:
166
+ return self.request("/api/v1/sandbox/reports", "POST", body={"website": website})
167
+
168
+ def sandbox_get_report(self, report_id: str = "sandbox-report") -> Dict[str, Any]:
169
+ return self.request(f"/api/v1/sandbox/reports/{urllib.parse.quote(report_id, safe='')}")
170
+
171
+ def sandbox_get_account(self) -> Dict[str, Any]:
172
+ return self.request("/api/v1/sandbox/me")
173
+
174
+
175
+ def _backoff(attempt: int) -> float:
176
+ return min(8.0, 0.5 * 2 ** attempt) + random.random() * 0.25
moatlight/py.typed ADDED
File without changes
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: moatlight
3
+ Version: 1.1.0
4
+ Summary: Official Python client for the Moatlight API: measure whether ChatGPT and Google AI Overview name a business.
5
+ Author-email: Moatlight <ceo@moatlight.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://www.moatlight.com
8
+ Project-URL: Documentation, https://www.moatlight.com/docs
9
+ Project-URL: Repository, https://github.com/Moatlight/moatlight-agent-kit
10
+ Project-URL: OpenAPI, https://www.moatlight.com/openapi.json
11
+ Keywords: moatlight,geo,aeo,ai-search,ai-visibility,mcp,sdk
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # moatlight (Python)
21
+
22
+ Official Python client for the [Moatlight API](https://www.moatlight.com/docs): measure whether ChatGPT and Google AI Overview name a business. Standard library only; Python 3.9+.
23
+
24
+ ```bash
25
+ pip install moatlight
26
+ ```
27
+
28
+ ```python
29
+ from moatlight import Moatlight
30
+
31
+ api = Moatlight() # no login: public endpoints and the sandbox
32
+ print(api.sandbox_get_report()["stage"]) # "finished" (made-up data)
33
+
34
+ api = Moatlight(token="...") # OAuth access token, see https://www.moatlight.com/auth.md
35
+ report = api.create_report("yourcompany.com") # 202 Accepted, safe to retry (Idempotency-Key)
36
+ report = api.wait_for_report(report["id"])
37
+ for r in api.all_reports(): # follows next_cursor
38
+ print(r["id"], r["stage"])
39
+ ```
40
+
41
+ Network errors, 429 and 5xx are retried (`Retry-After` honoured); errors raise `MoatlightError` with `status`, `code`, `message`, `hint`. Docs: https://www.moatlight.com/docs · Source: https://github.com/Moatlight/moatlight-agent-kit · MIT
@@ -0,0 +1,7 @@
1
+ moatlight/__init__.py,sha256=e56bvOeb3PL3dIT-JPBY_zwRy08vxY8biUDPipPHKvY,8779
2
+ moatlight/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ moatlight-1.1.0.dist-info/licenses/LICENSE,sha256=DLj9q3OR_rljO_XZ5748oUd45kdvQVF8MgOEyosPFFY,1066
4
+ moatlight-1.1.0.dist-info/METADATA,sha256=KJwbkO4G_uaH6IV2TQiF8XoJCEKfuAlGjdOkLGuidlY,1808
5
+ moatlight-1.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ moatlight-1.1.0.dist-info/top_level.txt,sha256=IGDhBdl-Kj2FlqFJjwkFEeC-OkDfSISNqNCODfwOTMg,10
7
+ moatlight-1.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Moatlight
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1 @@
1
+ moatlight