zapiack 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.
@@ -0,0 +1,194 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime
4
+ from typing import Any, List, Optional
5
+
6
+ from ..pagination import Page
7
+ from .base import Options, Params, Resource, UploadFile, quote
8
+
9
+
10
+ def _iso(value: Any) -> Any:
11
+ return value.isoformat() if isinstance(value, datetime) else value
12
+
13
+
14
+ class Messages(Resource):
15
+ def get(self, id: str, options: Options = None) -> Any:
16
+ return self._call("GET", f"push/messages/{quote(id)}", options=options)
17
+
18
+ def list(self, params: Optional[Params] = None, options: Options = None) -> Page:
19
+ return self._paged("push/messages", "messages", params, options)
20
+
21
+ def cancel(self, id: str, options: Options = None) -> Any:
22
+ """Cancels a scheduled push. Once it has started going out it cannot be recalled."""
23
+ return self._call("DELETE", f"push/messages/{quote(id)}", options=options)
24
+
25
+ def reschedule(self, id: str, scheduled_at: Any, options: Options = None) -> Any:
26
+ """Moves a scheduled push to another time."""
27
+ return self._call("PATCH", f"push/messages/{quote(id)}", body={"scheduledAt": _iso(scheduled_at)}, options=options)
28
+
29
+ def retry(self, id: str, params: Optional[Params] = None, options: Options = None) -> Any:
30
+ """Sends again to the devices a message failed for: all of them, or only `deliveryIds`. A device that is gone is never retried."""
31
+ return self._call("POST", f"push/messages/{quote(id)}/retry", body=dict(params or {}), options=options)
32
+
33
+ def metrics(self, id: str, options: Options = None) -> Any:
34
+ """Counts, rates, platforms, failures, buttons, events and a timeline for one message."""
35
+ return self._call("GET", f"push/messages/{quote(id)}/metrics", options=options)
36
+
37
+ def deliveries(self, id: str, params: Optional[Params] = None, options: Options = None) -> Page:
38
+ return self._paged(f"push/messages/{quote(id)}/deliveries", "deliveries", params, options)
39
+
40
+ def funnel(self, id: str, options: Options = None) -> Any:
41
+ """Sent, arrived, tapped, each button, converted, and the screens people went to next."""
42
+ return self._call("GET", f"push/messages/{quote(id)}/funnel", options=options)
43
+
44
+
45
+ class Devices(Resource):
46
+ def list(self, params: Optional[Params] = None, options: Options = None) -> Page:
47
+ return self._paged("push/devices", "devices", params, options)
48
+
49
+ def get(self, id: str, app_id: Optional[str] = None, options: Options = None) -> Any:
50
+ return self._call("GET", f"push/devices/{quote(id)}", query={"appId": app_id}, options=options)
51
+
52
+ def update(self, id: str, params: Params, options: Options = None) -> Any:
53
+ """Changes who a device belongs to or its tags. Tags you pass are merged with the ones it already has."""
54
+ body = dict(params)
55
+ app_id = body.pop("appId", None)
56
+ return self._call("PATCH", f"push/devices/{quote(id)}", query={"appId": app_id}, body=body, options=options)
57
+
58
+ def remove(self, id: str, app_id: Optional[str] = None, options: Options = None) -> None:
59
+ """Stops sending to a device and forgets who it belonged to."""
60
+ self._call("DELETE", f"push/devices/{quote(id)}", query={"appId": app_id}, options=options)
61
+
62
+
63
+ class Segments(Resource):
64
+ """Named audiences: people you list by hand, plus anyone carrying every tag of an optional rule."""
65
+
66
+ def list(self, app_id: Optional[str] = None, options: Options = None) -> Any:
67
+ return self._call("GET", "push/segments", query={"appId": app_id}, options=options)
68
+
69
+ def get(self, id: str, app_id: Optional[str] = None, options: Options = None) -> Any:
70
+ return self._call("GET", f"push/segments/{quote(id)}", query={"appId": app_id}, options=options)
71
+
72
+ def create(self, params: Params, options: Options = None) -> Any:
73
+ return self._call("POST", "push/segments", body=dict(params), options=options)
74
+
75
+ def update(self, id: str, params: Params, options: Options = None) -> Any:
76
+ body = dict(params)
77
+ app_id = body.pop("appId", None)
78
+ return self._call("PATCH", f"push/segments/{quote(id)}", query={"appId": app_id}, body=body, options=options)
79
+
80
+ def remove(self, id: str, app_id: Optional[str] = None, options: Options = None) -> None:
81
+ self._call("DELETE", f"push/segments/{quote(id)}", query={"appId": app_id}, options=options)
82
+
83
+ def members(self, id: str, params: Optional[Params] = None, options: Options = None) -> Page:
84
+ return self._paged(f"push/segments/{quote(id)}/members", "members", params, options)
85
+
86
+ def add_members(self, id: str, external_user_ids: List[str], app_id: Optional[str] = None, options: Options = None) -> Any:
87
+ """Adds people by the user ids your app gave Zapiack. Up to 1,000 at a time."""
88
+ return self._call("POST", f"push/segments/{quote(id)}/members", query={"appId": app_id}, body={"externalUserIds": external_user_ids}, options=options)
89
+
90
+ def remove_members(self, id: str, external_user_ids: List[str], app_id: Optional[str] = None, options: Options = None) -> Any:
91
+ return self._call("POST", f"push/segments/{quote(id)}/members/remove", query={"appId": app_id}, body={"externalUserIds": external_user_ids}, options=options)
92
+
93
+
94
+ class Credentials(Resource):
95
+ def apns(self, app_id: str, params: Params, options: Options = None) -> Any:
96
+ """An APNs key: `privateKey` (the .p8 text), `keyId`, `teamId`, and `environment`. Checked with Apple before it is saved."""
97
+ return self._call("PUT", f"push/apps/{quote(app_id)}/credentials/apns", body=dict(params), options=options)
98
+
99
+ def fcm(self, app_id: str, params: Params, options: Options = None) -> Any:
100
+ """A Firebase service account, as `serviceAccount`. Checked with Google before it is saved."""
101
+ return self._call("PUT", f"push/apps/{quote(app_id)}/credentials/fcm", body=dict(params), options=options)
102
+
103
+ def hms(self, app_id: str, params: Params, options: Options = None) -> Any:
104
+ """Huawei Push Kit: `appId` and `appSecret` from AppGallery Connect."""
105
+ return self._call("PUT", f"push/apps/{quote(app_id)}/credentials/hms", body=dict(params), options=options)
106
+
107
+ def validate(self, app_id: str, credential_id: str, options: Options = None) -> Any:
108
+ return self._call("POST", f"push/apps/{quote(app_id)}/credentials/{quote(credential_id)}/validate", options=options)
109
+
110
+ def remove(self, app_id: str, credential_id: str, options: Options = None) -> None:
111
+ self._call("DELETE", f"push/apps/{quote(app_id)}/credentials/{quote(credential_id)}", options=options)
112
+
113
+
114
+ class Apps(Resource):
115
+ def __init__(self, http: Any) -> None:
116
+ super().__init__(http)
117
+ self.credentials = Credentials(http)
118
+
119
+ def list(self, options: Options = None) -> Any:
120
+ return self._call("GET", "push/apps", options=options)
121
+
122
+ def get(self, id: str, options: Options = None) -> Any:
123
+ return self._call("GET", f"push/apps/{quote(id)}", options=options)
124
+
125
+ def create(self, params: Params, options: Options = None) -> Any:
126
+ return self._call("POST", "push/apps", body=dict(params), options=options)
127
+
128
+ def update(self, id: str, params: Params, options: Options = None) -> Any:
129
+ return self._call("PATCH", f"push/apps/{quote(id)}", body=dict(params), options=options)
130
+
131
+ def remove(self, id: str, options: Options = None) -> None:
132
+ self._call("DELETE", f"push/apps/{quote(id)}", options=options)
133
+
134
+
135
+ class Webhooks(Resource):
136
+ def list(self, options: Options = None) -> Any:
137
+ return self._call("GET", "push/webhooks", options=options)
138
+
139
+ def create(self, params: Params, options: Options = None) -> Any:
140
+ """The answer carries the signing secret once. Keep it: it is how you check a delivery came from Zapiack."""
141
+ return self._call("POST", "push/webhooks", body=dict(params), options=options)
142
+
143
+ def update(self, id: str, params: Params, options: Options = None) -> Any:
144
+ return self._call("PATCH", f"push/webhooks/{quote(id)}", body=dict(params), options=options)
145
+
146
+ def rotate_secret(self, id: str, options: Options = None) -> Any:
147
+ return self._call("POST", f"push/webhooks/{quote(id)}/secret", options=options)
148
+
149
+ def test(self, id: str, options: Options = None) -> Any:
150
+ """Sends a sample event to the endpoint and says whether it answered."""
151
+ return self._call("POST", f"push/webhooks/{quote(id)}/test", options=options)
152
+
153
+ def remove(self, id: str, options: Options = None) -> None:
154
+ self._call("DELETE", f"push/webhooks/{quote(id)}", options=options)
155
+
156
+
157
+ class Images(Resource):
158
+ def upload(self, file: UploadFile, options: Options = None) -> Any:
159
+ """Uploads a picture (PNG or JPEG, up to 2 MB) and answers with the https `url` to use as a push's `image`."""
160
+ return self._call("POST", "push/images", form=file.to_form(), options=options)
161
+
162
+
163
+ class Push(Resource):
164
+ def __init__(self, http: Any) -> None:
165
+ super().__init__(http)
166
+ self.messages = Messages(http)
167
+ self.devices = Devices(http)
168
+ self.segments = Segments(http)
169
+ self.apps = Apps(http)
170
+ self.webhooks = Webhooks(http)
171
+ self.images = Images(http)
172
+
173
+ def metrics(self, params: Optional[Params] = None, options: Options = None) -> Any:
174
+ """Counts over time for the project, or for one app, platform or message. Buckets are cut in `tz`."""
175
+ query = dict(params or {})
176
+ for key in ("from", "to"):
177
+ if key in query:
178
+ query[key] = _iso(query[key])
179
+ return self._call("GET", "push/metrics", query=query, options=options)
180
+
181
+ def reachable(self, params: Params, options: Options = None) -> Any:
182
+ """How many devices an audience would reach, per platform, before anything is sent."""
183
+ return self._call("POST", "push/reachable", body=dict(params), options=options)
184
+
185
+ def send(self, params: Params, options: Options = None) -> Any:
186
+ """Sends a push notification to a device, a user, everyone with certain tags, or everyone.
187
+
188
+ Answers once the push is accepted; delivery is reported by webhook or by `messages.get`. Repeating the call with the
189
+ same `idempotency_key` never sends it twice. `scheduled_at` may be a datetime (with a time zone) or an ISO 8601 string.
190
+ """
191
+ body = dict(params)
192
+ if "scheduledAt" in body:
193
+ body["scheduledAt"] = _iso(body["scheduledAt"])
194
+ return self._call("POST", "push/messages", body=body, send=True, options=options)
@@ -0,0 +1,16 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, List
4
+
5
+ from .base import Options, Params, Resource
6
+
7
+
8
+ class Sms(Resource):
9
+ def send(self, params: Params, options: Options = None) -> Any:
10
+ """Sends one SMS: `phone`, `country` (two letters, for example NG) and `message`. Repeating the call with the same
11
+ `idempotency_key` never sends or charges it twice."""
12
+ return self._call("POST", "sms/send", body=dict(params), send=True, options=options)
13
+
14
+ def send_batch(self, messages: List[Params], options: Options = None) -> Any:
15
+ """Sends many SMS in one request."""
16
+ return self._call("POST", "sms/send/batch", body=[dict(m) for m in messages], send=True, options=options)
@@ -0,0 +1,176 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime
4
+ from typing import Any, List, Optional, Union
5
+
6
+ from .base import Options, Params, Resource, UploadFile, quote
7
+
8
+
9
+ class Templates(Resource):
10
+ def list(self, options: Options = None) -> Any:
11
+ return self._call("GET", "whatsapp/templates", options=options)
12
+
13
+ def get(self, id: str, options: Options = None) -> Any:
14
+ return self._call("GET", f"whatsapp/templates/{quote(id)}", options=options)
15
+
16
+ def create(self, params: Params, options: Options = None) -> Any:
17
+ return self._call("POST", "whatsapp/templates", body=params, options=options)
18
+
19
+ def dismiss_category_change(self, id: str, options: Options = None) -> Any:
20
+ """Acknowledges that Meta changed a template's category, so the notice goes away."""
21
+ return self._call("POST", f"whatsapp/templates/{quote(id)}/dismiss-category-change", options=options)
22
+
23
+ def remove(self, id: str, options: Options = None) -> None:
24
+ self._call("DELETE", f"whatsapp/templates/{quote(id)}", options=options)
25
+
26
+
27
+ class Contacts(Resource):
28
+ def list(self, params: Optional[Params] = None, options: Options = None) -> Any:
29
+ return self._call("GET", "whatsapp/contacts", query=params, options=options)
30
+
31
+ def opt_in(self, params: Params, options: Options = None) -> Any:
32
+ return self._call("POST", "whatsapp/contacts/opt-in", body=params, options=options)
33
+
34
+ def opt_out(self, params: Params, options: Options = None) -> Any:
35
+ return self._call("POST", "whatsapp/contacts/opt-out", body=params, options=options)
36
+
37
+
38
+ class Media(Resource):
39
+ def upload(self, file: UploadFile, options: Options = None) -> Any:
40
+ """Uploads a file to send in a message. Use the id it returns as `media.id`."""
41
+ return self._call("POST", "whatsapp/media", form=file.to_form(), options=options)
42
+
43
+ def upload_from_url(self, params: Params, options: Options = None) -> Any:
44
+ """Has Zapiack fetch a file from a public address, instead of uploading its bytes."""
45
+ return self._call("POST", "whatsapp/media/url", body=params, options=options)
46
+
47
+ def get(self, id: str, options: Options = None) -> Any:
48
+ return self._call("GET", f"whatsapp/media/{quote(id)}", options=options)
49
+
50
+
51
+ class Conversations(Resource):
52
+ def list(self, params: Optional[Params] = None, options: Options = None) -> Any:
53
+ return self._call("GET", "whatsapp/conversations", query=params, options=options)
54
+
55
+ def get(self, id: str, options: Options = None) -> Any:
56
+ return self._call("GET", f"whatsapp/conversations/{quote(id)}", options=options)
57
+
58
+ def messages(self, id: str, params: Optional[Params] = None, options: Options = None) -> Any:
59
+ """The messages of a conversation, newest first. Pass `before` to page back in time."""
60
+ return self._call("GET", f"whatsapp/conversations/{quote(id)}/messages", query=params, options=options)
61
+
62
+ def reply(self, id: str, params: Params, options: Options = None) -> Any:
63
+ """Replies inside a conversation. Repeating the call with the same `idempotency_key` never sends it twice."""
64
+ return self._call("POST", f"whatsapp/conversations/{quote(id)}/messages", body=dict(params), send=True, options=options)
65
+
66
+ def assign(self, id: str, user_id: Optional[str], options: Options = None) -> Any:
67
+ """Assigns the conversation to a team member, or to nobody when `user_id` is None."""
68
+ return self._call("POST", f"whatsapp/conversations/{quote(id)}/assign", body={"userId": user_id}, options=options)
69
+
70
+ def mark_read(self, id: str, options: Options = None) -> Any:
71
+ return self._call("POST", f"whatsapp/conversations/{quote(id)}/read", options=options)
72
+
73
+
74
+ class Broadcasts(Resource):
75
+ def create(self, params: Params, options: Options = None) -> Any:
76
+ return self._call("POST", "whatsapp/broadcasts", body=params, options=options)
77
+
78
+ def list(self, params: Optional[Params] = None, options: Options = None) -> Any:
79
+ return self._call("GET", "whatsapp/broadcasts", query=params, options=options)
80
+
81
+ def get(self, id: str, options: Options = None) -> Any:
82
+ return self._call("GET", f"whatsapp/broadcasts/{quote(id)}", options=options)
83
+
84
+ def add_recipients(self, id: str, recipients: List[Params], options: Options = None) -> Any:
85
+ return self._call("POST", f"whatsapp/broadcasts/{quote(id)}/recipients", body={"recipients": recipients}, options=options)
86
+
87
+ def recipients(self, id: str, params: Optional[Params] = None, options: Options = None) -> Any:
88
+ return self._call("GET", f"whatsapp/broadcasts/{quote(id)}/recipients", query=params, options=options)
89
+
90
+ def check(self, id: str, options: Options = None) -> Any:
91
+ """Checks the broadcast before it starts: who can be reached, and what it will cost."""
92
+ return self._call("POST", f"whatsapp/broadcasts/{quote(id)}/check", options=options)
93
+
94
+ def start(self, id: str, scheduled_at: Union[str, datetime, None] = None, options: Options = None) -> Any:
95
+ """Starts the broadcast now, or at `scheduled_at` (an ISO 8601 time with its time zone)."""
96
+ when = scheduled_at.isoformat() if isinstance(scheduled_at, datetime) else scheduled_at
97
+ return self._call("POST", f"whatsapp/broadcasts/{quote(id)}/start", body={"scheduledAt": when} if when else {}, options=options)
98
+
99
+ def pause(self, id: str, options: Options = None) -> Any:
100
+ return self._call("POST", f"whatsapp/broadcasts/{quote(id)}/pause", options=options)
101
+
102
+ def resume(self, id: str, options: Options = None) -> Any:
103
+ return self._call("POST", f"whatsapp/broadcasts/{quote(id)}/resume", options=options)
104
+
105
+ def cancel(self, id: str, options: Options = None) -> Any:
106
+ return self._call("POST", f"whatsapp/broadcasts/{quote(id)}/cancel", options=options)
107
+
108
+
109
+ class WebhookEndpoints(Resource):
110
+ """Where Zapiack tells your server about WhatsApp events. Verify each request with `client.webhooks.verify`."""
111
+
112
+ def create(self, params: Params, options: Options = None) -> Any:
113
+ """The signing secret in the answer is shown once."""
114
+ return self._call("POST", "whatsapp/webhook-endpoints", body=params, options=options)
115
+
116
+ def list(self, options: Options = None) -> Any:
117
+ return self._call("GET", "whatsapp/webhook-endpoints", options=options)
118
+
119
+ def event_types(self, options: Options = None) -> Any:
120
+ """The events an endpoint can subscribe to."""
121
+ return self._call("GET", "whatsapp/webhook-events", options=options)
122
+
123
+ def update(self, id: str, params: Params, options: Options = None) -> Any:
124
+ return self._call("PATCH", f"whatsapp/webhook-endpoints/{quote(id)}", body=params, options=options)
125
+
126
+ def test(self, options: Options = None) -> Any:
127
+ """Sends a signed sample to every endpoint."""
128
+ return self._call("POST", "whatsapp/webhook-endpoints/test", options=options)
129
+
130
+ def remove(self, id: str, options: Options = None) -> None:
131
+ self._call("DELETE", f"whatsapp/webhook-endpoints/{quote(id)}", options=options)
132
+
133
+ def rotate_secret(self, id: str, options: Options = None) -> Any:
134
+ """Makes a new signing secret; the old one stops working. The new one is shown once."""
135
+ return self._call("POST", f"whatsapp/webhook-endpoints/{quote(id)}/rotate-secret", options=options)
136
+
137
+ def enable(self, id: str, options: Options = None) -> Any:
138
+ """Turns an endpoint back on after it was switched off for failing."""
139
+ return self._call("POST", f"whatsapp/webhook-endpoints/{quote(id)}/enable", options=options)
140
+
141
+
142
+ class WebhookDeliveries(Resource):
143
+ def list(self, params: Optional[Params] = None, options: Options = None) -> Any:
144
+ return self._call("GET", "whatsapp/webhook-deliveries", query=params, options=options)
145
+
146
+ def replay(self, id: str, options: Options = None) -> Any:
147
+ """Sends a past delivery again, for example after you fixed your endpoint."""
148
+ return self._call("POST", f"whatsapp/webhook-deliveries/{quote(id)}/replay", options=options)
149
+
150
+
151
+ class Whatsapp(Resource):
152
+ def __init__(self, http: Any) -> None:
153
+ super().__init__(http)
154
+ self.templates = Templates(http)
155
+ self.contacts = Contacts(http)
156
+ self.media = Media(http)
157
+ self.conversations = Conversations(http)
158
+ self.broadcasts = Broadcasts(http)
159
+ self.webhook_endpoints = WebhookEndpoints(http)
160
+ self.webhook_deliveries = WebhookDeliveries(http)
161
+
162
+ def send(self, params: Params, options: Options = None) -> Any:
163
+ """Sends a message. Repeating the call with the same `idempotency_key` never sends or charges it twice."""
164
+ return self._call("POST", "whatsapp/messages", body=dict(params), send=True, options=options)
165
+
166
+ def send_template(self, *, from_: str, to: str, template: Params, options: Options = None) -> Any:
167
+ return self.send({"from": from_, "to": to, "type": "template", "template": template}, options)
168
+
169
+ def send_text(self, *, from_: str, to: str, body: str, options: Options = None) -> Any:
170
+ return self.send({"from": from_, "to": to, "type": "text", "body": body}, options)
171
+
172
+ def get_message(self, id: str, options: Options = None) -> Any:
173
+ return self._call("GET", f"whatsapp/messages/{quote(id)}", options=options)
174
+
175
+ def numbers(self, options: Options = None) -> Any:
176
+ return self._call("GET", "whatsapp/numbers", options=options)
zapiack/webhooks.py ADDED
@@ -0,0 +1,64 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import json
6
+ import re
7
+ import time
8
+ from typing import Any, Optional, Union
9
+
10
+ from .errors import ZapiackSignatureError
11
+
12
+ _HEADER = re.compile(r"^t=(\d+),v1=([0-9a-f]{64})$")
13
+
14
+
15
+ def _signature(secret: str, timestamp: Union[int, str], body: str) -> str:
16
+ return hmac.new(secret.encode(), f"{timestamp}.{body}".encode(), hashlib.sha256).hexdigest()
17
+
18
+
19
+ class Webhooks:
20
+ """Checks and reads a webhook.
21
+
22
+ Pass the **raw** request body (before any JSON parsing), the `Zapiack-Signature` header and your endpoint's signing secret.
23
+ """
24
+
25
+ def verify(
26
+ self,
27
+ raw_body: Union[str, bytes],
28
+ signature_header: Optional[str],
29
+ secret: str,
30
+ *,
31
+ tolerance_seconds: int = 300,
32
+ now: Optional[float] = None,
33
+ ) -> Any:
34
+ """Returns the parsed body, or raises ZapiackSignatureError when the signature is missing, wrong or too old."""
35
+ body = raw_body.decode("utf-8") if isinstance(raw_body, (bytes, bytearray)) else raw_body
36
+ match = _HEADER.match(signature_header or "")
37
+ if not match:
38
+ raise ZapiackSignatureError("The Zapiack-Signature header is missing or malformed")
39
+
40
+ timestamp = int(match.group(1))
41
+ current = int(time.time() if now is None else now)
42
+ if abs(current - timestamp) > tolerance_seconds:
43
+ raise ZapiackSignatureError("The webhook is too old, or its clock is wrong")
44
+
45
+ if not hmac.compare_digest(_signature(secret, match.group(1), body), match.group(2)):
46
+ raise ZapiackSignatureError("The webhook signature does not match")
47
+
48
+ try:
49
+ return json.loads(body)
50
+ except ValueError as error:
51
+ raise ZapiackSignatureError("The webhook body is not valid JSON") from error
52
+
53
+ def is_valid(self, raw_body: Union[str, bytes], signature_header: Optional[str], secret: str, **kwargs: Any) -> bool:
54
+ """Whether a webhook is genuine, without reading it."""
55
+ try:
56
+ self.verify(raw_body, signature_header, secret, **kwargs)
57
+ return True
58
+ except ZapiackSignatureError:
59
+ return False
60
+
61
+ def sign(self, secret: str, body: str, timestamp: Optional[int] = None) -> str:
62
+ """Signs a body the way Zapiack does: for testing your own webhook handler."""
63
+ ts = int(time.time()) if timestamp is None else timestamp
64
+ return f"t={ts},v1={_signature(secret, ts, body)}"
@@ -0,0 +1,185 @@
1
+ Metadata-Version: 2.4
2
+ Name: zapiack
3
+ Version: 0.1.0
4
+ Summary: The official Zapiack SDK for Python: email, SMS and push notifications from one client.
5
+ Author-email: Zapiack <support@zapiack.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://zapiack.com
8
+ Project-URL: Documentation, https://docs.zapiack.com/introduction
9
+ Project-URL: Source, https://github.com/zapiack-hq/zapiack-python
10
+ Project-URL: Issues, https://github.com/zapiack-hq/zapiack-python/issues
11
+ Keywords: zapiack,email,sms,push,notifications,sdk
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Dynamic: license-file
25
+
26
+ # zapiack (Python)
27
+
28
+ The official Zapiack SDK for Python. Send email, SMS and push notifications from one client.
29
+
30
+ ```bash
31
+ pip install zapiack
32
+ ```
33
+
34
+ Python 3.9 or later. No dependencies.
35
+
36
+ ## Quickstart
37
+
38
+ ```python
39
+ import os
40
+ from zapiack import Zapiack
41
+
42
+ zapiack = Zapiack(os.environ["ZAPIACK_API_KEY"])
43
+
44
+ zapiack.email.send({
45
+ "from": "orders@myshop.com",
46
+ "to": "ada@example.com",
47
+ "subject": "Your order has shipped",
48
+ "html": "<p>It is on its way.</p>",
49
+ })
50
+
51
+ zapiack.sms.send({"phone": "+2348012345678", "country": "NG", "message": "Your order has shipped"})
52
+
53
+ zapiack.push.send({
54
+ "target": {"externalUserIds": ["user_123"]},
55
+ "title": "Your order has shipped",
56
+ "body": "Tap to track it",
57
+ "link": {"app": "myshop://orders/ord_789"},
58
+ })
59
+ ```
60
+
61
+ Create a secret API key in the dashboard under **Project → API Keys**. Keep it on your server: the client refuses a public app key.
62
+ The key can also come from the `ZAPIACK_API_KEY` environment variable: `Zapiack()`.
63
+
64
+ Parameters and answers are plain dictionaries, with the same names as the REST API and every other Zapiack SDK.
65
+
66
+ ## What it does for you
67
+
68
+ - **Safe retries.** A failed request is retried up to twice, with backoff, on network errors, `429` and `5xx`, honouring
69
+ `Retry-After`. Only requests that cannot happen twice are retried: reads, and sends, which carry an idempotency key.
70
+ - **Idempotent sends.** Every send gets an `Idempotency-Key` automatically, so a retried send never goes out twice. Pass your own
71
+ to make a repeat from your code safe too: `zapiack.sms.send(params, RequestOptions(idempotency_key="order-42"))`.
72
+ - **Typed errors.** Every failure is a `ZapiackError` with a stable `code`, the HTTP `status` and a `request_id`.
73
+ - **Timeouts.** 30 seconds by default, per client or per call.
74
+ - **Pagination.** List calls return the first page; iterate it to walk every page.
75
+ - **Webhook verification.** One call checks the signature and reads the body.
76
+
77
+ ```python
78
+ from zapiack import Zapiack, RequestOptions
79
+
80
+ zapiack = Zapiack("zpk_...", timeout=10, max_retries=3, app_info="my-app/1.4.0")
81
+ zapiack.sms.send(params, RequestOptions(idempotency_key="order-42", timeout=5))
82
+ ```
83
+
84
+ ## Email
85
+
86
+ ```python
87
+ zapiack.email.send({"from": f, "to": ["a@x.com", "b@x.com"], "templateId": "tpl_1", "variables": {"name": "Ada"}})
88
+ zapiack.email.send_batch([{"from": f, "to": "a@x.com", "subject": s, "html": h}, ...])
89
+ status = zapiack.email.get(email_id)
90
+
91
+ zapiack.email.contacts.create({"email": "ada@example.com", "firstName": "Ada"})
92
+ for contact in zapiack.email.contacts.list({"status": "SUBSCRIBED"}): # every contact, on every page
93
+ print(contact["email"])
94
+
95
+ zapiack.email.domains.add("myshop.com")
96
+ zapiack.email.templates.upload_asset(template_id, UploadFile(logo_bytes, "logo.png", "image/png"))
97
+ ```
98
+
99
+ Attachments take bytes or base64: `"attachments": [{"filename": "invoice.pdf", "content": pdf_bytes}]`.
100
+
101
+ ## SMS
102
+
103
+ ```python
104
+ zapiack.sms.send({"phone": "+2348012345678", "country": "NG", "message": "Hello"})
105
+ zapiack.sms.send_batch([{"phone": p, "country": "NG", "message": m}, ...])
106
+ ```
107
+
108
+ ## Push notifications
109
+
110
+ ```python
111
+ sent = zapiack.push.send({
112
+ "target": {"tags": {"plan": "pro"}},
113
+ "title": "New in Pro",
114
+ "body": "See what is new",
115
+ "image": "https://cdn.myshop.com/launch.jpg",
116
+ "actions": [{"id": "open", "title": "Open", "event": "launch_opened", "link": {"app": "myshop://launch"}}],
117
+ "tracking": {"windowMinutes": 60, "screens": True, "goal": "upgrade_completed"},
118
+ "scheduledAt": datetime(2026, 12, 1, 9, tzinfo=timezone.utc),
119
+ })
120
+
121
+ zapiack.push.messages.reschedule(sent["messageId"], "2026-12-02T09:00:00+01:00")
122
+ zapiack.push.messages.cancel(sent["messageId"])
123
+ funnel = zapiack.push.messages.funnel(sent["messageId"])
124
+ ```
125
+
126
+ A scheduled push works out who it reaches when its time comes. It can be cancelled or moved while it is still scheduled, and not
127
+ after it has started going out. Device-side registration and click tracking are done by the client SDKs inside your app.
128
+
129
+ ## Webhooks
130
+
131
+ Pass the **raw** request body, the `Zapiack-Signature` header and your endpoint's signing secret:
132
+
133
+ ```python
134
+ from flask import Flask, request
135
+ from zapiack import ZapiackSignatureError
136
+
137
+ @app.post("/zapiack")
138
+ def hook():
139
+ try:
140
+ payload = zapiack.webhooks.verify(request.get_data(), request.headers.get("Zapiack-Signature"), os.environ["ZAPIACK_WEBHOOK_SECRET"])
141
+ except ZapiackSignatureError:
142
+ return "", 400
143
+ for event in payload["events"]:
144
+ if event["type"] == "push.clicked":
145
+ print(event["externalUserId"], event["messageId"])
146
+ return "", 204
147
+ ```
148
+
149
+ `verify` raises `ZapiackSignatureError` when the signature is missing, wrong, or older than five minutes. Return any `2xx` to
150
+ acknowledge; otherwise the delivery is retried for up to a day.
151
+
152
+ ## Errors
153
+
154
+ ```python
155
+ from zapiack import ZapiackError
156
+
157
+ try:
158
+ zapiack.sms.send(params)
159
+ except ZapiackError as error:
160
+ print(error.code, error.status, error.request_id, error.details)
161
+ if error.code == "insufficient_balance": ...
162
+ if error.code == "rate_limited": time.sleep(error.retry_after or 1)
163
+ ```
164
+
165
+ | `code` | When |
166
+ |---|---|
167
+ | `invalid_request` | The request was wrong. `details` lists what, when the API says |
168
+ | `authentication_failed` | The key is missing or not valid |
169
+ | `insufficient_balance` | The wallet cannot cover the send |
170
+ | `permission_denied` | The key may not do this |
171
+ | `not_found` | There is no such thing |
172
+ | `conflict` | It clashes with what is already there |
173
+ | `unprocessable` | The request was understood and refused |
174
+ | `rate_limited` | Too many requests. `retry_after` says how long to wait |
175
+ | `server_error` | Zapiack failed. Retried for you, then raised |
176
+ | `connection_error`, `timeout` | No answer was received |
177
+ | `invalid_signature` | A webhook was not genuine |
178
+
179
+ A code the API names itself, such as `credential_invalid`, is passed through in lower case.
180
+
181
+ ## Tests
182
+
183
+ ```
184
+ python -m unittest discover -s tests
185
+ ```
@@ -0,0 +1,19 @@
1
+ zapiack/__init__.py,sha256=eiC92F6Tpr569u0ShQyqVrnMp3kErs4Wm7N9BaYl3Ig,688
2
+ zapiack/_http.py,sha256=FecmClsJwQubh-9P0QxGUgZmEQJjSvp3ng5IolX4taI,8310
3
+ zapiack/_version.py,sha256=CpXi3jGlx23RvRyU7iytOMZrnspdWw4yofS8lpP1AJU,18
4
+ zapiack/client.py,sha256=airR-W2lnd4Ydw2Me_YNJRV1Dh_k36MXjibmkp50b14,1778
5
+ zapiack/errors.py,sha256=cSyWu_ur4Im1WMi9ud7HKxLjgUcBhn7U4fE3T9AAwIc,3855
6
+ zapiack/pagination.py,sha256=vyvKBMSF-rA9iHQpH5eTlCpvAHxV1ezGYStQ7YFh0Nk,1812
7
+ zapiack/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ zapiack/webhooks.py,sha256=4u-cZvGYfw8iqh3pdmdjcbP2uPmoRhSubxsfMh2wtxI,2468
9
+ zapiack/resources/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ zapiack/resources/base.py,sha256=KYUKiDHzZcCI9nteEoTmh5YrUIFjA3H3nArUHkyqzB8,1901
11
+ zapiack/resources/email.py,sha256=ydgvPWUhLRSHZFrVf6emoYkpADlS9inDOTb5I1l6R38,7862
12
+ zapiack/resources/push.py,sha256=iGQ9I9JNyErndazHnYa7wKpMetERPd9VACcjiGscyoM,10493
13
+ zapiack/resources/sms.py,sha256=K1mFSTY8Y51d9aI7ZjHnv-NvR0bIL2pOyequHEqOJlU,721
14
+ zapiack/resources/whatsapp.py,sha256=VheOVhCad-cBRNHNjTKupTCtktnENJ8RQ73esGcG-3g,9445
15
+ zapiack-0.1.0.dist-info/licenses/LICENSE,sha256=dPK3Gyy2B6EP3QlaDa9J-eKwesIXTgvz4-jmRfWTXi0,1064
16
+ zapiack-0.1.0.dist-info/METADATA,sha256=ngQpmurAGRA72NT-bK56Zr-COMh_YMZnpf-vCHeTc80,6983
17
+ zapiack-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
18
+ zapiack-0.1.0.dist-info/top_level.txt,sha256=zn6B0pjnyl_1hemt1-gy_N6jhXnWb7RQBnq6j0hL50U,8
19
+ zapiack-0.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
+