lakshyapocketlab-hello 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.
- lakshyapocketlab_hello/__init__.py +29 -0
- lakshyapocketlab_hello/_client.py +174 -0
- lakshyapocketlab_hello/_core.py +206 -0
- lakshyapocketlab_hello/_resources_async.py +259 -0
- lakshyapocketlab_hello/_resources_sync.py +253 -0
- lakshyapocketlab_hello/_specs.py +254 -0
- lakshyapocketlab_hello/_version.py +1 -0
- lakshyapocketlab_hello/errors.py +125 -0
- lakshyapocketlab_hello/py.typed +0 -0
- lakshyapocketlab_hello/types.py +117 -0
- lakshyapocketlab_hello-0.1.0.dist-info/METADATA +241 -0
- lakshyapocketlab_hello-0.1.0.dist-info/RECORD +14 -0
- lakshyapocketlab_hello-0.1.0.dist-info/WHEEL +4 -0
- lakshyapocketlab_hello-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Official Python SDK for Hello, the WhatsApp Business API.
|
|
2
|
+
|
|
3
|
+
from lakshyapocketlab_hello import Hello
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from ._client import AsyncHello, Hello
|
|
7
|
+
from ._version import __version__
|
|
8
|
+
from .errors import (
|
|
9
|
+
APIConnectionError,
|
|
10
|
+
APIError,
|
|
11
|
+
APITimeoutError,
|
|
12
|
+
AuthenticationError,
|
|
13
|
+
HelloError,
|
|
14
|
+
NotFoundError,
|
|
15
|
+
RateLimitError,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"APIConnectionError",
|
|
20
|
+
"APIError",
|
|
21
|
+
"APITimeoutError",
|
|
22
|
+
"AsyncHello",
|
|
23
|
+
"AuthenticationError",
|
|
24
|
+
"Hello",
|
|
25
|
+
"HelloError",
|
|
26
|
+
"NotFoundError",
|
|
27
|
+
"RateLimitError",
|
|
28
|
+
"__version__",
|
|
29
|
+
]
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""The synchronous and asynchronous clients."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import time
|
|
7
|
+
from types import TracebackType
|
|
8
|
+
from typing import Any, Dict, Optional, Type, Union
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from . import _core
|
|
13
|
+
from . import _resources_async as ra
|
|
14
|
+
from . import _resources_sync as rs
|
|
15
|
+
from . import _specs as specs
|
|
16
|
+
from ._core import ClientConfig, Spec
|
|
17
|
+
from .errors import APIConnectionError, APITimeoutError, HelloError
|
|
18
|
+
|
|
19
|
+
Timeout = Union[float, httpx.Timeout]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def sleep(seconds: float) -> None:
|
|
23
|
+
"""Blocking sleep used between retries (patch in tests)."""
|
|
24
|
+
time.sleep(seconds)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
async def asleep(seconds: float) -> None:
|
|
28
|
+
"""Async sleep used between retries (patch in tests)."""
|
|
29
|
+
await asyncio.sleep(seconds)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _transport_error(exc: httpx.HTTPError, spec: Spec) -> HelloError:
|
|
33
|
+
target = f"{spec.method} {spec.path}"
|
|
34
|
+
if isinstance(exc, httpx.TimeoutException):
|
|
35
|
+
return APITimeoutError(f"Request timed out: {target}")
|
|
36
|
+
return APIConnectionError(f"Connection error: {target}: {exc}")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Hello:
|
|
40
|
+
"""Synchronous client for the Hello WhatsApp Business API.
|
|
41
|
+
|
|
42
|
+
>>> from lakshyapocketlab_hello import Hello
|
|
43
|
+
>>> client = Hello() # reads HELLO_API_KEY
|
|
44
|
+
>>> client.ping()
|
|
45
|
+
{'status': 'ok', 'test_mode': False}
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
api_key: Optional[str] = None,
|
|
51
|
+
base_url: Optional[str] = None,
|
|
52
|
+
timeout: Timeout = 30,
|
|
53
|
+
max_retries: int = 2,
|
|
54
|
+
http_client: Optional[httpx.Client] = None,
|
|
55
|
+
) -> None:
|
|
56
|
+
self._config = ClientConfig(api_key, base_url, timeout, max_retries)
|
|
57
|
+
self._owns_client = http_client is None
|
|
58
|
+
self._http = http_client or httpx.Client()
|
|
59
|
+
self.phone_numbers = rs.PhoneNumbers(self)
|
|
60
|
+
self.messages = rs.Messages(self)
|
|
61
|
+
self.media = rs.Media(self)
|
|
62
|
+
self.templates = rs.Templates(self)
|
|
63
|
+
self.webhook_override = rs.WebhookOverride(self)
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def base_url(self) -> str:
|
|
67
|
+
return self._config.base_url
|
|
68
|
+
|
|
69
|
+
def ping(self) -> Dict[str, Any]:
|
|
70
|
+
"""Check that the API key works (``GET /v1/ping``)."""
|
|
71
|
+
result: Dict[str, Any] = self._request(specs.ping())
|
|
72
|
+
return result
|
|
73
|
+
|
|
74
|
+
def close(self) -> None:
|
|
75
|
+
"""Close the HTTP client if this instance created it."""
|
|
76
|
+
if self._owns_client:
|
|
77
|
+
self._http.close()
|
|
78
|
+
|
|
79
|
+
def __enter__(self) -> Hello:
|
|
80
|
+
return self
|
|
81
|
+
|
|
82
|
+
def __exit__(
|
|
83
|
+
self,
|
|
84
|
+
exc_type: Optional[Type[BaseException]],
|
|
85
|
+
exc: Optional[BaseException],
|
|
86
|
+
tb: Optional[TracebackType],
|
|
87
|
+
) -> None:
|
|
88
|
+
self.close()
|
|
89
|
+
|
|
90
|
+
def _request(self, spec: Spec) -> Any:
|
|
91
|
+
cfg = self._config
|
|
92
|
+
attempt = 0
|
|
93
|
+
while True:
|
|
94
|
+
error: HelloError
|
|
95
|
+
try:
|
|
96
|
+
response = self._http.request(**cfg.request_kwargs(spec))
|
|
97
|
+
except httpx.HTTPError as exc:
|
|
98
|
+
error = _transport_error(exc, spec)
|
|
99
|
+
error.__cause__ = exc
|
|
100
|
+
else:
|
|
101
|
+
if response.status_code < 400:
|
|
102
|
+
return _core.decode_success(response, spec)
|
|
103
|
+
error = _core.build_api_error(response)
|
|
104
|
+
delay = _core.retry_delay(spec, attempt, cfg.max_retries, error)
|
|
105
|
+
if delay is None:
|
|
106
|
+
raise error
|
|
107
|
+
sleep(delay)
|
|
108
|
+
attempt += 1
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class AsyncHello:
|
|
112
|
+
"""Asynchronous client; same surface as :class:`Hello` with ``await``."""
|
|
113
|
+
|
|
114
|
+
def __init__(
|
|
115
|
+
self,
|
|
116
|
+
api_key: Optional[str] = None,
|
|
117
|
+
base_url: Optional[str] = None,
|
|
118
|
+
timeout: Timeout = 30,
|
|
119
|
+
max_retries: int = 2,
|
|
120
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
121
|
+
) -> None:
|
|
122
|
+
self._config = ClientConfig(api_key, base_url, timeout, max_retries)
|
|
123
|
+
self._owns_client = http_client is None
|
|
124
|
+
self._http = http_client or httpx.AsyncClient()
|
|
125
|
+
self.phone_numbers = ra.PhoneNumbers(self)
|
|
126
|
+
self.messages = ra.Messages(self)
|
|
127
|
+
self.media = ra.Media(self)
|
|
128
|
+
self.templates = ra.Templates(self)
|
|
129
|
+
self.webhook_override = ra.WebhookOverride(self)
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def base_url(self) -> str:
|
|
133
|
+
return self._config.base_url
|
|
134
|
+
|
|
135
|
+
async def ping(self) -> Dict[str, Any]:
|
|
136
|
+
"""Check that the API key works (``GET /v1/ping``)."""
|
|
137
|
+
result: Dict[str, Any] = await self._request(specs.ping())
|
|
138
|
+
return result
|
|
139
|
+
|
|
140
|
+
async def aclose(self) -> None:
|
|
141
|
+
"""Close the HTTP client if this instance created it."""
|
|
142
|
+
if self._owns_client:
|
|
143
|
+
await self._http.aclose()
|
|
144
|
+
|
|
145
|
+
async def __aenter__(self) -> AsyncHello:
|
|
146
|
+
return self
|
|
147
|
+
|
|
148
|
+
async def __aexit__(
|
|
149
|
+
self,
|
|
150
|
+
exc_type: Optional[Type[BaseException]],
|
|
151
|
+
exc: Optional[BaseException],
|
|
152
|
+
tb: Optional[TracebackType],
|
|
153
|
+
) -> None:
|
|
154
|
+
await self.aclose()
|
|
155
|
+
|
|
156
|
+
async def _request(self, spec: Spec) -> Any:
|
|
157
|
+
cfg = self._config
|
|
158
|
+
attempt = 0
|
|
159
|
+
while True:
|
|
160
|
+
error: HelloError
|
|
161
|
+
try:
|
|
162
|
+
response = await self._http.request(**cfg.request_kwargs(spec))
|
|
163
|
+
except httpx.HTTPError as exc:
|
|
164
|
+
error = _transport_error(exc, spec)
|
|
165
|
+
error.__cause__ = exc
|
|
166
|
+
else:
|
|
167
|
+
if response.status_code < 400:
|
|
168
|
+
return _core.decode_success(response, spec)
|
|
169
|
+
error = _core.build_api_error(response)
|
|
170
|
+
delay = _core.retry_delay(spec, attempt, cfg.max_retries, error)
|
|
171
|
+
if delay is None:
|
|
172
|
+
raise error
|
|
173
|
+
await asleep(delay)
|
|
174
|
+
attempt += 1
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""Transport-independent logic shared by the sync and async clients."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import email.utils
|
|
6
|
+
import json
|
|
7
|
+
import mimetypes
|
|
8
|
+
import os
|
|
9
|
+
import random
|
|
10
|
+
import time
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Any, Dict, Optional, Tuple
|
|
14
|
+
from urllib.parse import quote
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
|
|
18
|
+
from . import errors
|
|
19
|
+
from ._version import __version__
|
|
20
|
+
from .types import FileInput
|
|
21
|
+
|
|
22
|
+
DEFAULT_BASE_URL = "https://api.lakshyapocketlab.com"
|
|
23
|
+
ENV_API_KEY = "HELLO_API_KEY"
|
|
24
|
+
USER_AGENT = f"lakshyapocketlab-hello-python/{__version__}"
|
|
25
|
+
IDEMPOTENCY_HEADER = "Idempotency-Key"
|
|
26
|
+
|
|
27
|
+
RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
|
|
28
|
+
BACKOFF_BASE = 0.5
|
|
29
|
+
BACKOFF_MAX = 8.0
|
|
30
|
+
#: A server asking us to wait longer than this is not retried; the error is raised instead.
|
|
31
|
+
MAX_RETRY_AFTER = 60.0
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class Spec:
|
|
36
|
+
"""A fully described API call, independent of sync/async transport."""
|
|
37
|
+
|
|
38
|
+
method: str
|
|
39
|
+
path: str
|
|
40
|
+
params: Dict[str, Any] = field(default_factory=dict)
|
|
41
|
+
json_body: Optional[Any] = None
|
|
42
|
+
headers: Dict[str, str] = field(default_factory=dict)
|
|
43
|
+
form: Optional[Dict[str, str]] = None
|
|
44
|
+
file: Optional[Tuple[str, bytes, str]] = None
|
|
45
|
+
#: Safe to repeat (GET/PUT/DELETE and idempotent POSTs, or a send with an idempotency key).
|
|
46
|
+
idempotent: bool = False
|
|
47
|
+
expect_bytes: bool = False
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def segment(name: str, value: str) -> str:
|
|
51
|
+
"""URL-quote one path segment, refusing empty values that would hit a different route."""
|
|
52
|
+
text = str(value)
|
|
53
|
+
if not text:
|
|
54
|
+
raise ValueError(f"{name} must not be empty")
|
|
55
|
+
return quote(text, safe="")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def clean_params(params: Mapping[str, Any]) -> Dict[str, Any]:
|
|
59
|
+
"""Drop ``None`` values and render booleans the way the API expects."""
|
|
60
|
+
out: Dict[str, Any] = {}
|
|
61
|
+
for key, value in params.items():
|
|
62
|
+
if value is None:
|
|
63
|
+
continue
|
|
64
|
+
out[key] = "true" if value is True else "false" if value is False else value
|
|
65
|
+
return out
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def resolve_api_key(api_key: Optional[str]) -> str:
|
|
69
|
+
key = api_key if api_key is not None else os.environ.get(ENV_API_KEY)
|
|
70
|
+
if not key:
|
|
71
|
+
raise errors.HelloError(
|
|
72
|
+
f"No API key provided. Pass api_key=... or set the {ENV_API_KEY} environment variable."
|
|
73
|
+
)
|
|
74
|
+
return key
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def read_file(file: FileInput, mime_type: str, filename: Optional[str]) -> Tuple[str, bytes, str]:
|
|
78
|
+
"""Return ``(filename, content, mime_type)`` for an upload."""
|
|
79
|
+
if isinstance(file, (bytes, bytearray)):
|
|
80
|
+
data = bytes(file)
|
|
81
|
+
guessed: Optional[str] = None
|
|
82
|
+
elif isinstance(file, (str, os.PathLike)):
|
|
83
|
+
path = os.fspath(file)
|
|
84
|
+
with open(path, "rb") as fh:
|
|
85
|
+
data = fh.read()
|
|
86
|
+
guessed = os.path.basename(path)
|
|
87
|
+
else:
|
|
88
|
+
data = file.read()
|
|
89
|
+
name = getattr(file, "name", None)
|
|
90
|
+
guessed = os.path.basename(name) if isinstance(name, str) else None
|
|
91
|
+
if filename is None:
|
|
92
|
+
filename = guessed or "file" + (mimetypes.guess_extension(mime_type) or "")
|
|
93
|
+
return filename, data, mime_type
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def backoff_delay(attempt: int) -> float:
|
|
97
|
+
"""Exponential backoff with jitter: 0.5s, 1s, 2s ... capped at 8s, scaled by 0.5-1.0."""
|
|
98
|
+
return min(BACKOFF_BASE * float(2**attempt), BACKOFF_MAX) * random.uniform(0.5, 1.0)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def parse_retry_after(value: Optional[str]) -> Optional[float]:
|
|
102
|
+
"""Seconds from a ``Retry-After`` header (delta-seconds or HTTP-date)."""
|
|
103
|
+
if not value:
|
|
104
|
+
return None
|
|
105
|
+
value = value.strip()
|
|
106
|
+
try:
|
|
107
|
+
return max(float(value), 0.0)
|
|
108
|
+
except ValueError:
|
|
109
|
+
pass
|
|
110
|
+
try:
|
|
111
|
+
when = email.utils.parsedate_to_datetime(value)
|
|
112
|
+
except (TypeError, ValueError):
|
|
113
|
+
return None
|
|
114
|
+
return max(float(when.timestamp() - time.time()), 0.0)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def retry_delay(
|
|
118
|
+
spec: Spec, attempt: int, max_retries: int, error: errors.HelloError
|
|
119
|
+
) -> Optional[float]:
|
|
120
|
+
"""Seconds to wait before retrying, or ``None`` when the error must be raised."""
|
|
121
|
+
if not spec.idempotent or attempt >= max_retries:
|
|
122
|
+
return None
|
|
123
|
+
if isinstance(error, errors.APIError):
|
|
124
|
+
if error.status not in RETRY_STATUSES:
|
|
125
|
+
return None
|
|
126
|
+
if error.retry_after is not None:
|
|
127
|
+
return error.retry_after if error.retry_after <= MAX_RETRY_AFTER else None
|
|
128
|
+
return backoff_delay(attempt)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def build_api_error(response: httpx.Response) -> errors.APIError:
|
|
132
|
+
try:
|
|
133
|
+
body: Any = response.json()
|
|
134
|
+
except ValueError:
|
|
135
|
+
body = response.text or None
|
|
136
|
+
parsed = errors.parse_error_body(body, response.reason_phrase or f"HTTP {response.status_code}")
|
|
137
|
+
cls = errors.error_class(response.status_code, parsed["hello_code"])
|
|
138
|
+
return cls(
|
|
139
|
+
parsed["message"],
|
|
140
|
+
status=response.status_code,
|
|
141
|
+
code=parsed["code"],
|
|
142
|
+
subcode=parsed["subcode"],
|
|
143
|
+
hello_code=parsed["hello_code"],
|
|
144
|
+
fbtrace_id=parsed["fbtrace_id"],
|
|
145
|
+
details=parsed["details"],
|
|
146
|
+
body=body,
|
|
147
|
+
retry_after=parse_retry_after(response.headers.get("Retry-After")),
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def decode_success(response: httpx.Response, spec: Spec) -> Any:
|
|
152
|
+
if spec.expect_bytes:
|
|
153
|
+
return response.content
|
|
154
|
+
if not response.content:
|
|
155
|
+
return {}
|
|
156
|
+
try:
|
|
157
|
+
return response.json()
|
|
158
|
+
except json.JSONDecodeError as exc:
|
|
159
|
+
raise errors.HelloError(
|
|
160
|
+
f"Invalid JSON in {response.status_code} response from {spec.method} {spec.path}"
|
|
161
|
+
) from exc
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class ClientConfig:
|
|
165
|
+
"""Resolved client options plus request building shared by both clients."""
|
|
166
|
+
|
|
167
|
+
def __init__(
|
|
168
|
+
self,
|
|
169
|
+
api_key: Optional[str],
|
|
170
|
+
base_url: Optional[str],
|
|
171
|
+
timeout: Any,
|
|
172
|
+
max_retries: int,
|
|
173
|
+
) -> None:
|
|
174
|
+
if max_retries < 0:
|
|
175
|
+
raise ValueError("max_retries must be >= 0")
|
|
176
|
+
self.api_key = resolve_api_key(api_key)
|
|
177
|
+
self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
|
|
178
|
+
self.timeout = timeout
|
|
179
|
+
self.max_retries = max_retries
|
|
180
|
+
|
|
181
|
+
def request_kwargs(self, spec: Spec) -> Dict[str, Any]:
|
|
182
|
+
headers = {
|
|
183
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
184
|
+
"User-Agent": USER_AGENT,
|
|
185
|
+
"Accept": "application/octet-stream" if spec.expect_bytes else "application/json",
|
|
186
|
+
**spec.headers,
|
|
187
|
+
}
|
|
188
|
+
kwargs: Dict[str, Any] = {
|
|
189
|
+
"method": spec.method,
|
|
190
|
+
"url": self.base_url + spec.path,
|
|
191
|
+
"headers": headers,
|
|
192
|
+
"timeout": self.timeout,
|
|
193
|
+
}
|
|
194
|
+
params = clean_params(spec.params)
|
|
195
|
+
if params:
|
|
196
|
+
kwargs["params"] = params
|
|
197
|
+
if spec.json_body is not None:
|
|
198
|
+
kwargs["json"] = spec.json_body
|
|
199
|
+
if spec.file is not None:
|
|
200
|
+
kwargs["data"] = spec.form or {}
|
|
201
|
+
kwargs["files"] = {"file": spec.file}
|
|
202
|
+
return kwargs
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def send_headers(idempotency_key: Optional[str]) -> Dict[str, str]:
|
|
206
|
+
return {IDEMPOTENCY_HEADER: idempotency_key} if idempotency_key else {}
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""Async resources, mirroring ``_resources_sync.py`` method for method."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional
|
|
7
|
+
|
|
8
|
+
from . import _specs as specs
|
|
9
|
+
from .types import FileInput, MediaType, MessageBody, TemplateDefinition
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from ._client import AsyncHello
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class _Resource:
|
|
16
|
+
def __init__(self, client: AsyncHello) -> None:
|
|
17
|
+
self._c = client
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PhoneNumbers(_Resource):
|
|
21
|
+
async def list(self) -> Dict[str, Any]:
|
|
22
|
+
"""List the organization's sending numbers (``GET /v1/phone_numbers``)."""
|
|
23
|
+
result: Dict[str, Any] = await self._c._request(specs.phone_numbers_list())
|
|
24
|
+
return result
|
|
25
|
+
|
|
26
|
+
async def list_for_waba(self, waba_id: str) -> Dict[str, Any]:
|
|
27
|
+
"""List the numbers of one WhatsApp Business Account."""
|
|
28
|
+
result: Dict[str, Any] = await self._c._request(specs.phone_numbers_list_for_waba(waba_id))
|
|
29
|
+
return result
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Messages(_Resource):
|
|
33
|
+
async def send(
|
|
34
|
+
self,
|
|
35
|
+
phone_number_id: str,
|
|
36
|
+
message: MessageBody,
|
|
37
|
+
*,
|
|
38
|
+
sync: bool = False,
|
|
39
|
+
async_: bool = False,
|
|
40
|
+
idempotency_key: Optional[str] = None,
|
|
41
|
+
) -> Dict[str, Any]:
|
|
42
|
+
"""Send any WhatsApp Cloud API message body.
|
|
43
|
+
|
|
44
|
+
``sync=True`` waits up to 25 s for WhatsApp to accept the message; ``async_=True``
|
|
45
|
+
returns at once (queued). Without either, the API key's default applies. Pass an
|
|
46
|
+
``idempotency_key`` to make the call safely retryable (the SDK then retries on
|
|
47
|
+
429/5xx/network errors).
|
|
48
|
+
"""
|
|
49
|
+
spec = specs.messages_send(phone_number_id, message, sync, async_, idempotency_key)
|
|
50
|
+
result: Dict[str, Any] = await self._c._request(spec)
|
|
51
|
+
return result
|
|
52
|
+
|
|
53
|
+
async def send_text(
|
|
54
|
+
self,
|
|
55
|
+
phone_number_id: str,
|
|
56
|
+
to: str,
|
|
57
|
+
body: str,
|
|
58
|
+
*,
|
|
59
|
+
preview_url: bool = False,
|
|
60
|
+
reply_to: Optional[str] = None,
|
|
61
|
+
sync: bool = False,
|
|
62
|
+
async_: bool = False,
|
|
63
|
+
idempotency_key: Optional[str] = None,
|
|
64
|
+
) -> Dict[str, Any]:
|
|
65
|
+
"""Send a text message (needs an open 24-hour window)."""
|
|
66
|
+
message = specs.text_body(to, body, preview_url, reply_to)
|
|
67
|
+
return await self.send(
|
|
68
|
+
phone_number_id, message, sync=sync, async_=async_, idempotency_key=idempotency_key
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
async def send_template(
|
|
72
|
+
self,
|
|
73
|
+
phone_number_id: str,
|
|
74
|
+
to: str,
|
|
75
|
+
name: str,
|
|
76
|
+
language: str = "en_US",
|
|
77
|
+
components: Optional[List[Mapping[str, Any]]] = None,
|
|
78
|
+
*,
|
|
79
|
+
reply_to: Optional[str] = None,
|
|
80
|
+
sync: bool = False,
|
|
81
|
+
async_: bool = False,
|
|
82
|
+
idempotency_key: Optional[str] = None,
|
|
83
|
+
) -> Dict[str, Any]:
|
|
84
|
+
"""Send an approved template."""
|
|
85
|
+
message = specs.template_body(to, name, language, components, reply_to)
|
|
86
|
+
return await self.send(
|
|
87
|
+
phone_number_id, message, sync=sync, async_=async_, idempotency_key=idempotency_key
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
async def send_media(
|
|
91
|
+
self,
|
|
92
|
+
phone_number_id: str,
|
|
93
|
+
to: str,
|
|
94
|
+
media_type: MediaType,
|
|
95
|
+
*,
|
|
96
|
+
media_id: Optional[str] = None,
|
|
97
|
+
link: Optional[str] = None,
|
|
98
|
+
caption: Optional[str] = None,
|
|
99
|
+
filename: Optional[str] = None,
|
|
100
|
+
reply_to: Optional[str] = None,
|
|
101
|
+
sync: bool = False,
|
|
102
|
+
async_: bool = False,
|
|
103
|
+
idempotency_key: Optional[str] = None,
|
|
104
|
+
) -> Dict[str, Any]:
|
|
105
|
+
"""Send an image, video, audio, document or sticker by ``media_id`` or public ``link``."""
|
|
106
|
+
message = specs.media_body(to, media_type, media_id, link, caption, filename, reply_to)
|
|
107
|
+
return await self.send(
|
|
108
|
+
phone_number_id, message, sync=sync, async_=async_, idempotency_key=idempotency_key
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
async def mark_as_read(
|
|
112
|
+
self, phone_number_id: str, message_id: str, *, typing_indicator: bool = False
|
|
113
|
+
) -> Dict[str, Any]:
|
|
114
|
+
"""Mark a received message (its ``wamid``) as read."""
|
|
115
|
+
result: Dict[str, Any] = await self._c._request(
|
|
116
|
+
specs.mark_as_read(phone_number_id, message_id, typing_indicator)
|
|
117
|
+
)
|
|
118
|
+
return result
|
|
119
|
+
|
|
120
|
+
async def get(self, message_id: str) -> Dict[str, Any]:
|
|
121
|
+
"""Get a sent message's status by ``hello_id`` or ``wamid`` (``GET /v1/messages/{id}``)."""
|
|
122
|
+
result: Dict[str, Any] = await self._c._request(specs.messages_get(message_id))
|
|
123
|
+
return result
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class Media(_Resource):
|
|
127
|
+
async def upload(
|
|
128
|
+
self,
|
|
129
|
+
phone_number_id: str,
|
|
130
|
+
file: FileInput,
|
|
131
|
+
mime_type: str,
|
|
132
|
+
filename: Optional[str] = None,
|
|
133
|
+
) -> Dict[str, Any]:
|
|
134
|
+
"""Upload bytes, a file path or a binary file object. Returns ``{"id": "<media_id>"}``."""
|
|
135
|
+
result: Dict[str, Any] = await self._c._request(
|
|
136
|
+
specs.media_upload(phone_number_id, file, mime_type, filename)
|
|
137
|
+
)
|
|
138
|
+
return result
|
|
139
|
+
|
|
140
|
+
async def get(self, media_id: str) -> Dict[str, Any]:
|
|
141
|
+
"""Look up a media object (``url``, ``mime_type``, ``file_size``, ...)."""
|
|
142
|
+
result: Dict[str, Any] = await self._c._request(specs.media_get(media_id))
|
|
143
|
+
return result
|
|
144
|
+
|
|
145
|
+
async def download(self, media_id: str) -> bytes:
|
|
146
|
+
"""Download the media file's bytes."""
|
|
147
|
+
result: bytes = await self._c._request(specs.media_download(media_id))
|
|
148
|
+
return result
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class Templates(_Resource):
|
|
152
|
+
async def list(
|
|
153
|
+
self,
|
|
154
|
+
waba_id: str,
|
|
155
|
+
*,
|
|
156
|
+
name: Optional[str] = None,
|
|
157
|
+
search: Optional[str] = None,
|
|
158
|
+
status: Optional[str] = None,
|
|
159
|
+
category: Optional[str] = None,
|
|
160
|
+
language: Optional[str] = None,
|
|
161
|
+
limit: Optional[int] = None,
|
|
162
|
+
after: Optional[str] = None,
|
|
163
|
+
before: Optional[str] = None,
|
|
164
|
+
summary: Optional[str] = None,
|
|
165
|
+
sort_by: Optional[str] = None,
|
|
166
|
+
sort_order: Optional[str] = None,
|
|
167
|
+
) -> Dict[str, Any]:
|
|
168
|
+
"""List a WABA's templates, newest first. Page with ``paging.cursors.after``."""
|
|
169
|
+
spec = specs.templates_list(
|
|
170
|
+
waba_id,
|
|
171
|
+
name=name,
|
|
172
|
+
search=search,
|
|
173
|
+
status=status,
|
|
174
|
+
category=category,
|
|
175
|
+
language=language,
|
|
176
|
+
limit=limit,
|
|
177
|
+
after=after,
|
|
178
|
+
before=before,
|
|
179
|
+
summary=summary,
|
|
180
|
+
sort_by=sort_by,
|
|
181
|
+
sort_order=sort_order,
|
|
182
|
+
)
|
|
183
|
+
result: Dict[str, Any] = await self._c._request(spec)
|
|
184
|
+
return result
|
|
185
|
+
|
|
186
|
+
async def get(self, template_id: str) -> Dict[str, Any]:
|
|
187
|
+
"""Get one template."""
|
|
188
|
+
result: Dict[str, Any] = await self._c._request(specs.templates_get(template_id))
|
|
189
|
+
return result
|
|
190
|
+
|
|
191
|
+
async def create(self, waba_id: str, template: TemplateDefinition) -> Dict[str, Any]:
|
|
192
|
+
"""Submit a new template to Meta (starts PENDING)."""
|
|
193
|
+
result: Dict[str, Any] = await self._c._request(specs.templates_create(waba_id, template))
|
|
194
|
+
return result
|
|
195
|
+
|
|
196
|
+
async def create_bulk(
|
|
197
|
+
self, waba_id: str, templates: List[TemplateDefinition]
|
|
198
|
+
) -> Dict[str, Any]:
|
|
199
|
+
"""Create or edit up to 100 templates; results are per row in input order."""
|
|
200
|
+
result: Dict[str, Any] = await self._c._request(
|
|
201
|
+
specs.templates_create_bulk(waba_id, templates)
|
|
202
|
+
)
|
|
203
|
+
return result
|
|
204
|
+
|
|
205
|
+
async def edit(self, template_id: str, changes: TemplateDefinition) -> Dict[str, Any]:
|
|
206
|
+
"""Edit a template (status resets to PENDING)."""
|
|
207
|
+
result: Dict[str, Any] = await self._c._request(specs.templates_edit(template_id, changes))
|
|
208
|
+
return result
|
|
209
|
+
|
|
210
|
+
async def sync(self, waba_id: str) -> Dict[str, Any]:
|
|
211
|
+
"""Re-read every template of the WABA from Meta."""
|
|
212
|
+
result: Dict[str, Any] = await self._c._request(specs.templates_sync(waba_id))
|
|
213
|
+
return result
|
|
214
|
+
|
|
215
|
+
async def delete(self, template_id: str) -> Dict[str, Any]:
|
|
216
|
+
"""Permanently delete one language of a template."""
|
|
217
|
+
result: Dict[str, Any] = await self._c._request(specs.templates_delete(template_id))
|
|
218
|
+
return result
|
|
219
|
+
|
|
220
|
+
async def delete_by_name(self, waba_id: str, name: str) -> Dict[str, Any]:
|
|
221
|
+
"""Permanently delete every language of a template name."""
|
|
222
|
+
result: Dict[str, Any] = await self._c._request(
|
|
223
|
+
specs.templates_delete_by_name(waba_id, name)
|
|
224
|
+
)
|
|
225
|
+
return result
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class WebhookOverride(_Resource):
|
|
229
|
+
async def get(self, phone_number_id: str, *, refresh: bool = False) -> Dict[str, Any]:
|
|
230
|
+
"""Show a number's direct-webhook state; ``refresh=True`` checks Meta's live setting."""
|
|
231
|
+
result: Dict[str, Any] = await self._c._request(specs.webhook_get(phone_number_id, refresh))
|
|
232
|
+
return result
|
|
233
|
+
|
|
234
|
+
async def set(
|
|
235
|
+
self,
|
|
236
|
+
phone_number_id: str,
|
|
237
|
+
url: str,
|
|
238
|
+
verify_token: str,
|
|
239
|
+
*,
|
|
240
|
+
acknowledge_no_tracking: bool,
|
|
241
|
+
) -> Dict[str, Any]:
|
|
242
|
+
"""Point a number's webhook at your own https URL.
|
|
243
|
+
|
|
244
|
+
Hello then stops showing that number's incoming messages and delivery statuses, so
|
|
245
|
+
``acknowledge_no_tracking`` must be ``True`` (the API rejects it otherwise).
|
|
246
|
+
"""
|
|
247
|
+
spec = specs.webhook_set(phone_number_id, url, verify_token, acknowledge_no_tracking)
|
|
248
|
+
result: Dict[str, Any] = await self._c._request(spec)
|
|
249
|
+
return result
|
|
250
|
+
|
|
251
|
+
async def remove(self, phone_number_id: str) -> Dict[str, Any]:
|
|
252
|
+
"""Remove the override so Meta delivers to Hello again."""
|
|
253
|
+
result: Dict[str, Any] = await self._c._request(specs.webhook_remove(phone_number_id))
|
|
254
|
+
return result
|
|
255
|
+
|
|
256
|
+
async def reapply(self, phone_number_id: str) -> Dict[str, Any]:
|
|
257
|
+
"""Re-apply the stored override on Meta (after status ``draft``)."""
|
|
258
|
+
result: Dict[str, Any] = await self._c._request(specs.webhook_reapply(phone_number_id))
|
|
259
|
+
return result
|