zapz 0.1.0__tar.gz

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.
zapz-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: zapz
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the ZapZ WhatsApp API
5
+ License: MIT
6
+ Project-URL: Homepage, https://zapz.dev
7
+ Project-URL: Source, https://github.com/zapz-api/zapz-sdk
8
+ Project-URL: Issues, https://github.com/zapz-api/zapz-sdk/issues
9
+ Keywords: whatsapp,api,zapz,sdk
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.8
14
+ Description-Content-Type: text/markdown
15
+
16
+ # zapz
17
+
18
+ SDK oficial da API de WhatsApp da ZapZ para Python 3.8+. Sem dependências.
19
+
20
+ ```bash
21
+ pip install zapz
22
+ ```
23
+
24
+ ```python
25
+ from zapz import ZapZ
26
+
27
+ zapz = ZapZ() # lê ZAPZ_API_KEY
28
+ msg = zapz.messages.send_text("INSTANCE_ID", {"to": "5511999999999", "text": "Olá!"})
29
+ print(msg["id"], msg["status"])
30
+ ```
31
+
32
+ Recursos: `instances`, `messages`, `contacts`, `groups`, `webhooks`, `sandbox`. Métodos em snake_case (`send_text`, `update_participants`…); os parâmetros de cada envio são `TypedDict`.
33
+
34
+ Opções do cliente: `api_key`, `base_url` (ou `ZAPZ_BASE_URL`), `timeout` (s, padrão 30), `max_retries` (padrão 2).
35
+
36
+ Erros herdam de `ZapZError` (`status`, `code`, `retry_after`, `body`): `ValidationError`, `AuthenticationError`, `PermissionDeniedError`, `NotFoundError`, `ConflictError`, `RateLimitError`, `InternalServerError`, `APIConnectionError`.
37
+
38
+ ## Webhooks
39
+
40
+ ```python
41
+ from zapz import verify_webhook
42
+
43
+ event = verify_webhook(request.get_data(), request.headers, os.environ["ZAPZ_WEBHOOK_SECRET"])
44
+ ```
zapz-0.1.0/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # zapz
2
+
3
+ SDK oficial da API de WhatsApp da ZapZ para Python 3.8+. Sem dependências.
4
+
5
+ ```bash
6
+ pip install zapz
7
+ ```
8
+
9
+ ```python
10
+ from zapz import ZapZ
11
+
12
+ zapz = ZapZ() # lê ZAPZ_API_KEY
13
+ msg = zapz.messages.send_text("INSTANCE_ID", {"to": "5511999999999", "text": "Olá!"})
14
+ print(msg["id"], msg["status"])
15
+ ```
16
+
17
+ Recursos: `instances`, `messages`, `contacts`, `groups`, `webhooks`, `sandbox`. Métodos em snake_case (`send_text`, `update_participants`…); os parâmetros de cada envio são `TypedDict`.
18
+
19
+ Opções do cliente: `api_key`, `base_url` (ou `ZAPZ_BASE_URL`), `timeout` (s, padrão 30), `max_retries` (padrão 2).
20
+
21
+ Erros herdam de `ZapZError` (`status`, `code`, `retry_after`, `body`): `ValidationError`, `AuthenticationError`, `PermissionDeniedError`, `NotFoundError`, `ConflictError`, `RateLimitError`, `InternalServerError`, `APIConnectionError`.
22
+
23
+ ## Webhooks
24
+
25
+ ```python
26
+ from zapz import verify_webhook
27
+
28
+ event = verify_webhook(request.get_data(), request.headers, os.environ["ZAPZ_WEBHOOK_SECRET"])
29
+ ```
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "zapz"
7
+ version = "0.1.0"
8
+ description = "Official Python SDK for the ZapZ WhatsApp API"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.8"
12
+ dependencies = []
13
+ keywords = ["whatsapp", "api", "zapz", "sdk"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Typing :: Typed",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://zapz.dev"
22
+ Source = "https://github.com/zapz-api/zapz-sdk"
23
+ Issues = "https://github.com/zapz-api/zapz-sdk/issues"
24
+
25
+ [tool.setuptools.packages.find]
26
+ include = ["zapz*"]
27
+
28
+ [tool.setuptools.package-data]
29
+ zapz = ["py.typed"]
zapz-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,52 @@
1
+ """Integration smoke test against a running API with a sk_test_ key:
2
+
3
+ ZAPZ_API_KEY=sk_test_... ZAPZ_BASE_URL=http://localhost:3056 python -m unittest discover -s tests
4
+ """
5
+ import hashlib
6
+ import hmac
7
+ import json
8
+ import os
9
+ import time
10
+ import unittest
11
+
12
+ from zapz import NotFoundError, WebhookVerificationError, ZapZ, verify_webhook
13
+
14
+
15
+ class WebhookTest(unittest.TestCase):
16
+ def test_round_trip(self):
17
+ secret = "whsec_test"
18
+ body = json.dumps({"event": "message_status", "data": {"status": "read"}})
19
+ ts = str(int(time.time()))
20
+ sig = "sha256=" + hmac.new(secret.encode(), f"{ts}.{body}".encode(), hashlib.sha256).hexdigest()
21
+ ev = verify_webhook(body, {"X-Webhook-Timestamp": ts, "X-Webhook-Signature-V2": sig}, secret)
22
+ self.assertEqual(ev["event"], "message_status")
23
+ with self.assertRaises(WebhookVerificationError):
24
+ verify_webhook(body + " ", {"x-webhook-timestamp": ts, "x-webhook-signature-v2": sig}, secret)
25
+ with self.assertRaises(WebhookVerificationError):
26
+ verify_webhook(body, {"x-webhook-timestamp": "1", "x-webhook-signature-v2": sig}, secret)
27
+
28
+
29
+ @unittest.skipUnless(os.environ.get("ZAPZ_API_KEY"), "set ZAPZ_API_KEY (sk_test_) to run")
30
+ class SandboxFlowTest(unittest.TestCase):
31
+ def test_flow(self):
32
+ zapz = ZapZ()
33
+ self.assertTrue(zapz.is_sandbox)
34
+ instances = zapz.instances.list()
35
+ inst = next((i for i in instances if i.get("sandbox")), instances[0])
36
+
37
+ msg = zapz.messages.send_text(inst["id"], {"to": "5511999990001", "text": "Olá do SDK Python"})
38
+ self.assertTrue(msg["id"])
39
+ again = zapz.messages.send_text(inst["id"], {"to": "5511999990001", "text": "Olá do SDK Python", "clientMessageId": msg["id"]})
40
+ self.assertTrue(again.get("duplicate"))
41
+ self.assertEqual(zapz.messages.get(inst["id"], msg["id"])["id"], msg["id"])
42
+
43
+ hook = zapz.webhooks.create({"url": "https://example.com/zapz-sdk-python", "events": ["message_status"], "secret": "whsec_sdk_python_123"})
44
+ self.assertTrue(any(w["id"] == hook["id"] for w in zapz.webhooks.list()))
45
+ zapz.webhooks.delete(hook["id"])
46
+
47
+ with self.assertRaises(NotFoundError):
48
+ zapz.messages.get(inst["id"], "does-not-exist")
49
+
50
+
51
+ if __name__ == "__main__":
52
+ unittest.main()
@@ -0,0 +1,56 @@
1
+ """Official Python SDK for the ZapZ WhatsApp API.
2
+
3
+ from zapz import ZapZ
4
+ zapz = ZapZ(api_key="sk_live_...")
5
+ zapz.messages.send_text("INSTANCE_ID", {"to": "5511999999999", "text": "Olá!"})
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import Optional
10
+
11
+ from ._core import DEFAULT_BASE_URL, ZapZCore
12
+ from ._errors import (
13
+ APIConnectionError,
14
+ AuthenticationError,
15
+ ConflictError,
16
+ InternalServerError,
17
+ NotFoundError,
18
+ PermissionDeniedError,
19
+ RateLimitError,
20
+ ValidationError,
21
+ ZapZError,
22
+ )
23
+ from ._generated import (
24
+ ContactsResource,
25
+ GroupsResource,
26
+ InstancesResource,
27
+ MessagesResource,
28
+ SandboxResource,
29
+ WebhooksResource,
30
+ )
31
+ from ._version import VERSION
32
+ from .models import Message, WebhookEvent
33
+ from .webhooks import WebhookVerificationError, verify_webhook
34
+
35
+
36
+ class ZapZ(ZapZCore):
37
+ """ZapZ API client. ``api_key`` defaults to the ZAPZ_API_KEY environment variable."""
38
+
39
+ def __init__(self, api_key: Optional[str] = None, *, base_url: Optional[str] = None,
40
+ timeout: float = 30.0, max_retries: int = 2) -> None:
41
+ super().__init__(api_key, base_url=base_url, timeout=timeout, max_retries=max_retries)
42
+ self.instances = InstancesResource(self)
43
+ self.messages = MessagesResource(self)
44
+ self.contacts = ContactsResource(self)
45
+ self.groups = GroupsResource(self)
46
+ self.webhooks = WebhooksResource(self)
47
+ self.sandbox = SandboxResource(self)
48
+
49
+ verify_webhook = staticmethod(verify_webhook)
50
+
51
+
52
+ __all__ = [
53
+ "ZapZ", "VERSION", "DEFAULT_BASE_URL", "Message", "WebhookEvent", "verify_webhook",
54
+ "ZapZError", "APIConnectionError", "ValidationError", "AuthenticationError", "PermissionDeniedError",
55
+ "NotFoundError", "ConflictError", "RateLimitError", "InternalServerError", "WebhookVerificationError",
56
+ ]
@@ -0,0 +1,99 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import random
6
+ import socket
7
+ import time
8
+ import uuid
9
+ import urllib.error
10
+ import urllib.request
11
+ from typing import Any, Dict, Optional
12
+ from urllib.parse import urlencode
13
+
14
+ from ._errors import APIConnectionError, ZapZError, error_from_response
15
+ from ._version import VERSION
16
+
17
+ DEFAULT_BASE_URL = "https://api.zapz.dev"
18
+
19
+
20
+ def _backoff(attempt: int) -> float:
21
+ return min(8.0, 0.5 * 2 ** attempt) * (0.75 + random.random() * 0.5)
22
+
23
+
24
+ class ZapZCore:
25
+ """HTTP layer shared by every resource (stdlib only)."""
26
+
27
+ def __init__(self, api_key: Optional[str] = None, *, base_url: Optional[str] = None,
28
+ timeout: float = 30.0, max_retries: int = 2) -> None:
29
+ key = api_key or os.environ.get("ZAPZ_API_KEY")
30
+ if not key:
31
+ raise ZapZError("Missing API key: pass api_key=... or set ZAPZ_API_KEY.")
32
+ self._api_key = key
33
+ url = (base_url or os.environ.get("ZAPZ_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
34
+ self.base_url = url[:-3] if url.endswith("/v1") else url
35
+ self.timeout = timeout
36
+ self.max_retries = max_retries
37
+
38
+ @property
39
+ def is_sandbox(self) -> bool:
40
+ """True for sk_test_ keys (sandbox: nothing reaches WhatsApp)."""
41
+ return self._api_key.startswith("sk_test_")
42
+
43
+ def request(self, method: str, path: str, *, body: Any = None, query: Optional[Dict[str, Any]] = None,
44
+ auto_client_message_id: bool = False, timeout: Optional[float] = None,
45
+ max_retries: Optional[int] = None) -> Any:
46
+ if auto_client_message_id and isinstance(body, dict) and not body.get("clientMessageId"):
47
+ body = {**body, "clientMessageId": str(uuid.uuid4())}
48
+ url = self.base_url + "/v1" + path
49
+ q = {k: ("true" if v is True else "false" if v is False else v) for k, v in (query or {}).items() if v is not None}
50
+ if q:
51
+ url += "?" + urlencode(q)
52
+ data = json.dumps(body).encode() if body is not None else None
53
+ headers = {
54
+ "Authorization": f"Bearer {self._api_key}",
55
+ "Accept": "application/json",
56
+ "User-Agent": f"zapz-python/{VERSION}",
57
+ }
58
+ if data is not None:
59
+ headers["Content-Type"] = "application/json"
60
+ # a retry is safe when the request is idempotent or carries an idempotency key
61
+ idempotent = method in ("GET", "DELETE") or bool(isinstance(body, dict) and body.get("clientMessageId"))
62
+ retries = self.max_retries if max_retries is None else max_retries
63
+
64
+ attempt = 0
65
+ while True:
66
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
67
+ try:
68
+ with urllib.request.urlopen(req, timeout=timeout or self.timeout) as res: # noqa: S310
69
+ return _parse(res.read())
70
+ except urllib.error.HTTPError as e:
71
+ status = e.code
72
+ payload = _parse(e.read())
73
+ err = error_from_response(status, payload, e.headers.get("Retry-After"))
74
+ refused = status in (429, 503) # nothing was processed
75
+ transient = status in (502, 504)
76
+ if attempt < retries and (refused or (transient and idempotent)):
77
+ wait = err.retry_after if err.retry_after else _backoff(attempt)
78
+ if wait <= 60:
79
+ time.sleep(wait)
80
+ attempt += 1
81
+ continue
82
+ raise err from None
83
+ except (urllib.error.URLError, socket.timeout, ConnectionError, TimeoutError) as e:
84
+ if idempotent and attempt < retries:
85
+ time.sleep(_backoff(attempt))
86
+ attempt += 1
87
+ continue
88
+ reason = getattr(e, "reason", e)
89
+ raise APIConnectionError(f"Connection error: {reason}") from None
90
+
91
+
92
+ def _parse(raw: bytes) -> Any:
93
+ if not raw:
94
+ return None
95
+ text = raw.decode("utf-8", errors="replace")
96
+ try:
97
+ return json.loads(text)
98
+ except ValueError:
99
+ return text
@@ -0,0 +1,88 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Optional
4
+
5
+
6
+ class ZapZError(Exception):
7
+ """Base class for every error raised by the SDK."""
8
+
9
+ def __init__(self, message: str, *, status: Optional[int] = None, code: Optional[str] = None,
10
+ retry_after: Optional[float] = None, body: Any = None) -> None:
11
+ super().__init__(message)
12
+ self.message = message
13
+ #: HTTP status (None for network errors)
14
+ self.status = status
15
+ #: machine-readable code from the API, e.g. ``INSTANCE_NOT_CONNECTED``
16
+ self.code = code
17
+ #: seconds to wait before retrying, when the API says so
18
+ self.retry_after = retry_after
19
+ self.body = body
20
+
21
+ def __str__(self) -> str:
22
+ prefix = f"[{self.status}{' ' + self.code if self.code else ''}] " if self.status else ""
23
+ return prefix + self.message
24
+
25
+
26
+ class APIConnectionError(ZapZError):
27
+ """Could not reach the API (DNS, TLS, timeout, connection reset)."""
28
+
29
+
30
+ class ValidationError(ZapZError):
31
+ """400 / 422: the request is invalid."""
32
+
33
+
34
+ class AuthenticationError(ZapZError):
35
+ """401: missing, revoked or wrong-environment API key."""
36
+
37
+
38
+ class PermissionDeniedError(ZapZError):
39
+ """403: the key lacks a scope, the IP is not allowed or the account is suspended."""
40
+
41
+
42
+ class NotFoundError(ZapZError):
43
+ """404"""
44
+
45
+
46
+ class ConflictError(ZapZError):
47
+ """409: e.g. the instance is not connected."""
48
+
49
+
50
+ class RateLimitError(ZapZError):
51
+ """429: rate limit or anti-ban pacing. See ``retry_after``."""
52
+
53
+
54
+ class InternalServerError(ZapZError):
55
+ """5xx"""
56
+
57
+
58
+ def error_from_response(status: int, body: Any, retry_after_header: Optional[str]) -> ZapZError:
59
+ data = body if isinstance(body, dict) else {}
60
+ msg = data.get("message")
61
+ if isinstance(msg, list):
62
+ msg = "; ".join(str(m) for m in msg)
63
+ message = str(msg) if msg else f"HTTP {status}"
64
+ retry_after: Optional[float] = None
65
+ for v in (data.get("retryAfter"), retry_after_header):
66
+ try:
67
+ if v is not None:
68
+ retry_after = float(v)
69
+ break
70
+ except (TypeError, ValueError):
71
+ pass
72
+ code = data.get("error") if isinstance(data.get("error"), str) else None
73
+ kw = dict(status=status, code=code, retry_after=retry_after, body=body)
74
+ if status in (400, 422):
75
+ return ValidationError(message, **kw)
76
+ if status == 401:
77
+ return AuthenticationError(message, **kw)
78
+ if status == 403:
79
+ return PermissionDeniedError(message, **kw)
80
+ if status == 404:
81
+ return NotFoundError(message, **kw)
82
+ if status == 409:
83
+ return ConflictError(message, **kw)
84
+ if status == 429:
85
+ return RateLimitError(message, **kw)
86
+ if status >= 500:
87
+ return InternalServerError(message, **kw)
88
+ return ZapZError(message, **kw)
@@ -0,0 +1,2 @@
1
+ # Generated by generator/generate.py from openapi.json. Do not edit.
2
+ from .resources import InstancesResource, MessagesResource, ContactsResource, GroupsResource, WebhooksResource, SandboxResource