msgine 1.0.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.
- msgine/__init__.py +16 -0
- msgine/_async.py +60 -0
- msgine/_core.py +155 -0
- msgine/_sync.py +60 -0
- msgine/_version.py +1 -0
- msgine/client.py +98 -0
- msgine/errors.py +32 -0
- msgine/py.typed +0 -0
- msgine/resources.py +551 -0
- msgine/webhooks.py +46 -0
- msgine-1.0.0.dist-info/METADATA +155 -0
- msgine-1.0.0.dist-info/RECORD +13 -0
- msgine-1.0.0.dist-info/WHEEL +4 -0
msgine/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from ._core import Page
|
|
2
|
+
from ._version import __version__
|
|
3
|
+
from .client import AsyncMsGine, MsGine
|
|
4
|
+
from .errors import MsGineConnectionError, MsGineError, WebhookVerificationError
|
|
5
|
+
from .webhooks import verify_webhook
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"AsyncMsGine",
|
|
9
|
+
"MsGine",
|
|
10
|
+
"MsGineConnectionError",
|
|
11
|
+
"MsGineError",
|
|
12
|
+
"Page",
|
|
13
|
+
"WebhookVerificationError",
|
|
14
|
+
"__version__",
|
|
15
|
+
"verify_webhook",
|
|
16
|
+
]
|
msgine/_async.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
from . import _core
|
|
8
|
+
from ._core import Config, Transform, backoff, encode_body, parse_body, retry_after_seconds, to_error
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AsyncTransport:
|
|
12
|
+
def __init__(self, config: Config, client: httpx.AsyncClient | None) -> None:
|
|
13
|
+
self._config = config
|
|
14
|
+
self._owns_client = client is None
|
|
15
|
+
self._client = client or httpx.AsyncClient()
|
|
16
|
+
|
|
17
|
+
async def aclose(self) -> None:
|
|
18
|
+
if self._owns_client:
|
|
19
|
+
await self._client.aclose()
|
|
20
|
+
|
|
21
|
+
async def request(
|
|
22
|
+
self,
|
|
23
|
+
method: str,
|
|
24
|
+
path: str,
|
|
25
|
+
*,
|
|
26
|
+
query: dict[str, Any] | None = None,
|
|
27
|
+
body: Any = None,
|
|
28
|
+
idempotent: bool = False,
|
|
29
|
+
transform: Transform = None,
|
|
30
|
+
) -> Any:
|
|
31
|
+
config = self._config
|
|
32
|
+
url = config.url(path, query)
|
|
33
|
+
content = encode_body(body)
|
|
34
|
+
repeatable = _core.safe_to_repeat(method, idempotent)
|
|
35
|
+
attempt = 0
|
|
36
|
+
while True:
|
|
37
|
+
try:
|
|
38
|
+
response = await self._client.request(
|
|
39
|
+
method,
|
|
40
|
+
url,
|
|
41
|
+
content=content,
|
|
42
|
+
headers=config.headers(method, url, content),
|
|
43
|
+
timeout=config.timeout,
|
|
44
|
+
)
|
|
45
|
+
except httpx.HTTPError as error:
|
|
46
|
+
if repeatable and attempt < config.max_retries:
|
|
47
|
+
await _core.asleep(backoff(attempt))
|
|
48
|
+
attempt += 1
|
|
49
|
+
continue
|
|
50
|
+
raise _core.connection_error(error, config.timeout) from error
|
|
51
|
+
|
|
52
|
+
if response.is_success:
|
|
53
|
+
result = parse_body(response)
|
|
54
|
+
return transform(result) if transform else result
|
|
55
|
+
|
|
56
|
+
retry_after = retry_after_seconds(response.headers.get("retry-after"))
|
|
57
|
+
if not config.should_retry(attempt, response.status_code, repeatable):
|
|
58
|
+
raise to_error(response, retry_after)
|
|
59
|
+
await _core.asleep(retry_after if retry_after is not None else backoff(attempt))
|
|
60
|
+
attempt += 1
|
msgine/_core.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import hashlib
|
|
5
|
+
import hmac
|
|
6
|
+
import json
|
|
7
|
+
import random
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from email.utils import parsedate_to_datetime
|
|
12
|
+
from typing import Any
|
|
13
|
+
from urllib.parse import quote, urlencode, urlsplit
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from ._version import __version__
|
|
18
|
+
from .errors import MsGineConnectionError, MsGineError
|
|
19
|
+
|
|
20
|
+
DEFAULT_BASE_URL = "https://api.msgine.net/api/v1"
|
|
21
|
+
|
|
22
|
+
Transform = Callable[[Any], Any] | None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Page:
|
|
27
|
+
items: list[Any]
|
|
28
|
+
total: Any
|
|
29
|
+
page: Any
|
|
30
|
+
pages: Any
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def sleep(seconds: float) -> None:
|
|
34
|
+
time.sleep(seconds)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
async def asleep(seconds: float) -> None:
|
|
38
|
+
await asyncio.sleep(seconds)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def backoff(attempt: int) -> float:
|
|
42
|
+
return float(min(1.0 * 2**attempt, 8.0) + random.random() * 0.25)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def retry_after_seconds(header: str | None) -> float | None:
|
|
46
|
+
if not header:
|
|
47
|
+
return None
|
|
48
|
+
try:
|
|
49
|
+
return min(max(float(header), 1.0), 60.0)
|
|
50
|
+
except ValueError:
|
|
51
|
+
pass
|
|
52
|
+
try:
|
|
53
|
+
date = parsedate_to_datetime(header)
|
|
54
|
+
except (TypeError, ValueError):
|
|
55
|
+
return None
|
|
56
|
+
return min(max(date.timestamp() - time.time(), 1.0), 60.0)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def parse_body(response: httpx.Response) -> Any:
|
|
60
|
+
return response.json() if response.content else None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def to_error(response: httpx.Response, retry_after: float | None) -> MsGineError:
|
|
64
|
+
text = response.text
|
|
65
|
+
body: Any
|
|
66
|
+
try:
|
|
67
|
+
body = json.loads(text) if text else {}
|
|
68
|
+
except ValueError:
|
|
69
|
+
body = {"message": text}
|
|
70
|
+
if not isinstance(body, dict):
|
|
71
|
+
body = {"message": text}
|
|
72
|
+
message = body.get("message")
|
|
73
|
+
code = body.get("error")
|
|
74
|
+
details = body.get("details")
|
|
75
|
+
return MsGineError(
|
|
76
|
+
message if isinstance(message, str) and message else f"HTTP {response.status_code}",
|
|
77
|
+
status=response.status_code,
|
|
78
|
+
code=code if isinstance(code, str) else "http_error",
|
|
79
|
+
details=details if isinstance(details, list) else None,
|
|
80
|
+
retry_after=retry_after,
|
|
81
|
+
body=body,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def connection_error(error: httpx.HTTPError, timeout: float) -> MsGineConnectionError:
|
|
86
|
+
if isinstance(error, httpx.TimeoutException):
|
|
87
|
+
return MsGineConnectionError(f"Request timed out after {timeout} s", "timeout")
|
|
88
|
+
return MsGineConnectionError(f"Could not reach MsGine: {error}", "connection_error")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class Config:
|
|
92
|
+
def __init__(
|
|
93
|
+
self,
|
|
94
|
+
api_key: str,
|
|
95
|
+
signing_secret: str | None,
|
|
96
|
+
base_url: str,
|
|
97
|
+
timeout: float,
|
|
98
|
+
max_retries: int,
|
|
99
|
+
) -> None:
|
|
100
|
+
if not api_key:
|
|
101
|
+
raise ValueError("MsGine: api_key is required")
|
|
102
|
+
self.api_key = api_key
|
|
103
|
+
self.signing_secret = signing_secret
|
|
104
|
+
self.base_url = base_url.rstrip("/")
|
|
105
|
+
self.timeout = timeout
|
|
106
|
+
self.max_retries = max_retries
|
|
107
|
+
|
|
108
|
+
def url(self, path: str, query: dict[str, Any] | None) -> str:
|
|
109
|
+
pairs = [(key, _query_value(value)) for key, value in (query or {}).items() if value is not None]
|
|
110
|
+
return self.base_url + path + (f"?{urlencode(pairs)}" if pairs else "")
|
|
111
|
+
|
|
112
|
+
def headers(self, method: str, url: str, content: bytes | None) -> dict[str, str]:
|
|
113
|
+
headers = {
|
|
114
|
+
"accept": "application/json",
|
|
115
|
+
"user-agent": f"msgine-python/{__version__}",
|
|
116
|
+
"x-api-key": self.api_key,
|
|
117
|
+
}
|
|
118
|
+
if content is not None:
|
|
119
|
+
headers["content-type"] = "application/json"
|
|
120
|
+
if self.signing_secret:
|
|
121
|
+
parts = urlsplit(url)
|
|
122
|
+
target = parts.path + (f"?{parts.query}" if parts.query else "")
|
|
123
|
+
timestamp = str(int(time.time()))
|
|
124
|
+
body_hash = hashlib.sha256(content or b"").hexdigest()
|
|
125
|
+
message = f"{method}{target}{timestamp}{body_hash}"
|
|
126
|
+
headers["x-timestamp"] = timestamp
|
|
127
|
+
headers["x-signature"] = hmac.new(
|
|
128
|
+
self.signing_secret.encode(), message.encode(), hashlib.sha256
|
|
129
|
+
).hexdigest()
|
|
130
|
+
return headers
|
|
131
|
+
|
|
132
|
+
def should_retry(self, attempt: int, status: int, safe_to_repeat: bool) -> bool:
|
|
133
|
+
return attempt < self.max_retries and (
|
|
134
|
+
status == 429 or (safe_to_repeat and (status == 408 or status >= 500))
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _query_value(value: Any) -> str:
|
|
139
|
+
if isinstance(value, bool):
|
|
140
|
+
return "true" if value else "false"
|
|
141
|
+
return str(value)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def encode_body(body: Any) -> bytes | None:
|
|
145
|
+
if body is None:
|
|
146
|
+
return None
|
|
147
|
+
return json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def safe_to_repeat(method: str, idempotent: bool) -> bool:
|
|
151
|
+
return method not in ("POST", "PATCH") or idempotent
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def path_id(value: str) -> str:
|
|
155
|
+
return quote(value, safe="")
|
msgine/_sync.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
from . import _core
|
|
8
|
+
from ._core import Config, Transform, backoff, encode_body, parse_body, retry_after_seconds, to_error
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SyncTransport:
|
|
12
|
+
def __init__(self, config: Config, client: httpx.Client | None) -> None:
|
|
13
|
+
self._config = config
|
|
14
|
+
self._owns_client = client is None
|
|
15
|
+
self._client = client or httpx.Client()
|
|
16
|
+
|
|
17
|
+
def close(self) -> None:
|
|
18
|
+
if self._owns_client:
|
|
19
|
+
self._client.close()
|
|
20
|
+
|
|
21
|
+
def request(
|
|
22
|
+
self,
|
|
23
|
+
method: str,
|
|
24
|
+
path: str,
|
|
25
|
+
*,
|
|
26
|
+
query: dict[str, Any] | None = None,
|
|
27
|
+
body: Any = None,
|
|
28
|
+
idempotent: bool = False,
|
|
29
|
+
transform: Transform = None,
|
|
30
|
+
) -> Any:
|
|
31
|
+
config = self._config
|
|
32
|
+
url = config.url(path, query)
|
|
33
|
+
content = encode_body(body)
|
|
34
|
+
repeatable = _core.safe_to_repeat(method, idempotent)
|
|
35
|
+
attempt = 0
|
|
36
|
+
while True:
|
|
37
|
+
try:
|
|
38
|
+
response = self._client.request(
|
|
39
|
+
method,
|
|
40
|
+
url,
|
|
41
|
+
content=content,
|
|
42
|
+
headers=config.headers(method, url, content),
|
|
43
|
+
timeout=config.timeout,
|
|
44
|
+
)
|
|
45
|
+
except httpx.HTTPError as error:
|
|
46
|
+
if repeatable and attempt < config.max_retries:
|
|
47
|
+
_core.sleep(backoff(attempt))
|
|
48
|
+
attempt += 1
|
|
49
|
+
continue
|
|
50
|
+
raise _core.connection_error(error, config.timeout) from error
|
|
51
|
+
|
|
52
|
+
if response.is_success:
|
|
53
|
+
result = parse_body(response)
|
|
54
|
+
return transform(result) if transform else result
|
|
55
|
+
|
|
56
|
+
retry_after = retry_after_seconds(response.headers.get("retry-after"))
|
|
57
|
+
if not config.should_retry(attempt, response.status_code, repeatable):
|
|
58
|
+
raise to_error(response, retry_after)
|
|
59
|
+
_core.sleep(retry_after if retry_after is not None else backoff(attempt))
|
|
60
|
+
attempt += 1
|
msgine/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
msgine/client.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from types import TracebackType
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
from ._async import AsyncTransport
|
|
8
|
+
from ._core import DEFAULT_BASE_URL, Config
|
|
9
|
+
from ._sync import SyncTransport
|
|
10
|
+
from .resources import (
|
|
11
|
+
Analytics,
|
|
12
|
+
ContactFields,
|
|
13
|
+
Email,
|
|
14
|
+
Events,
|
|
15
|
+
Messages,
|
|
16
|
+
OptOuts,
|
|
17
|
+
Push,
|
|
18
|
+
Sms,
|
|
19
|
+
Transport,
|
|
20
|
+
Webhooks,
|
|
21
|
+
WhatsApp,
|
|
22
|
+
Workflows,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _Resources:
|
|
27
|
+
def __init__(self, http: Transport) -> None:
|
|
28
|
+
self.sms = Sms(http)
|
|
29
|
+
self.whatsapp = WhatsApp(http)
|
|
30
|
+
self.email = Email(http)
|
|
31
|
+
self.push = Push(http)
|
|
32
|
+
self.messages = Messages(http)
|
|
33
|
+
self.webhooks = Webhooks(http)
|
|
34
|
+
self.workflows = Workflows(http)
|
|
35
|
+
self.events = Events(http)
|
|
36
|
+
self.opt_outs = OptOuts(http)
|
|
37
|
+
self.contact_fields = ContactFields(http)
|
|
38
|
+
self.analytics = Analytics(http)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class MsGine(_Resources):
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
api_key: str,
|
|
45
|
+
*,
|
|
46
|
+
signing_secret: str | None = None,
|
|
47
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
48
|
+
timeout: float = 30.0,
|
|
49
|
+
max_retries: int = 2,
|
|
50
|
+
http_client: httpx.Client | None = None,
|
|
51
|
+
) -> None:
|
|
52
|
+
config = Config(api_key, signing_secret, base_url, timeout, max_retries)
|
|
53
|
+
self._transport = SyncTransport(config, http_client)
|
|
54
|
+
super().__init__(self._transport)
|
|
55
|
+
|
|
56
|
+
def close(self) -> None:
|
|
57
|
+
self._transport.close()
|
|
58
|
+
|
|
59
|
+
def __enter__(self) -> MsGine:
|
|
60
|
+
return self
|
|
61
|
+
|
|
62
|
+
def __exit__(
|
|
63
|
+
self,
|
|
64
|
+
exc_type: type[BaseException] | None,
|
|
65
|
+
exc: BaseException | None,
|
|
66
|
+
traceback: TracebackType | None,
|
|
67
|
+
) -> None:
|
|
68
|
+
self.close()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class AsyncMsGine(_Resources):
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
api_key: str,
|
|
75
|
+
*,
|
|
76
|
+
signing_secret: str | None = None,
|
|
77
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
78
|
+
timeout: float = 30.0,
|
|
79
|
+
max_retries: int = 2,
|
|
80
|
+
http_client: httpx.AsyncClient | None = None,
|
|
81
|
+
) -> None:
|
|
82
|
+
config = Config(api_key, signing_secret, base_url, timeout, max_retries)
|
|
83
|
+
self._transport = AsyncTransport(config, http_client)
|
|
84
|
+
super().__init__(self._transport)
|
|
85
|
+
|
|
86
|
+
async def aclose(self) -> None:
|
|
87
|
+
await self._transport.aclose()
|
|
88
|
+
|
|
89
|
+
async def __aenter__(self) -> AsyncMsGine:
|
|
90
|
+
return self
|
|
91
|
+
|
|
92
|
+
async def __aexit__(
|
|
93
|
+
self,
|
|
94
|
+
exc_type: type[BaseException] | None,
|
|
95
|
+
exc: BaseException | None,
|
|
96
|
+
traceback: TracebackType | None,
|
|
97
|
+
) -> None:
|
|
98
|
+
await self.aclose()
|
msgine/errors.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class MsGineError(Exception):
|
|
7
|
+
def __init__(
|
|
8
|
+
self,
|
|
9
|
+
message: str,
|
|
10
|
+
*,
|
|
11
|
+
status: int,
|
|
12
|
+
code: str,
|
|
13
|
+
details: list[dict[str, Any]] | None = None,
|
|
14
|
+
retry_after: float | None = None,
|
|
15
|
+
body: Any = None,
|
|
16
|
+
) -> None:
|
|
17
|
+
super().__init__(message)
|
|
18
|
+
self.message = message
|
|
19
|
+
self.status = status
|
|
20
|
+
self.code = code
|
|
21
|
+
self.details = details or []
|
|
22
|
+
self.retry_after = retry_after
|
|
23
|
+
self.body = body
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class MsGineConnectionError(MsGineError):
|
|
27
|
+
def __init__(self, message: str, code: str) -> None:
|
|
28
|
+
super().__init__(message, status=0, code=code)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class WebhookVerificationError(Exception):
|
|
32
|
+
pass
|
msgine/py.typed
ADDED
|
File without changes
|
msgine/resources.py
ADDED
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import uuid
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import Any, Protocol
|
|
6
|
+
|
|
7
|
+
from ._core import Page, Transform, path_id
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Transport(Protocol):
|
|
11
|
+
def request(
|
|
12
|
+
self,
|
|
13
|
+
method: str,
|
|
14
|
+
path: str,
|
|
15
|
+
*,
|
|
16
|
+
query: dict[str, Any] | None = None,
|
|
17
|
+
body: Any = None,
|
|
18
|
+
idempotent: bool = False,
|
|
19
|
+
transform: Transform = None,
|
|
20
|
+
) -> Any: ...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
Strings = list[str]
|
|
24
|
+
Recipients = str | Strings
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class _Unset:
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
UNSET = _Unset()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _join(value: Recipients | None) -> str | None:
|
|
35
|
+
return ",".join(value) if isinstance(value, list) else value
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _clean(fields: dict[str, Any]) -> dict[str, Any]:
|
|
39
|
+
return {key: value for key, value in fields.items() if value is not None}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _page(key: str) -> Callable[[Any], Page]:
|
|
43
|
+
def build(raw: dict[str, Any]) -> Page:
|
|
44
|
+
items = raw.get(key) or []
|
|
45
|
+
return Page(items=items, total=raw.get("total"), page=raw.get("page"), pages=raw.get("pages"))
|
|
46
|
+
|
|
47
|
+
return build
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _send(http: Transport, path: str, fields: dict[str, Any], idempotency_key: str | None) -> Any:
|
|
51
|
+
body = _clean(fields)
|
|
52
|
+
body["idempotencyKey"] = idempotency_key if idempotency_key is not None else str(uuid.uuid4())
|
|
53
|
+
return http.request("POST", path, body=body, idempotent=True)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _list(http: Transport, path: str, key: str, **query: Any) -> Any:
|
|
57
|
+
return http.request("GET", path, query=query, transform=_page(key))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Sms:
|
|
61
|
+
def __init__(self, http: Transport) -> None:
|
|
62
|
+
self._http = http
|
|
63
|
+
|
|
64
|
+
def send(
|
|
65
|
+
self,
|
|
66
|
+
*,
|
|
67
|
+
to: Recipients,
|
|
68
|
+
message: str,
|
|
69
|
+
from_: str | None = None,
|
|
70
|
+
scheduled_for: str | None = None,
|
|
71
|
+
idempotency_key: str | None = None,
|
|
72
|
+
) -> Any:
|
|
73
|
+
fields = {"to": _join(to), "message": message, "from": from_, "scheduledFor": scheduled_for}
|
|
74
|
+
return _send(self._http, "/developers/sms", fields, idempotency_key)
|
|
75
|
+
|
|
76
|
+
def list(self, *, page: int | None = None, limit: int | None = None) -> Any:
|
|
77
|
+
return _list(self._http, "/developers/sms/history", "messages", page=page, limit=limit)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class WhatsApp:
|
|
81
|
+
def __init__(self, http: Transport) -> None:
|
|
82
|
+
self._http = http
|
|
83
|
+
|
|
84
|
+
def send(
|
|
85
|
+
self,
|
|
86
|
+
*,
|
|
87
|
+
to: Recipients,
|
|
88
|
+
message: str | None = None,
|
|
89
|
+
from_: str | None = None,
|
|
90
|
+
message_type: str | None = None,
|
|
91
|
+
template_id: str | None = None,
|
|
92
|
+
template_language: str | None = None,
|
|
93
|
+
template_params: Strings | None = None,
|
|
94
|
+
media_url: str | None = None,
|
|
95
|
+
media_type: str | None = None,
|
|
96
|
+
scheduled_for: str | None = None,
|
|
97
|
+
idempotency_key: str | None = None,
|
|
98
|
+
) -> Any:
|
|
99
|
+
fields = {
|
|
100
|
+
"to": _join(to),
|
|
101
|
+
"message": message,
|
|
102
|
+
"from": from_,
|
|
103
|
+
"messageType": message_type,
|
|
104
|
+
"templateId": template_id,
|
|
105
|
+
"templateLanguage": template_language,
|
|
106
|
+
"templateParams": template_params,
|
|
107
|
+
"mediaUrl": media_url,
|
|
108
|
+
"mediaType": media_type,
|
|
109
|
+
"scheduledFor": scheduled_for,
|
|
110
|
+
}
|
|
111
|
+
return _send(self._http, "/developers/whatsapp", fields, idempotency_key)
|
|
112
|
+
|
|
113
|
+
def list(self, *, page: int | None = None, limit: int | None = None) -> Any:
|
|
114
|
+
return _list(self._http, "/developers/whatsapp/history", "messages", page=page, limit=limit)
|
|
115
|
+
|
|
116
|
+
def inbound(self, *, page: int | None = None, limit: int | None = None) -> Any:
|
|
117
|
+
return _list(self._http, "/developers/whatsapp/inbound", "data", page=page, limit=limit)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class Email:
|
|
121
|
+
def __init__(self, http: Transport) -> None:
|
|
122
|
+
self._http = http
|
|
123
|
+
|
|
124
|
+
def send(
|
|
125
|
+
self,
|
|
126
|
+
*,
|
|
127
|
+
from_: str,
|
|
128
|
+
to: Recipients,
|
|
129
|
+
subject: str,
|
|
130
|
+
text: str | None = None,
|
|
131
|
+
html: str | None = None,
|
|
132
|
+
cc: Recipients | None = None,
|
|
133
|
+
bcc: Recipients | None = None,
|
|
134
|
+
scheduled_for: str | None = None,
|
|
135
|
+
idempotency_key: str | None = None,
|
|
136
|
+
) -> Any:
|
|
137
|
+
fields = {
|
|
138
|
+
"from": from_,
|
|
139
|
+
"to": _join(to),
|
|
140
|
+
"subject": subject,
|
|
141
|
+
"text": text,
|
|
142
|
+
"html": html,
|
|
143
|
+
"cc": _join(cc),
|
|
144
|
+
"bcc": _join(bcc),
|
|
145
|
+
"scheduledFor": scheduled_for,
|
|
146
|
+
"messageType": "transactional",
|
|
147
|
+
}
|
|
148
|
+
return _send(self._http, "/developers/email", fields, idempotency_key)
|
|
149
|
+
|
|
150
|
+
def list(self, *, page: int | None = None, limit: int | None = None) -> Any:
|
|
151
|
+
return _list(self._http, "/developers/email/history", "emails", page=page, limit=limit)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class PushDevices:
|
|
155
|
+
def __init__(self, http: Transport) -> None:
|
|
156
|
+
self._http = http
|
|
157
|
+
|
|
158
|
+
def list(self) -> Any:
|
|
159
|
+
return self._http.request("GET", "/developers/push/devices")
|
|
160
|
+
|
|
161
|
+
def register(self, *, token: str, platform: str, external_user_id: str | None = None) -> Any:
|
|
162
|
+
body = _clean({"token": token, "platform": platform, "externalUserId": external_user_id})
|
|
163
|
+
return self._http.request("POST", "/developers/push/device", body=body, idempotent=True)
|
|
164
|
+
|
|
165
|
+
def remove(self, token: str) -> Any:
|
|
166
|
+
return self._http.request("DELETE", "/developers/push/device", body={"token": token})
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class PushConfig:
|
|
170
|
+
def __init__(self, http: Transport) -> None:
|
|
171
|
+
self._http = http
|
|
172
|
+
|
|
173
|
+
def get(self) -> Any:
|
|
174
|
+
return self._http.request("GET", "/developers/push/config")
|
|
175
|
+
|
|
176
|
+
def set(self, *, project_id: str, client_email: str, private_key: str) -> Any:
|
|
177
|
+
body = {"projectId": project_id, "clientEmail": client_email, "privateKey": private_key}
|
|
178
|
+
return self._http.request("PUT", "/developers/push/config", body=body)
|
|
179
|
+
|
|
180
|
+
def delete(self) -> Any:
|
|
181
|
+
return self._http.request("DELETE", "/developers/push/config")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class Push:
|
|
185
|
+
def __init__(self, http: Transport) -> None:
|
|
186
|
+
self._http = http
|
|
187
|
+
self.devices = PushDevices(http)
|
|
188
|
+
self.config = PushConfig(http)
|
|
189
|
+
|
|
190
|
+
def send(
|
|
191
|
+
self,
|
|
192
|
+
*,
|
|
193
|
+
title: str,
|
|
194
|
+
body: str,
|
|
195
|
+
external_user_ids: Strings | None = None,
|
|
196
|
+
topic: str | None = None,
|
|
197
|
+
type: str | None = None,
|
|
198
|
+
priority: str | None = None,
|
|
199
|
+
ttl: int | None = None,
|
|
200
|
+
data: dict[str, str] | None = None,
|
|
201
|
+
image_url: str | None = None,
|
|
202
|
+
collapse_key: str | None = None,
|
|
203
|
+
android: dict[str, Any] | None = None,
|
|
204
|
+
apns: dict[str, Any] | None = None,
|
|
205
|
+
webpush: dict[str, Any] | None = None,
|
|
206
|
+
scheduled_for: str | None = None,
|
|
207
|
+
idempotency_key: str | None = None,
|
|
208
|
+
) -> Any:
|
|
209
|
+
fields = {
|
|
210
|
+
"title": title,
|
|
211
|
+
"body": body,
|
|
212
|
+
"externalUserIds": external_user_ids,
|
|
213
|
+
"topic": topic,
|
|
214
|
+
"type": type,
|
|
215
|
+
"priority": priority,
|
|
216
|
+
"ttl": ttl,
|
|
217
|
+
"data": data,
|
|
218
|
+
"imageUrl": image_url,
|
|
219
|
+
"collapseKey": collapse_key,
|
|
220
|
+
"android": android,
|
|
221
|
+
"apns": apns,
|
|
222
|
+
"webpush": webpush,
|
|
223
|
+
"scheduledFor": scheduled_for,
|
|
224
|
+
}
|
|
225
|
+
return _send(self._http, "/developers/push", fields, idempotency_key)
|
|
226
|
+
|
|
227
|
+
def list(self, *, page: int | None = None, limit: int | None = None) -> Any:
|
|
228
|
+
return _list(self._http, "/developers/push/history", "notifications", page=page, limit=limit)
|
|
229
|
+
|
|
230
|
+
def confirm(self, notification_id: str, event: str) -> Any:
|
|
231
|
+
body = {"notificationId": notification_id, "event": event}
|
|
232
|
+
return self._http.request("POST", "/developers/push/delivery", body=body, idempotent=True)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class Messages:
|
|
236
|
+
def __init__(self, http: Transport) -> None:
|
|
237
|
+
self._http = http
|
|
238
|
+
|
|
239
|
+
def get(self, message_id: str) -> Any:
|
|
240
|
+
return self._http.request("GET", f"/developers/{path_id(message_id)}")
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
class Webhooks:
|
|
244
|
+
def __init__(self, http: Transport) -> None:
|
|
245
|
+
self._http = http
|
|
246
|
+
|
|
247
|
+
def create(self, *, url: str, events: Strings, description: str | None = None) -> Any:
|
|
248
|
+
body = _clean({"url": url, "events": events, "description": description})
|
|
249
|
+
return self._http.request("POST", "/developers/webhooks", body=body)
|
|
250
|
+
|
|
251
|
+
def list(self) -> Any:
|
|
252
|
+
return self._http.request("GET", "/developers/webhooks")
|
|
253
|
+
|
|
254
|
+
def get(self, webhook_id: str) -> Any:
|
|
255
|
+
return self._http.request("GET", f"/developers/webhooks/{path_id(webhook_id)}")
|
|
256
|
+
|
|
257
|
+
def update(
|
|
258
|
+
self,
|
|
259
|
+
webhook_id: str,
|
|
260
|
+
*,
|
|
261
|
+
url: str | None = None,
|
|
262
|
+
events: Strings | None = None,
|
|
263
|
+
is_active: bool | None = None,
|
|
264
|
+
description: str | None = None,
|
|
265
|
+
max_retries: int | None = None,
|
|
266
|
+
) -> Any:
|
|
267
|
+
body = _clean(
|
|
268
|
+
{
|
|
269
|
+
"url": url,
|
|
270
|
+
"events": events,
|
|
271
|
+
"isActive": is_active,
|
|
272
|
+
"description": description,
|
|
273
|
+
"maxRetries": max_retries,
|
|
274
|
+
}
|
|
275
|
+
)
|
|
276
|
+
return self._http.request("PATCH", f"/developers/webhooks/{path_id(webhook_id)}", body=body)
|
|
277
|
+
|
|
278
|
+
def delete(self, webhook_id: str) -> Any:
|
|
279
|
+
return self._http.request("DELETE", f"/developers/webhooks/{path_id(webhook_id)}")
|
|
280
|
+
|
|
281
|
+
def rotate_secret(self, webhook_id: str) -> Any:
|
|
282
|
+
return self._http.request("POST", f"/developers/webhooks/{path_id(webhook_id)}/rotate-secret")
|
|
283
|
+
|
|
284
|
+
def deliveries(self, webhook_id: str, *, limit: int | None = None) -> Any:
|
|
285
|
+
return self._http.request(
|
|
286
|
+
"GET", f"/developers/webhooks/{path_id(webhook_id)}/deliveries", query={"limit": limit}
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
def test(self, webhook_id: str) -> Any:
|
|
290
|
+
return self._http.request("POST", f"/developers/webhooks/{path_id(webhook_id)}/test")
|
|
291
|
+
|
|
292
|
+
def events(self) -> Any:
|
|
293
|
+
return self._http.request(
|
|
294
|
+
"GET", "/developers/webhooks/events", transform=lambda response: response["events"]
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
class WorkflowRuns:
|
|
299
|
+
def __init__(self, http: Transport) -> None:
|
|
300
|
+
self._http = http
|
|
301
|
+
|
|
302
|
+
def start(
|
|
303
|
+
self,
|
|
304
|
+
workflow_id: str,
|
|
305
|
+
*,
|
|
306
|
+
input: dict[str, Any] | None = None,
|
|
307
|
+
contact_id: str | None = None,
|
|
308
|
+
phone: str | None = None,
|
|
309
|
+
sandbox: bool | None = None,
|
|
310
|
+
idempotency_key: str | None = None,
|
|
311
|
+
) -> Any:
|
|
312
|
+
fields = {"input": input, "contactId": contact_id, "phone": phone, "sandbox": sandbox}
|
|
313
|
+
path = f"/developers/workflows/{path_id(workflow_id)}/runs"
|
|
314
|
+
return _send(self._http, path, fields, idempotency_key)
|
|
315
|
+
|
|
316
|
+
def list(
|
|
317
|
+
self,
|
|
318
|
+
workflow_id: str,
|
|
319
|
+
*,
|
|
320
|
+
page: int | None = None,
|
|
321
|
+
limit: int | None = None,
|
|
322
|
+
status: str | None = None,
|
|
323
|
+
) -> Any:
|
|
324
|
+
return _list(
|
|
325
|
+
self._http,
|
|
326
|
+
f"/developers/workflows/{path_id(workflow_id)}/runs",
|
|
327
|
+
"data",
|
|
328
|
+
page=page,
|
|
329
|
+
limit=limit,
|
|
330
|
+
status=status,
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
def get(self, run_id: str) -> Any:
|
|
334
|
+
return self._http.request("GET", f"/developers/workflows/runs/{path_id(run_id)}")
|
|
335
|
+
|
|
336
|
+
def cancel(self, run_id: str) -> Any:
|
|
337
|
+
return self._http.request("POST", f"/developers/workflows/runs/{path_id(run_id)}/cancel")
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
class WorkflowLaunches:
|
|
341
|
+
def __init__(self, http: Transport) -> None:
|
|
342
|
+
self._http = http
|
|
343
|
+
|
|
344
|
+
def create(self, workflow_id: str, *, at: str | None = None, sandbox: bool | None = None) -> Any:
|
|
345
|
+
body = _clean({"at": at, "sandbox": sandbox})
|
|
346
|
+
return self._http.request("POST", f"/developers/workflows/{path_id(workflow_id)}/launches", body=body)
|
|
347
|
+
|
|
348
|
+
def list(self, workflow_id: str) -> Any:
|
|
349
|
+
return self._http.request("GET", f"/developers/workflows/{path_id(workflow_id)}/launches")
|
|
350
|
+
|
|
351
|
+
def get(self, launch_id: str) -> Any:
|
|
352
|
+
return self._http.request("GET", f"/developers/workflows/launches/{path_id(launch_id)}")
|
|
353
|
+
|
|
354
|
+
def cancel(self, launch_id: str) -> Any:
|
|
355
|
+
return self._http.request("POST", f"/developers/workflows/launches/{path_id(launch_id)}/cancel")
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
class WorkflowHooks:
|
|
359
|
+
def __init__(self, http: Transport) -> None:
|
|
360
|
+
self._http = http
|
|
361
|
+
|
|
362
|
+
def get(self, workflow_id: str) -> Any:
|
|
363
|
+
return self._http.request("GET", f"/developers/workflows/{path_id(workflow_id)}/hook")
|
|
364
|
+
|
|
365
|
+
def create(self, workflow_id: str) -> Any:
|
|
366
|
+
return self._http.request("POST", f"/developers/workflows/{path_id(workflow_id)}/hook")
|
|
367
|
+
|
|
368
|
+
def delete(self, workflow_id: str) -> Any:
|
|
369
|
+
return self._http.request("DELETE", f"/developers/workflows/{path_id(workflow_id)}/hook")
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
class WorkflowSecrets:
|
|
373
|
+
def __init__(self, http: Transport) -> None:
|
|
374
|
+
self._http = http
|
|
375
|
+
|
|
376
|
+
def list(self) -> Any:
|
|
377
|
+
return self._http.request("GET", "/developers/workflows/secrets")
|
|
378
|
+
|
|
379
|
+
def set(self, name: str, value: str) -> Any:
|
|
380
|
+
path = f"/developers/workflows/secrets/{path_id(name)}"
|
|
381
|
+
return self._http.request("PUT", path, body={"value": value})
|
|
382
|
+
|
|
383
|
+
def delete(self, name: str) -> Any:
|
|
384
|
+
return self._http.request("DELETE", f"/developers/workflows/secrets/{path_id(name)}")
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
class MessagingPolicy:
|
|
388
|
+
def __init__(self, http: Transport) -> None:
|
|
389
|
+
self._http = http
|
|
390
|
+
|
|
391
|
+
def get(self) -> Any:
|
|
392
|
+
return self._http.request("GET", "/developers/workflows/messaging-policy")
|
|
393
|
+
|
|
394
|
+
def update(
|
|
395
|
+
self,
|
|
396
|
+
*,
|
|
397
|
+
timezone: str | None = None,
|
|
398
|
+
quiet_hours_start: str | None | _Unset = UNSET,
|
|
399
|
+
quiet_hours_end: str | None | _Unset = UNSET,
|
|
400
|
+
daily_marketing_cap_per_contact: int | None | _Unset = UNSET,
|
|
401
|
+
) -> Any:
|
|
402
|
+
fields: dict[str, Any] = {
|
|
403
|
+
"timezone": timezone,
|
|
404
|
+
"quietHoursStart": quiet_hours_start,
|
|
405
|
+
"quietHoursEnd": quiet_hours_end,
|
|
406
|
+
"dailyMarketingCapPerContact": daily_marketing_cap_per_contact,
|
|
407
|
+
}
|
|
408
|
+
body = {
|
|
409
|
+
key: value
|
|
410
|
+
for key, value in fields.items()
|
|
411
|
+
if not isinstance(value, _Unset) and (value is not None or key != "timezone")
|
|
412
|
+
}
|
|
413
|
+
return self._http.request("PUT", "/developers/workflows/messaging-policy", body=body)
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
class Workflows:
|
|
417
|
+
def __init__(self, http: Transport) -> None:
|
|
418
|
+
self._http = http
|
|
419
|
+
self.runs = WorkflowRuns(http)
|
|
420
|
+
self.launches = WorkflowLaunches(http)
|
|
421
|
+
self.hooks = WorkflowHooks(http)
|
|
422
|
+
self.secrets = WorkflowSecrets(http)
|
|
423
|
+
self.messaging_policy = MessagingPolicy(http)
|
|
424
|
+
|
|
425
|
+
def list(self, *, page: int | None = None, limit: int | None = None, status: str | None = None) -> Any:
|
|
426
|
+
return _list(self._http, "/developers/workflows", "data", page=page, limit=limit, status=status)
|
|
427
|
+
|
|
428
|
+
def create(
|
|
429
|
+
self, *, name: str, description: str | None = None, definition: dict[str, Any] | None = None
|
|
430
|
+
) -> Any:
|
|
431
|
+
body = _clean({"name": name, "description": description, "definition": definition})
|
|
432
|
+
return self._http.request("POST", "/developers/workflows", body=body)
|
|
433
|
+
|
|
434
|
+
def get(self, workflow_id: str) -> Any:
|
|
435
|
+
return self._http.request("GET", f"/developers/workflows/{path_id(workflow_id)}")
|
|
436
|
+
|
|
437
|
+
def update(
|
|
438
|
+
self,
|
|
439
|
+
workflow_id: str,
|
|
440
|
+
*,
|
|
441
|
+
name: str | None = None,
|
|
442
|
+
description: str | None = None,
|
|
443
|
+
definition: dict[str, Any] | None = None,
|
|
444
|
+
) -> Any:
|
|
445
|
+
body = _clean({"name": name, "description": description, "definition": definition})
|
|
446
|
+
return self._http.request("PATCH", f"/developers/workflows/{path_id(workflow_id)}", body=body)
|
|
447
|
+
|
|
448
|
+
def archive(self, workflow_id: str) -> Any:
|
|
449
|
+
return self._http.request("DELETE", f"/developers/workflows/{path_id(workflow_id)}")
|
|
450
|
+
|
|
451
|
+
def validate(self, workflow_id: str) -> Any:
|
|
452
|
+
return self._http.request(
|
|
453
|
+
"POST", f"/developers/workflows/{path_id(workflow_id)}/validate", idempotent=True
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
def publish(self, workflow_id: str) -> Any:
|
|
457
|
+
return self._http.request("POST", f"/developers/workflows/{path_id(workflow_id)}/publish")
|
|
458
|
+
|
|
459
|
+
def pause(self, workflow_id: str) -> Any:
|
|
460
|
+
return self._http.request("POST", f"/developers/workflows/{path_id(workflow_id)}/pause")
|
|
461
|
+
|
|
462
|
+
def resume(self, workflow_id: str) -> Any:
|
|
463
|
+
return self._http.request("POST", f"/developers/workflows/{path_id(workflow_id)}/resume")
|
|
464
|
+
|
|
465
|
+
def versions(self, workflow_id: str) -> Any:
|
|
466
|
+
return self._http.request("GET", f"/developers/workflows/{path_id(workflow_id)}/versions")
|
|
467
|
+
|
|
468
|
+
def node_types(self) -> Any:
|
|
469
|
+
return self._http.request("GET", "/developers/workflows/node-types")
|
|
470
|
+
|
|
471
|
+
def platform_events(self) -> Any:
|
|
472
|
+
return self._http.request("GET", "/developers/workflows/platform-events")
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
class Events:
|
|
476
|
+
def __init__(self, http: Transport) -> None:
|
|
477
|
+
self._http = http
|
|
478
|
+
|
|
479
|
+
def send(
|
|
480
|
+
self,
|
|
481
|
+
*,
|
|
482
|
+
name: str,
|
|
483
|
+
payload: dict[str, Any] | None = None,
|
|
484
|
+
contact_id: str | None = None,
|
|
485
|
+
phone: str | None = None,
|
|
486
|
+
idempotency_key: str | None = None,
|
|
487
|
+
) -> Any:
|
|
488
|
+
fields = {"name": name, "payload": payload, "contactId": contact_id, "phone": phone}
|
|
489
|
+
return _send(self._http, "/developers/events", fields, idempotency_key)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
class OptOuts:
|
|
493
|
+
def __init__(self, http: Transport) -> None:
|
|
494
|
+
self._http = http
|
|
495
|
+
|
|
496
|
+
def list(self, *, page: int | None = None, limit: int | None = None, channel: str | None = None) -> Any:
|
|
497
|
+
return _list(self._http, "/developers/opt-outs", "data", page=page, limit=limit, channel=channel)
|
|
498
|
+
|
|
499
|
+
def create(self, *, channel: str, address: str, reason: str | None = None) -> Any:
|
|
500
|
+
body = _clean({"channel": channel, "address": address, "reason": reason})
|
|
501
|
+
return self._http.request("POST", "/developers/opt-outs", body=body, idempotent=True)
|
|
502
|
+
|
|
503
|
+
def delete(self, opt_out_id: str) -> Any:
|
|
504
|
+
return self._http.request("DELETE", f"/developers/opt-outs/{path_id(opt_out_id)}")
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
class ContactFields:
|
|
508
|
+
def __init__(self, http: Transport) -> None:
|
|
509
|
+
self._http = http
|
|
510
|
+
|
|
511
|
+
def list(self) -> Any:
|
|
512
|
+
return self._http.request("GET", "/developers/contacts/fields")
|
|
513
|
+
|
|
514
|
+
def create(self, *, key: str, label: str, type: str, options: Strings | None = None) -> Any:
|
|
515
|
+
body = _clean({"key": key, "label": label, "type": type, "options": options})
|
|
516
|
+
return self._http.request("POST", "/developers/contacts/fields", body=body)
|
|
517
|
+
|
|
518
|
+
def update(self, field_id: str, *, label: str | None = None, options: Strings | None = None) -> Any:
|
|
519
|
+
body = _clean({"label": label, "options": options})
|
|
520
|
+
return self._http.request("PATCH", f"/developers/contacts/fields/{path_id(field_id)}", body=body)
|
|
521
|
+
|
|
522
|
+
def delete(self, field_id: str) -> Any:
|
|
523
|
+
return self._http.request("DELETE", f"/developers/contacts/fields/{path_id(field_id)}")
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
class Analytics:
|
|
527
|
+
def __init__(self, http: Transport) -> None:
|
|
528
|
+
self._http = http
|
|
529
|
+
|
|
530
|
+
def _range(self, name: str, from_: str | None, to: str | None) -> Any:
|
|
531
|
+
return self._http.request(
|
|
532
|
+
"GET", f"/developers/analytics/{name}", query={"from": from_, "to": to}
|
|
533
|
+
)
|
|
534
|
+
|
|
535
|
+
def summary(self, *, from_: str | None = None, to: str | None = None) -> Any:
|
|
536
|
+
return self._range("summary", from_, to)
|
|
537
|
+
|
|
538
|
+
def messaging(self, *, from_: str | None = None, to: str | None = None) -> Any:
|
|
539
|
+
return self._range("messaging", from_, to)
|
|
540
|
+
|
|
541
|
+
def engagement(self, *, from_: str | None = None, to: str | None = None) -> Any:
|
|
542
|
+
return self._range("engagement", from_, to)
|
|
543
|
+
|
|
544
|
+
def developer(self, *, from_: str | None = None, to: str | None = None) -> Any:
|
|
545
|
+
return self._range("developer", from_, to)
|
|
546
|
+
|
|
547
|
+
def overview(self, *, from_: str | None = None, to: str | None = None) -> Any:
|
|
548
|
+
return self._range("overview", from_, to)
|
|
549
|
+
|
|
550
|
+
def daily(self, *, days: int | None = None) -> Any:
|
|
551
|
+
return self._http.request("GET", "/developers/analytics/daily", query={"days": days})
|
msgine/webhooks.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import hmac
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .errors import WebhookVerificationError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def verify_webhook(
|
|
13
|
+
payload: bytes | str,
|
|
14
|
+
signature_header: str | None,
|
|
15
|
+
secret: str,
|
|
16
|
+
*,
|
|
17
|
+
tolerance: int = 300,
|
|
18
|
+
now: int | None = None,
|
|
19
|
+
) -> dict[str, Any]:
|
|
20
|
+
if not signature_header:
|
|
21
|
+
raise WebhookVerificationError("Missing X-MsGine-Signature header")
|
|
22
|
+
|
|
23
|
+
parts: dict[str, list[str]] = {}
|
|
24
|
+
for part in signature_header.split(","):
|
|
25
|
+
key, _, value = part.strip().partition("=")
|
|
26
|
+
if key and value:
|
|
27
|
+
parts.setdefault(key, []).append(value)
|
|
28
|
+
signatures = parts.get("v1", [])
|
|
29
|
+
try:
|
|
30
|
+
timestamp = int(parts.get("t", [""])[0])
|
|
31
|
+
except ValueError:
|
|
32
|
+
timestamp = None
|
|
33
|
+
if timestamp is None or not signatures:
|
|
34
|
+
raise WebhookVerificationError("Malformed X-MsGine-Signature header")
|
|
35
|
+
|
|
36
|
+
current = int(time.time()) if now is None else now
|
|
37
|
+
if abs(current - timestamp) > tolerance:
|
|
38
|
+
raise WebhookVerificationError("Webhook timestamp is outside the tolerance window")
|
|
39
|
+
|
|
40
|
+
body = payload if isinstance(payload, str) else bytes(payload).decode("utf-8")
|
|
41
|
+
expected = hmac.new(secret.encode(), f"{timestamp}.{body}".encode(), hashlib.sha256).hexdigest().encode()
|
|
42
|
+
if not any(hmac.compare_digest(signature.encode(), expected) for signature in signatures):
|
|
43
|
+
raise WebhookVerificationError("Webhook signature does not match")
|
|
44
|
+
|
|
45
|
+
event: dict[str, Any] = json.loads(body)
|
|
46
|
+
return event
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: msgine
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python client for the MsGine messaging API
|
|
5
|
+
Project-URL: Documentation, https://docs.msgine.net
|
|
6
|
+
Classifier: Programming Language :: Python :: 3
|
|
7
|
+
Classifier: Typing :: Typed
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Requires-Dist: httpx<1,>=0.27
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
12
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
13
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
14
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# msgine
|
|
18
|
+
|
|
19
|
+
Python client for the MsGine messaging API: SMS, WhatsApp, email, push, workflows and webhooks.
|
|
20
|
+
|
|
21
|
+
Documentation: https://docs.msgine.net
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
pip install msgine
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Requires Python 3.10 or newer. The only dependency is `httpx`.
|
|
30
|
+
|
|
31
|
+
## Quick start
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from msgine import MsGine
|
|
35
|
+
|
|
36
|
+
with MsGine("msg_<kid>_<secret>") as client:
|
|
37
|
+
message = client.sms.send(to="+256700000001", message="Your code is 4821")
|
|
38
|
+
print(message["id"], message["status"])
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Async:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import asyncio
|
|
45
|
+
from msgine import AsyncMsGine
|
|
46
|
+
|
|
47
|
+
async def main() -> None:
|
|
48
|
+
async with AsyncMsGine("msg_<kid>_<secret>") as client:
|
|
49
|
+
page = await client.sms.list(page=1, limit=20)
|
|
50
|
+
print(page.total, len(page.items))
|
|
51
|
+
|
|
52
|
+
asyncio.run(main())
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Both clients expose the same resources and methods. Parameters are keyword-only and snake_case
|
|
56
|
+
(`scheduled_for`, `idempotency_key`, `from_`); they are sent under their API names. Nested data such as
|
|
57
|
+
`payload`, `definition` or `android` is sent as given. Responses are plain dicts with the API's camelCase
|
|
58
|
+
keys. List calls return `Page(items, total, page, pages)`.
|
|
59
|
+
|
|
60
|
+
## Configuration
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
MsGine(
|
|
64
|
+
api_key,
|
|
65
|
+
signing_secret=None,
|
|
66
|
+
base_url="https://api.msgine.net/api/v1",
|
|
67
|
+
timeout=30.0,
|
|
68
|
+
max_retries=2,
|
|
69
|
+
http_client=None,
|
|
70
|
+
)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
`http_client` takes an `httpx.Client` (`httpx.AsyncClient` for `AsyncMsGine`) to share a connection pool or
|
|
74
|
+
set proxies. A client you pass in is not closed by `close()`.
|
|
75
|
+
|
|
76
|
+
## Sending
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
client.sms.send(to=["+256700000001", "+256700000002"], message="Hello", scheduled_for="2026-12-25T09:00:00Z")
|
|
80
|
+
|
|
81
|
+
client.whatsapp.send(to="+256700000001", template_id="order_update", template_language="en",
|
|
82
|
+
template_params=["A-1042"])
|
|
83
|
+
|
|
84
|
+
client.email.send(from_="hello@example.com", to="user@example.com", subject="Receipt", html="<p>Thanks</p>")
|
|
85
|
+
|
|
86
|
+
client.push.send(title="Order shipped", body="On its way", external_user_ids=["user-42"])
|
|
87
|
+
|
|
88
|
+
client.events.send(name="order.created", payload={"orderId": "A-1042"}, phone="+256700000001")
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Email is transactional only. Recipients may be a string or a list. Every send carries an idempotency key:
|
|
92
|
+
yours (`idempotency_key=`) or a generated one that is reused across retries.
|
|
93
|
+
|
|
94
|
+
Other resources: `messages`, `webhooks`, `workflows` (`runs`, `launches`, `hooks`, `secrets`,
|
|
95
|
+
`messaging_policy`), `opt_outs`, `contact_fields`, `analytics`, `push.devices`, `push.config`.
|
|
96
|
+
|
|
97
|
+
## Webhooks
|
|
98
|
+
|
|
99
|
+
Verify the raw request body, not re-serialised JSON.
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
103
|
+
from msgine import WebhookVerificationError, verify_webhook
|
|
104
|
+
|
|
105
|
+
app = FastAPI()
|
|
106
|
+
|
|
107
|
+
@app.post("/msgine")
|
|
108
|
+
async def receive(request: Request) -> dict[str, bool]:
|
|
109
|
+
try:
|
|
110
|
+
event = verify_webhook(
|
|
111
|
+
await request.body(),
|
|
112
|
+
request.headers.get("x-msgine-signature"),
|
|
113
|
+
"whsec_...",
|
|
114
|
+
)
|
|
115
|
+
except WebhookVerificationError:
|
|
116
|
+
raise HTTPException(status_code=400)
|
|
117
|
+
print(event["event"], event["data"])
|
|
118
|
+
return {"ok": True}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Signatures older than 300 seconds are refused; change it with `tolerance=`. Several `v1` signatures are
|
|
122
|
+
accepted, so a rotated secret can overlap.
|
|
123
|
+
|
|
124
|
+
## Errors and retries
|
|
125
|
+
|
|
126
|
+
API errors raise `MsGineError` with `status`, `code`, `message`, `details`, `retry_after` and `body`.
|
|
127
|
+
Network failures and timeouts raise `MsGineConnectionError` (`status` 0, `code` `connection_error` or
|
|
128
|
+
`timeout`).
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from msgine import MsGineError
|
|
132
|
+
|
|
133
|
+
try:
|
|
134
|
+
client.sms.send(to="x", message="Hi")
|
|
135
|
+
except MsGineError as error:
|
|
136
|
+
print(error.status, error.code, error.details)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Up to `max_retries` retries (default 2). A 429 is always retried. Network errors, 408 and 5xx are retried
|
|
140
|
+
only for requests that are safe to repeat: GET, PUT and DELETE, and sends, which carry an idempotency key.
|
|
141
|
+
The wait follows `Retry-After` (1 to 60 seconds) or backs off exponentially from 1 second.
|
|
142
|
+
|
|
143
|
+
## Sandbox keys
|
|
144
|
+
|
|
145
|
+
A key created with the sandbox environment validates and records requests but sends nothing and charges
|
|
146
|
+
nothing. Use one in tests and CI.
|
|
147
|
+
|
|
148
|
+
## Request signing
|
|
149
|
+
|
|
150
|
+
Pass `signing_secret` to sign every request with `x-timestamp` and `x-signature` headers (HMAC-SHA256 of
|
|
151
|
+
method, path and query, timestamp and body hash). A fresh signature is computed for each attempt.
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
client = MsGine("msg_<kid>_<secret>", signing_secret="sk_...")
|
|
155
|
+
```
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
msgine/__init__.py,sha256=xBpjhlIxRzFVKu6fiMp6Xhx6DkRK1VJuRD_0Kkq7jyE,397
|
|
2
|
+
msgine/_async.py,sha256=5Hyx5LxYe8OSJxB0ksdbEAaYtOXLhB0iSLG84vFB25A,2071
|
|
3
|
+
msgine/_core.py,sha256=0eYHvkruPZ00Zjx8d7UrVq4bHpSXCjedKWTOLSu2KvQ,4721
|
|
4
|
+
msgine/_sync.py,sha256=69a9r8JxHAI5LoO9X_QaS3i0rAXddyazbkfHChod-jo,2020
|
|
5
|
+
msgine/_version.py,sha256=J-j-u0itpEFT6irdmWmixQqYMadNl1X91TxUmoiLHMI,22
|
|
6
|
+
msgine/client.py,sha256=5IZH4rpmpPm0CxrSuxB_RL5Kb4UfZJ6sHDJulSz_ceA,2510
|
|
7
|
+
msgine/errors.py,sha256=ytfJJ14ZYth0zjOXcEheSPP-li5LetMNxpItXXyhll0,762
|
|
8
|
+
msgine/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
msgine/resources.py,sha256=Ly818sJefBJb-8ySFaK0ylxQy_M2L6ByvwmgFfYrd9I,19631
|
|
10
|
+
msgine/webhooks.py,sha256=0tD7u2HieK9r1jpC7tja3kWZzxe6dfXIz3hJlxgfMuc,1540
|
|
11
|
+
msgine-1.0.0.dist-info/METADATA,sha256=VM9WZx63zG6WMw4zc-zEFtUJxnVOWYwgTCrek8kLXu8,4871
|
|
12
|
+
msgine-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
13
|
+
msgine-1.0.0.dist-info/RECORD,,
|