clawpro 0.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.
clawpro/__init__.py ADDED
@@ -0,0 +1,304 @@
1
+ """Official Python SDK for the ClawPro Instagram outbound API.
2
+
3
+ from clawpro import ClawPro
4
+ clawpro = ClawPro(api_key="sk_live_...")
5
+ for account in clawpro.accounts.list():
6
+ print(account["username"], account["status"])
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import random
11
+ import time
12
+ from typing import Any, Dict, Iterator, List, Optional, TypedDict
13
+
14
+ import httpx
15
+
16
+ __version__ = "0.1.0"
17
+ __all__ = ["ClawPro", "ClawProError"]
18
+
19
+ DEFAULT_BASE_URL = "https://api.tryclawpro.com"
20
+
21
+
22
+ # ─────────────────────────────── Types ───────────────────────────────────────
23
+ class Account(TypedDict, total=False):
24
+ id: str
25
+ username: str
26
+ status: str
27
+ warmupTier: int
28
+ dailyDmCap: int
29
+
30
+
31
+ class Campaign(TypedDict, total=False):
32
+ id: str
33
+ accountId: str
34
+ name: str
35
+ status: str
36
+ targets: List[Dict[str, Any]]
37
+ offer: str
38
+ icpCriteria: str
39
+ dailyDmTarget: int
40
+
41
+
42
+ class Lead(TypedDict, total=False):
43
+ id: str
44
+ igUsername: str
45
+ fullName: Optional[str]
46
+ sourceTargetUsername: str
47
+ engagementType: str
48
+ score: Optional[int]
49
+ scoreReason: Optional[str]
50
+ status: str
51
+ messages: List[Dict[str, Any]]
52
+
53
+
54
+ class Webhook(TypedDict, total=False):
55
+ id: str
56
+ label: str
57
+ url: str
58
+ type: str
59
+ events: List[str]
60
+ active: bool
61
+ lastStatus: Optional[int]
62
+ secret: str
63
+
64
+
65
+ class ApiKey(TypedDict, total=False):
66
+ id: str
67
+ name: str
68
+ environment: str
69
+ access: str
70
+ keyPrefix: str
71
+ createdAt: str
72
+ expiresAt: Optional[str]
73
+ lastUsedAt: Optional[str]
74
+
75
+
76
+ class UsageSummary(TypedDict):
77
+ callsThisMonth: int
78
+ calls24h: int
79
+ errors: int
80
+ avgLatencyMs: int
81
+
82
+
83
+ class RequestLog(TypedDict, total=False):
84
+ id: str
85
+ requestId: str
86
+ method: str
87
+ path: str
88
+ status: int
89
+ latencyMs: int
90
+ error: Optional[str]
91
+ createdAt: str
92
+ keyName: Optional[str]
93
+ keyPrefix: Optional[str]
94
+
95
+
96
+ class ClawProError(Exception):
97
+ """Raised for any non-2xx API response."""
98
+
99
+ def __init__(self, message: str, status: int, code: str = "error", request_id: Optional[str] = None):
100
+ super().__init__(message)
101
+ self.status = status
102
+ self.code = code
103
+ self.request_id = request_id
104
+
105
+
106
+ # ───────────────────────────── Resources ─────────────────────────────────────
107
+ class _Resource:
108
+ def __init__(self, client: "ClawPro") -> None:
109
+ self._c = client
110
+
111
+
112
+ class _Accounts(_Resource):
113
+ def list(self) -> List[Account]:
114
+ return self._c._request("GET", "/accounts")["accounts"]
115
+
116
+ def create(self, username: str, *, country: Optional[str] = None, proxy_type: Optional[str] = None,
117
+ proxy_url: Optional[str] = None, timezone: Optional[str] = None) -> Account:
118
+ body: Dict[str, Any] = {"username": username}
119
+ if country:
120
+ body["country"] = country
121
+ if proxy_type:
122
+ body["proxyType"] = proxy_type
123
+ if proxy_url:
124
+ body["proxyUrl"] = proxy_url
125
+ if timezone:
126
+ body["timezone"] = timezone
127
+ return self._c._request("POST", "/accounts", json=body)["account"]
128
+
129
+ def delete(self, account_id: str) -> None:
130
+ self._c._request("DELETE", f"/accounts/{account_id}")
131
+
132
+
133
+ class _Campaigns(_Resource):
134
+ def list(self) -> List[Campaign]:
135
+ return self._c._request("GET", "/campaigns")["campaigns"]
136
+
137
+ def create(self, *, account_id: str, name: str, targets: List[str], offer: Optional[str] = None,
138
+ icp_criteria: Optional[str] = None, daily_dm_target: Optional[int] = None) -> Campaign:
139
+ body: Dict[str, Any] = {"accountId": account_id, "name": name, "targets": targets}
140
+ if offer is not None:
141
+ body["offer"] = offer
142
+ if icp_criteria is not None:
143
+ body["icpCriteria"] = icp_criteria
144
+ if daily_dm_target is not None:
145
+ body["dailyDmTarget"] = daily_dm_target
146
+ return self._c._request("POST", "/campaigns", json=body)["campaign"]
147
+
148
+ def run(self, campaign_id: str) -> Dict[str, int]:
149
+ return self._c._request("POST", f"/campaigns/{campaign_id}/run")
150
+
151
+ def leads(self, campaign_id: str, *, status: Optional[str] = None) -> List[Lead]:
152
+ params = {"status": status} if status else None
153
+ return self._c._request("GET", f"/campaigns/{campaign_id}/leads", params=params)["leads"]
154
+
155
+ def inbox(self, campaign_id: str) -> List[Lead]:
156
+ return self._c._request("GET", f"/campaigns/{campaign_id}/inbox")["threads"]
157
+
158
+
159
+ class _Leads(_Resource):
160
+ def update(self, lead_id: str, *, status: str) -> Lead:
161
+ """Advance a lead, e.g. status='booked' (fires the lead.booked webhook)."""
162
+ return self._c._request("PATCH", f"/leads/{lead_id}", json={"status": status})["lead"]
163
+
164
+
165
+ class _Webhooks(_Resource):
166
+ def events(self) -> List[str]:
167
+ return self._c._request("GET", "/webhooks/events")["events"]
168
+
169
+ def list(self) -> List[Webhook]:
170
+ return self._c._request("GET", "/webhooks")["webhooks"]
171
+
172
+ def create(self, url: str, *, events: Optional[List[str]] = None, type: str = "generic",
173
+ label: Optional[str] = None) -> Webhook:
174
+ body: Dict[str, Any] = {"url": url, "type": type, "events": events or ["*"]}
175
+ if label:
176
+ body["label"] = label
177
+ return self._c._request("POST", "/webhooks", json=body)["webhook"]
178
+
179
+ def delete(self, webhook_id: str) -> None:
180
+ self._c._request("DELETE", f"/webhooks/{webhook_id}")
181
+
182
+ def test(self, webhook_id: str) -> Any:
183
+ return self._c._request("POST", f"/webhooks/{webhook_id}/test")
184
+
185
+
186
+ class _Keys(_Resource):
187
+ def list(self) -> List[ApiKey]:
188
+ return self._c._request("GET", "/keys")["keys"]
189
+
190
+ def create(self, name: str, *, environment: Optional[str] = None, access: Optional[str] = None,
191
+ expires_at: Optional[str] = None) -> Dict[str, Any]:
192
+ """Returns {"secret": ..., "key": ApiKey}. The secret is shown only here."""
193
+ body: Dict[str, Any] = {"name": name}
194
+ if environment:
195
+ body["environment"] = environment
196
+ if access:
197
+ body["access"] = access
198
+ if expires_at:
199
+ body["expiresAt"] = expires_at
200
+ return self._c._request("POST", "/keys", json=body)
201
+
202
+ def revoke(self, key_id: str) -> None:
203
+ self._c._request("DELETE", f"/keys/{key_id}")
204
+
205
+
206
+ class _Usage(_Resource):
207
+ def summary(self) -> UsageSummary:
208
+ return self._c._request("GET", "/usage")
209
+
210
+ def logs(self, *, key: Optional[str] = None, method: Optional[str] = None, status: Optional[str] = None,
211
+ from_: Optional[str] = None, to: Optional[str] = None, endpoint: Optional[str] = None,
212
+ request_id: Optional[str] = None, search: Optional[str] = None,
213
+ limit: Optional[int] = None, offset: Optional[int] = None) -> List[RequestLog]:
214
+ params = {
215
+ "key": key, "method": method, "status": status, "from": from_, "to": to,
216
+ "endpoint": endpoint, "requestId": request_id, "search": search,
217
+ "limit": limit, "offset": offset,
218
+ }
219
+ params = {k: v for k, v in params.items() if v is not None}
220
+ return self._c._request("GET", "/logs", params=params)["logs"]
221
+
222
+ def iterate_logs(self, *, page_size: int = 100, **filters: Any) -> Iterator[RequestLog]:
223
+ """Auto-paginate every matching log."""
224
+ offset = 0
225
+ while True:
226
+ page = self.logs(limit=page_size, offset=offset, **filters)
227
+ for row in page:
228
+ yield row
229
+ if len(page) < page_size:
230
+ return
231
+ offset += page_size
232
+
233
+
234
+ # ─────────────────────────────── Client ──────────────────────────────────────
235
+ class ClawPro:
236
+ """ClawPro API client.
237
+
238
+ Args:
239
+ api_key: A ``sk_live_…`` / ``sk_test_…`` key (sent as ``X-API-Key``).
240
+ base_url: API origin (override for staging/self-hosted).
241
+ max_retries: Retries for transient failures (network, 429, 5xx). Default 2.
242
+ timeout: Per-request timeout (seconds).
243
+ """
244
+
245
+ def __init__(self, api_key: str, *, base_url: str = DEFAULT_BASE_URL,
246
+ max_retries: int = 2, timeout: float = 30.0) -> None:
247
+ if not api_key:
248
+ raise ValueError("ClawPro: api_key is required")
249
+ self._base = base_url.rstrip("/") + "/api/instagram"
250
+ self._max_retries = max_retries
251
+ self._http = httpx.Client(
252
+ timeout=timeout,
253
+ headers={"X-API-Key": api_key, "Accept": "application/json"},
254
+ )
255
+ self.accounts = _Accounts(self)
256
+ self.campaigns = _Campaigns(self)
257
+ self.leads = _Leads(self)
258
+ self.webhooks = _Webhooks(self)
259
+ self.keys = _Keys(self)
260
+ self.usage = _Usage(self)
261
+
262
+ @staticmethod
263
+ def _backoff(attempt: int) -> float:
264
+ return (0.25 * (2 ** attempt)) * (0.8 + random.random() * 0.4)
265
+
266
+ def _request(self, method: str, path: str, *, params: Optional[Dict[str, Any]] = None,
267
+ json: Optional[Dict[str, Any]] = None) -> Any:
268
+ url = self._base + path
269
+ idempotent = method in ("GET", "DELETE", "PUT")
270
+ attempt = 0
271
+ while True:
272
+ try:
273
+ resp = self._http.request(method, url, params=params, json=json)
274
+ except httpx.TransportError as exc:
275
+ if idempotent and attempt < self._max_retries:
276
+ time.sleep(self._backoff(attempt))
277
+ attempt += 1
278
+ continue
279
+ raise ClawProError(f"Network error: {exc}", 0, "network_error")
280
+
281
+ transient = resp.status_code == 429 or resp.status_code >= 500
282
+ if transient and (resp.status_code == 429 or idempotent) and attempt < self._max_retries:
283
+ retry_after = resp.headers.get("retry-after")
284
+ wait = float(retry_after) if retry_after and retry_after.isdigit() else self._backoff(attempt)
285
+ time.sleep(wait)
286
+ attempt += 1
287
+ continue
288
+
289
+ data = resp.json() if resp.content else None
290
+ if resp.status_code >= 400:
291
+ body = data if isinstance(data, dict) else {}
292
+ message = body.get("message") or body.get("error") or f"HTTP {resp.status_code}"
293
+ raise ClawProError(message, resp.status_code, body.get("error", "error"),
294
+ resp.headers.get("x-request-id"))
295
+ return data
296
+
297
+ def close(self) -> None:
298
+ self._http.close()
299
+
300
+ def __enter__(self) -> "ClawPro":
301
+ return self
302
+
303
+ def __exit__(self, *exc: Any) -> None:
304
+ self.close()
clawpro/py.typed ADDED
File without changes
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: clawpro
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the ClawPro Instagram outbound API.
5
+ Project-URL: Homepage, https://tryclawpro.com
6
+ Project-URL: Repository, https://github.com/Bojale-Labs/clawpro-python
7
+ Author: ClawPro
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: clawpro,dm,instagram,outbound,sdk,tryclawpro
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.8
16
+ Requires-Dist: httpx>=0.24
17
+ Description-Content-Type: text/markdown
18
+
19
+ # clawpro
20
+
21
+ Official Python SDK for the **ClawPro** Instagram outbound API — connect sending accounts, run competitor-audience campaigns, score leads, manage webhooks, and read usage.
22
+
23
+ ```bash
24
+ pip install clawpro
25
+ ```
26
+
27
+ Python 3.8+. Get an API key from the [developer portal](https://tryclawpro.com) → **API & Developers → API Keys**.
28
+
29
+ ## Quick start
30
+
31
+ ```python
32
+ import os
33
+ from clawpro import ClawPro, ClawProError
34
+
35
+ clawpro = ClawPro(api_key=os.environ["CLAWPRO_API_KEY"])
36
+
37
+ account = clawpro.accounts.create(username="burner_account", country="gb")
38
+
39
+ campaign = clawpro.campaigns.create(
40
+ account_id=account["id"],
41
+ name="Founders engaging with X",
42
+ targets=["@influencer1"],
43
+ offer="We help B2B founders book demos via Instagram outbound.",
44
+ daily_dm_target=20,
45
+ )
46
+ clawpro.campaigns.run(campaign["id"])
47
+
48
+ # Warm replies → mark a lead booked (fires the lead.booked webhook)
49
+ inbox = clawpro.campaigns.inbox(campaign["id"])
50
+ if inbox:
51
+ clawpro.leads.update(inbox[0]["id"], status="booked")
52
+
53
+ print(clawpro.usage.summary())
54
+
55
+ # Auto-paginate the request log
56
+ for log in clawpro.usage.iterate_logs(page_size=100):
57
+ ...
58
+ ```
59
+
60
+ ## Resources
61
+
62
+ `accounts`, `campaigns`, `leads`, `webhooks`, `keys`, `usage` — mirroring the REST API. Requests authenticate with `X-API-Key`; transient failures (network, `429` honoring `Retry-After`, `5xx`) are retried with exponential backoff for idempotent calls.
63
+
64
+ ## Errors
65
+
66
+ ```python
67
+ try:
68
+ clawpro.accounts.create(username="taken_handle")
69
+ except ClawProError as err:
70
+ print(err.status, err, err.request_id) # 409 "@taken_handle is already connected"
71
+ ```
72
+
73
+ ## Configuration
74
+
75
+ ```python
76
+ ClawPro(api_key="...", base_url="https://api.tryclawpro.com", max_retries=3, timeout=30.0)
77
+ ```
78
+
79
+ It's also a context manager (`with ClawPro(...) as clawpro: ...`) and exposes `.close()`.
80
+
81
+ ## License
82
+
83
+ MIT
@@ -0,0 +1,6 @@
1
+ clawpro/__init__.py,sha256=FYV1Kr0zwXFFBYxuMxRyQGMGZBCGN0Qf8m7fiYybNKs,10993
2
+ clawpro/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ clawpro-0.1.0.dist-info/METADATA,sha256=oGWiS4CDZLoESjL1li4djnNCv1ZXqttHKkzK80SVdlA,2457
4
+ clawpro-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
5
+ clawpro-0.1.0.dist-info/licenses/LICENSE,sha256=_Zx7znszRomQxl_Nhx2gfeUQ11PtgGZQqWplFJa5IvE,1064
6
+ clawpro-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ClawPro
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.