smarthivesms 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.
- smarthivesms/__init__.py +20 -0
- smarthivesms/client.py +630 -0
- smarthivesms/errors.py +50 -0
- smarthivesms/py.typed +0 -0
- smarthivesms-1.0.0.dist-info/METADATA +169 -0
- smarthivesms-1.0.0.dist-info/RECORD +8 -0
- smarthivesms-1.0.0.dist-info/WHEEL +4 -0
- smarthivesms-1.0.0.dist-info/licenses/LICENSE +21 -0
smarthivesms/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from .client import AsyncSmarthiveSMS, SmarthiveSMS, SmsRoute
|
|
2
|
+
from .errors import (
|
|
3
|
+
SmarthiveAuthError,
|
|
4
|
+
SmarthiveError,
|
|
5
|
+
SmarthiveRateLimitError,
|
|
6
|
+
SmarthiveValidationError,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
__version__ = "1.0.0"
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"__version__",
|
|
13
|
+
"SmarthiveSMS",
|
|
14
|
+
"AsyncSmarthiveSMS",
|
|
15
|
+
"SmsRoute",
|
|
16
|
+
"SmarthiveError",
|
|
17
|
+
"SmarthiveAuthError",
|
|
18
|
+
"SmarthiveValidationError",
|
|
19
|
+
"SmarthiveRateLimitError",
|
|
20
|
+
]
|
smarthivesms/client.py
ADDED
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Dict, Literal, Optional, Sequence, Union
|
|
7
|
+
from urllib.parse import quote
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from .errors import (
|
|
12
|
+
SmarthiveAuthError,
|
|
13
|
+
SmarthiveError,
|
|
14
|
+
SmarthiveRateLimitError,
|
|
15
|
+
SmarthiveValidationError,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
SmsRoute = Literal["MKT", "TRX", "INTL"]
|
|
19
|
+
|
|
20
|
+
DEFAULT_BASE_URL = "https://api.smarthivesms.com"
|
|
21
|
+
DEFAULT_TIMEOUT = 30.0
|
|
22
|
+
DEFAULT_MAX_RETRIES = 2
|
|
23
|
+
SDK_USER_AGENT = "smarthivesms-python/1.0.0"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _extract_error_message(payload: Any, fallback: str) -> str:
|
|
27
|
+
if isinstance(payload, dict):
|
|
28
|
+
for key in ("message", "error", "detail", "msg"):
|
|
29
|
+
val = payload.get(key)
|
|
30
|
+
if isinstance(val, str) and val.strip():
|
|
31
|
+
return val
|
|
32
|
+
if isinstance(payload, str) and payload.strip():
|
|
33
|
+
return payload
|
|
34
|
+
return fallback
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _parse_response(response: httpx.Response) -> Any:
|
|
38
|
+
if not response.text:
|
|
39
|
+
return {}
|
|
40
|
+
try:
|
|
41
|
+
return response.json()
|
|
42
|
+
except ValueError:
|
|
43
|
+
return response.text
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _parse_retry_after(response: httpx.Response) -> Optional[float]:
|
|
47
|
+
raw = response.headers.get("retry-after")
|
|
48
|
+
if not raw:
|
|
49
|
+
return None
|
|
50
|
+
try:
|
|
51
|
+
return float(raw)
|
|
52
|
+
except ValueError:
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class _BaseClient:
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
api_key: Optional[str] = None,
|
|
60
|
+
*,
|
|
61
|
+
api_key_mkt: Optional[str] = None,
|
|
62
|
+
api_key_trx: Optional[str] = None,
|
|
63
|
+
api_key_intl: Optional[str] = None,
|
|
64
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
65
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
66
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
67
|
+
) -> None:
|
|
68
|
+
self._default_api_key = api_key if api_key is not None else os.getenv("SMARTHIVE_API_KEY", "")
|
|
69
|
+
self._mkt_api_key = api_key_mkt if api_key_mkt is not None else os.getenv("SMARTHIVE_API_KEY_MKT")
|
|
70
|
+
self._trx_api_key = api_key_trx if api_key_trx is not None else os.getenv("SMARTHIVE_API_KEY_TRX")
|
|
71
|
+
self._intl_api_key = api_key_intl if api_key_intl is not None else os.getenv("SMARTHIVE_API_KEY_INTL")
|
|
72
|
+
self.base_url = base_url.rstrip("/")
|
|
73
|
+
self.timeout = timeout
|
|
74
|
+
self.max_retries = max_retries
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def is_sandbox(self) -> bool:
|
|
78
|
+
"""True when the resolved default API key is a SmarthiveSMS Sandbox key (`SMTSBX_...`)."""
|
|
79
|
+
return self.resolve_key().startswith("SMTSBX_")
|
|
80
|
+
|
|
81
|
+
def resolve_key(self, route: Optional[str] = None, explicit_key: Optional[str] = None) -> str:
|
|
82
|
+
if explicit_key:
|
|
83
|
+
return explicit_key
|
|
84
|
+
normalized = (route or "").upper()
|
|
85
|
+
if normalized == "TRX" and self._trx_api_key:
|
|
86
|
+
return self._trx_api_key
|
|
87
|
+
if normalized == "MKT" and self._mkt_api_key:
|
|
88
|
+
return self._mkt_api_key
|
|
89
|
+
if normalized == "INTL" and self._intl_api_key:
|
|
90
|
+
return self._intl_api_key
|
|
91
|
+
return (
|
|
92
|
+
self._default_api_key
|
|
93
|
+
or self._trx_api_key
|
|
94
|
+
or self._mkt_api_key
|
|
95
|
+
or self._intl_api_key
|
|
96
|
+
or ""
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
def _build_headers(self, key: str) -> Dict[str, str]:
|
|
100
|
+
return {
|
|
101
|
+
"Content-Type": "application/json",
|
|
102
|
+
"x-api-key": key,
|
|
103
|
+
"User-Agent": SDK_USER_AGENT,
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class _SmsResource:
|
|
108
|
+
def __init__(self, client: SmarthiveSMS) -> None:
|
|
109
|
+
self._client = client
|
|
110
|
+
|
|
111
|
+
def send(
|
|
112
|
+
self,
|
|
113
|
+
*,
|
|
114
|
+
sender: str,
|
|
115
|
+
recipients: str,
|
|
116
|
+
msg: str,
|
|
117
|
+
route: SmsRoute = "MKT",
|
|
118
|
+
type: int = 1,
|
|
119
|
+
ext_ref: Optional[str] = None,
|
|
120
|
+
api_key: Optional[str] = None,
|
|
121
|
+
) -> Dict[str, Any]:
|
|
122
|
+
payload: Dict[str, Any] = {
|
|
123
|
+
"sender": sender,
|
|
124
|
+
"recipients": recipients,
|
|
125
|
+
"msg": msg,
|
|
126
|
+
"route": route,
|
|
127
|
+
"type": type,
|
|
128
|
+
}
|
|
129
|
+
if ext_ref is not None:
|
|
130
|
+
payload["ext_ref"] = ext_ref
|
|
131
|
+
return self._client._request(
|
|
132
|
+
"POST",
|
|
133
|
+
"/api/sms/send",
|
|
134
|
+
json_body=payload,
|
|
135
|
+
api_key=self._client.resolve_key(route, api_key),
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
def send_bulk(
|
|
139
|
+
self,
|
|
140
|
+
*,
|
|
141
|
+
sender: str,
|
|
142
|
+
recipients: Union[str, Sequence[str]],
|
|
143
|
+
msg: str,
|
|
144
|
+
route: SmsRoute = "MKT",
|
|
145
|
+
type: int = 1,
|
|
146
|
+
api_key: Optional[str] = None,
|
|
147
|
+
) -> Dict[str, Any]:
|
|
148
|
+
recipients_str = recipients if isinstance(recipients, str) else ",".join(recipients)
|
|
149
|
+
return self._client._request(
|
|
150
|
+
"POST",
|
|
151
|
+
"/api/sms/send/multi",
|
|
152
|
+
json_body={
|
|
153
|
+
"sender": sender,
|
|
154
|
+
"recipients": recipients_str,
|
|
155
|
+
"msg": msg,
|
|
156
|
+
"route": route,
|
|
157
|
+
"type": type,
|
|
158
|
+
},
|
|
159
|
+
api_key=self._client.resolve_key(route, api_key),
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
def status(self, message_id: str, *, api_key: Optional[str] = None) -> Dict[str, Any]:
|
|
163
|
+
return self._client._request(
|
|
164
|
+
"POST",
|
|
165
|
+
"/api/sms/status",
|
|
166
|
+
json_body={"message_id": message_id},
|
|
167
|
+
api_key=self._client.resolve_key(None, api_key),
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class _BalanceResource:
|
|
172
|
+
def __init__(self, client: SmarthiveSMS) -> None:
|
|
173
|
+
self._client = client
|
|
174
|
+
|
|
175
|
+
def get(self, *, api_key: Optional[str] = None) -> Dict[str, Any]:
|
|
176
|
+
return self._client._request(
|
|
177
|
+
"GET",
|
|
178
|
+
"/api/sms/credit",
|
|
179
|
+
api_key=self._client.resolve_key(None, api_key),
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class _WhatsappResource:
|
|
184
|
+
def __init__(self, client: SmarthiveSMS) -> None:
|
|
185
|
+
self._client = client
|
|
186
|
+
|
|
187
|
+
def send_otp(
|
|
188
|
+
self,
|
|
189
|
+
*,
|
|
190
|
+
recipient: str,
|
|
191
|
+
code: str,
|
|
192
|
+
sender: str = "SmarthiveSMS",
|
|
193
|
+
api_key: Optional[str] = None,
|
|
194
|
+
) -> Dict[str, Any]:
|
|
195
|
+
return self._client._request(
|
|
196
|
+
"POST",
|
|
197
|
+
"/api/whatsapp/send",
|
|
198
|
+
json_body={"recipient": recipient, "code": code, "sender": sender},
|
|
199
|
+
api_key=self._client.resolve_key(None, api_key),
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class _VoiceResource:
|
|
204
|
+
def __init__(self, client: SmarthiveSMS) -> None:
|
|
205
|
+
self._client = client
|
|
206
|
+
|
|
207
|
+
def send_otp(
|
|
208
|
+
self,
|
|
209
|
+
*,
|
|
210
|
+
phone: str,
|
|
211
|
+
otp: str,
|
|
212
|
+
api_key: Optional[str] = None,
|
|
213
|
+
) -> Dict[str, Any]:
|
|
214
|
+
return self._client._request(
|
|
215
|
+
"POST",
|
|
216
|
+
"/api/voice/otp",
|
|
217
|
+
json_body={"phone": phone, "otp": otp},
|
|
218
|
+
api_key=self._client.resolve_key(None, api_key),
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
def status(self, call_id: str, *, api_key: Optional[str] = None) -> Dict[str, Any]:
|
|
222
|
+
return self._client._request(
|
|
223
|
+
"GET",
|
|
224
|
+
f"/api/voice/status/{quote(call_id, safe='')}",
|
|
225
|
+
api_key=self._client.resolve_key(None, api_key),
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class _EmailResource:
|
|
230
|
+
def __init__(self, client: SmarthiveSMS) -> None:
|
|
231
|
+
self._client = client
|
|
232
|
+
|
|
233
|
+
def send(
|
|
234
|
+
self,
|
|
235
|
+
*,
|
|
236
|
+
to: str,
|
|
237
|
+
subject: str,
|
|
238
|
+
html: str,
|
|
239
|
+
from_email: str = "support@smarthivesms.com",
|
|
240
|
+
from_name: str = "Smarthive Notification",
|
|
241
|
+
name: str = "Transactional Email",
|
|
242
|
+
api_key: Optional[str] = None,
|
|
243
|
+
) -> Dict[str, Any]:
|
|
244
|
+
return self._client._request(
|
|
245
|
+
"POST",
|
|
246
|
+
"/api/email/campaign/send_campaign",
|
|
247
|
+
json_body={
|
|
248
|
+
"name": name,
|
|
249
|
+
"from": from_email,
|
|
250
|
+
"fromName": from_name,
|
|
251
|
+
"to": to,
|
|
252
|
+
"subject": subject,
|
|
253
|
+
"html": html,
|
|
254
|
+
},
|
|
255
|
+
api_key=self._client.resolve_key(None, api_key),
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
class SmarthiveSMS(_BaseClient):
|
|
260
|
+
"""Synchronous SmarthiveSMS Python SDK client."""
|
|
261
|
+
|
|
262
|
+
def __init__(
|
|
263
|
+
self,
|
|
264
|
+
api_key: Optional[str] = None,
|
|
265
|
+
*,
|
|
266
|
+
api_key_mkt: Optional[str] = None,
|
|
267
|
+
api_key_trx: Optional[str] = None,
|
|
268
|
+
api_key_intl: Optional[str] = None,
|
|
269
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
270
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
271
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
272
|
+
http_client: Optional[httpx.Client] = None,
|
|
273
|
+
) -> None:
|
|
274
|
+
super().__init__(
|
|
275
|
+
api_key,
|
|
276
|
+
api_key_mkt=api_key_mkt,
|
|
277
|
+
api_key_trx=api_key_trx,
|
|
278
|
+
api_key_intl=api_key_intl,
|
|
279
|
+
base_url=base_url,
|
|
280
|
+
timeout=timeout,
|
|
281
|
+
max_retries=max_retries,
|
|
282
|
+
)
|
|
283
|
+
self._owns_client = http_client is None
|
|
284
|
+
self._http = http_client or httpx.Client(base_url=self.base_url, timeout=self.timeout)
|
|
285
|
+
|
|
286
|
+
self.sms = _SmsResource(self)
|
|
287
|
+
self.balance = _BalanceResource(self)
|
|
288
|
+
self.whatsapp = _WhatsappResource(self)
|
|
289
|
+
self.voice = _VoiceResource(self)
|
|
290
|
+
self.email = _EmailResource(self)
|
|
291
|
+
|
|
292
|
+
def close(self) -> None:
|
|
293
|
+
if self._owns_client:
|
|
294
|
+
self._http.close()
|
|
295
|
+
|
|
296
|
+
def __enter__(self) -> SmarthiveSMS:
|
|
297
|
+
return self
|
|
298
|
+
|
|
299
|
+
def __exit__(self, *args: Any) -> None:
|
|
300
|
+
self.close()
|
|
301
|
+
|
|
302
|
+
def _request(
|
|
303
|
+
self,
|
|
304
|
+
method: str,
|
|
305
|
+
path: str,
|
|
306
|
+
*,
|
|
307
|
+
api_key: str,
|
|
308
|
+
json_body: Optional[Dict[str, Any]] = None,
|
|
309
|
+
) -> Dict[str, Any]:
|
|
310
|
+
is_sandbox = api_key.startswith("SMTSBX_")
|
|
311
|
+
if not api_key:
|
|
312
|
+
raise SmarthiveAuthError(
|
|
313
|
+
"Missing SmarthiveSMS API key. Pass `api_key` or set `SMARTHIVE_API_KEY`.",
|
|
314
|
+
status_code=401,
|
|
315
|
+
is_sandbox=False,
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
last_exc: Optional[Exception] = None
|
|
319
|
+
for attempt in range(self.max_retries + 1):
|
|
320
|
+
try:
|
|
321
|
+
res = self._http.request(
|
|
322
|
+
method,
|
|
323
|
+
path,
|
|
324
|
+
json=json_body,
|
|
325
|
+
headers=self._build_headers(api_key),
|
|
326
|
+
)
|
|
327
|
+
except httpx.HTTPError as exc:
|
|
328
|
+
last_exc = exc
|
|
329
|
+
if attempt < self.max_retries:
|
|
330
|
+
time.sleep(0.25 * (2**attempt))
|
|
331
|
+
continue
|
|
332
|
+
raise SmarthiveError(str(exc), status_code=0, response=exc, is_sandbox=is_sandbox) from exc
|
|
333
|
+
|
|
334
|
+
data = _parse_response(res)
|
|
335
|
+
if res.is_success:
|
|
336
|
+
return data if isinstance(data, dict) else {"data": data}
|
|
337
|
+
|
|
338
|
+
message = _extract_error_message(data, f"Request failed with HTTP {res.status_code}")
|
|
339
|
+
|
|
340
|
+
if res.status_code in (401, 403):
|
|
341
|
+
raise SmarthiveAuthError(message, status_code=res.status_code, response=data, is_sandbox=is_sandbox)
|
|
342
|
+
if res.status_code in (400, 422):
|
|
343
|
+
raise SmarthiveValidationError(message, status_code=res.status_code, response=data, is_sandbox=is_sandbox)
|
|
344
|
+
if res.status_code == 429:
|
|
345
|
+
retry_after = _parse_retry_after(res)
|
|
346
|
+
if attempt < self.max_retries:
|
|
347
|
+
time.sleep(retry_after if retry_after is not None else float(2**attempt))
|
|
348
|
+
continue
|
|
349
|
+
raise SmarthiveRateLimitError(
|
|
350
|
+
message,
|
|
351
|
+
status_code=429,
|
|
352
|
+
response=data,
|
|
353
|
+
retry_after=retry_after,
|
|
354
|
+
is_sandbox=is_sandbox,
|
|
355
|
+
)
|
|
356
|
+
if res.status_code >= 500 and attempt < self.max_retries:
|
|
357
|
+
time.sleep(0.25 * (2**attempt))
|
|
358
|
+
continue
|
|
359
|
+
|
|
360
|
+
raise SmarthiveError(message, status_code=res.status_code, response=data, is_sandbox=is_sandbox)
|
|
361
|
+
|
|
362
|
+
raise SmarthiveError(
|
|
363
|
+
str(last_exc) if last_exc else "Network request to SmarthiveSMS failed",
|
|
364
|
+
status_code=0,
|
|
365
|
+
response=last_exc,
|
|
366
|
+
is_sandbox=is_sandbox,
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
class _AsyncSmsResource:
|
|
371
|
+
def __init__(self, client: AsyncSmarthiveSMS) -> None:
|
|
372
|
+
self._client = client
|
|
373
|
+
|
|
374
|
+
async def send(
|
|
375
|
+
self,
|
|
376
|
+
*,
|
|
377
|
+
sender: str,
|
|
378
|
+
recipients: str,
|
|
379
|
+
msg: str,
|
|
380
|
+
route: SmsRoute = "MKT",
|
|
381
|
+
type: int = 1,
|
|
382
|
+
ext_ref: Optional[str] = None,
|
|
383
|
+
api_key: Optional[str] = None,
|
|
384
|
+
) -> Dict[str, Any]:
|
|
385
|
+
payload: Dict[str, Any] = {
|
|
386
|
+
"sender": sender,
|
|
387
|
+
"recipients": recipients,
|
|
388
|
+
"msg": msg,
|
|
389
|
+
"route": route,
|
|
390
|
+
"type": type,
|
|
391
|
+
}
|
|
392
|
+
if ext_ref is not None:
|
|
393
|
+
payload["ext_ref"] = ext_ref
|
|
394
|
+
return await self._client._request(
|
|
395
|
+
"POST",
|
|
396
|
+
"/api/sms/send",
|
|
397
|
+
json_body=payload,
|
|
398
|
+
api_key=self._client.resolve_key(route, api_key),
|
|
399
|
+
)
|
|
400
|
+
|
|
401
|
+
async def send_bulk(
|
|
402
|
+
self,
|
|
403
|
+
*,
|
|
404
|
+
sender: str,
|
|
405
|
+
recipients: Union[str, Sequence[str]],
|
|
406
|
+
msg: str,
|
|
407
|
+
route: SmsRoute = "MKT",
|
|
408
|
+
type: int = 1,
|
|
409
|
+
api_key: Optional[str] = None,
|
|
410
|
+
) -> Dict[str, Any]:
|
|
411
|
+
recipients_str = recipients if isinstance(recipients, str) else ",".join(recipients)
|
|
412
|
+
return await self._client._request(
|
|
413
|
+
"POST",
|
|
414
|
+
"/api/sms/send/multi",
|
|
415
|
+
json_body={
|
|
416
|
+
"sender": sender,
|
|
417
|
+
"recipients": recipients_str,
|
|
418
|
+
"msg": msg,
|
|
419
|
+
"route": route,
|
|
420
|
+
"type": type,
|
|
421
|
+
},
|
|
422
|
+
api_key=self._client.resolve_key(route, api_key),
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
async def status(self, message_id: str, *, api_key: Optional[str] = None) -> Dict[str, Any]:
|
|
426
|
+
return await self._client._request(
|
|
427
|
+
"POST",
|
|
428
|
+
"/api/sms/status",
|
|
429
|
+
json_body={"message_id": message_id},
|
|
430
|
+
api_key=self._client.resolve_key(None, api_key),
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
class _AsyncBalanceResource:
|
|
435
|
+
def __init__(self, client: AsyncSmarthiveSMS) -> None:
|
|
436
|
+
self._client = client
|
|
437
|
+
|
|
438
|
+
async def get(self, *, api_key: Optional[str] = None) -> Dict[str, Any]:
|
|
439
|
+
return await self._client._request(
|
|
440
|
+
"GET",
|
|
441
|
+
"/api/sms/credit",
|
|
442
|
+
api_key=self._client.resolve_key(None, api_key),
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
class _AsyncWhatsappResource:
|
|
447
|
+
def __init__(self, client: AsyncSmarthiveSMS) -> None:
|
|
448
|
+
self._client = client
|
|
449
|
+
|
|
450
|
+
async def send_otp(
|
|
451
|
+
self,
|
|
452
|
+
*,
|
|
453
|
+
recipient: str,
|
|
454
|
+
code: str,
|
|
455
|
+
sender: str = "SmarthiveSMS",
|
|
456
|
+
api_key: Optional[str] = None,
|
|
457
|
+
) -> Dict[str, Any]:
|
|
458
|
+
return await self._client._request(
|
|
459
|
+
"POST",
|
|
460
|
+
"/api/whatsapp/send",
|
|
461
|
+
json_body={"recipient": recipient, "code": code, "sender": sender},
|
|
462
|
+
api_key=self._client.resolve_key(None, api_key),
|
|
463
|
+
)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
class _AsyncVoiceResource:
|
|
467
|
+
def __init__(self, client: AsyncSmarthiveSMS) -> None:
|
|
468
|
+
self._client = client
|
|
469
|
+
|
|
470
|
+
async def send_otp(
|
|
471
|
+
self,
|
|
472
|
+
*,
|
|
473
|
+
phone: str,
|
|
474
|
+
otp: str,
|
|
475
|
+
api_key: Optional[str] = None,
|
|
476
|
+
) -> Dict[str, Any]:
|
|
477
|
+
return await self._client._request(
|
|
478
|
+
"POST",
|
|
479
|
+
"/api/voice/otp",
|
|
480
|
+
json_body={"phone": phone, "otp": otp},
|
|
481
|
+
api_key=self._client.resolve_key(None, api_key),
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
async def status(self, call_id: str, *, api_key: Optional[str] = None) -> Dict[str, Any]:
|
|
485
|
+
return await self._client._request(
|
|
486
|
+
"GET",
|
|
487
|
+
f"/api/voice/status/{quote(call_id, safe='')}",
|
|
488
|
+
api_key=self._client.resolve_key(None, api_key),
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
class _AsyncEmailResource:
|
|
493
|
+
def __init__(self, client: AsyncSmarthiveSMS) -> None:
|
|
494
|
+
self._client = client
|
|
495
|
+
|
|
496
|
+
async def send(
|
|
497
|
+
self,
|
|
498
|
+
*,
|
|
499
|
+
to: str,
|
|
500
|
+
subject: str,
|
|
501
|
+
html: str,
|
|
502
|
+
from_email: str = "support@smarthivesms.com",
|
|
503
|
+
from_name: str = "Smarthive Notification",
|
|
504
|
+
name: str = "Transactional Email",
|
|
505
|
+
api_key: Optional[str] = None,
|
|
506
|
+
) -> Dict[str, Any]:
|
|
507
|
+
return await self._client._request(
|
|
508
|
+
"POST",
|
|
509
|
+
"/api/email/campaign/send_campaign",
|
|
510
|
+
json_body={
|
|
511
|
+
"name": name,
|
|
512
|
+
"from": from_email,
|
|
513
|
+
"fromName": from_name,
|
|
514
|
+
"to": to,
|
|
515
|
+
"subject": subject,
|
|
516
|
+
"html": html,
|
|
517
|
+
},
|
|
518
|
+
api_key=self._client.resolve_key(None, api_key),
|
|
519
|
+
)
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
class AsyncSmarthiveSMS(_BaseClient):
|
|
523
|
+
"""Asynchronous SmarthiveSMS Python SDK client (FastAPI, Starlette, asyncio)."""
|
|
524
|
+
|
|
525
|
+
def __init__(
|
|
526
|
+
self,
|
|
527
|
+
api_key: Optional[str] = None,
|
|
528
|
+
*,
|
|
529
|
+
api_key_mkt: Optional[str] = None,
|
|
530
|
+
api_key_trx: Optional[str] = None,
|
|
531
|
+
api_key_intl: Optional[str] = None,
|
|
532
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
533
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
534
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
535
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
536
|
+
) -> None:
|
|
537
|
+
super().__init__(
|
|
538
|
+
api_key,
|
|
539
|
+
api_key_mkt=api_key_mkt,
|
|
540
|
+
api_key_trx=api_key_trx,
|
|
541
|
+
api_key_intl=api_key_intl,
|
|
542
|
+
base_url=base_url,
|
|
543
|
+
timeout=timeout,
|
|
544
|
+
max_retries=max_retries,
|
|
545
|
+
)
|
|
546
|
+
self._owns_client = http_client is None
|
|
547
|
+
self._http = http_client or httpx.AsyncClient(base_url=self.base_url, timeout=self.timeout)
|
|
548
|
+
|
|
549
|
+
self.sms = _AsyncSmsResource(self)
|
|
550
|
+
self.balance = _AsyncBalanceResource(self)
|
|
551
|
+
self.whatsapp = _AsyncWhatsappResource(self)
|
|
552
|
+
self.voice = _AsyncVoiceResource(self)
|
|
553
|
+
self.email = _AsyncEmailResource(self)
|
|
554
|
+
|
|
555
|
+
async def aclose(self) -> None:
|
|
556
|
+
if self._owns_client:
|
|
557
|
+
await self._http.aclose()
|
|
558
|
+
|
|
559
|
+
async def __aenter__(self) -> AsyncSmarthiveSMS:
|
|
560
|
+
return self
|
|
561
|
+
|
|
562
|
+
async def __aexit__(self, *args: Any) -> None:
|
|
563
|
+
await self.aclose()
|
|
564
|
+
|
|
565
|
+
async def _request(
|
|
566
|
+
self,
|
|
567
|
+
method: str,
|
|
568
|
+
path: str,
|
|
569
|
+
*,
|
|
570
|
+
api_key: str,
|
|
571
|
+
json_body: Optional[Dict[str, Any]] = None,
|
|
572
|
+
) -> Dict[str, Any]:
|
|
573
|
+
is_sandbox = api_key.startswith("SMTSBX_")
|
|
574
|
+
if not api_key:
|
|
575
|
+
raise SmarthiveAuthError(
|
|
576
|
+
"Missing SmarthiveSMS API key. Pass `api_key` or set `SMARTHIVE_API_KEY`.",
|
|
577
|
+
status_code=401,
|
|
578
|
+
is_sandbox=False,
|
|
579
|
+
)
|
|
580
|
+
|
|
581
|
+
last_exc: Optional[Exception] = None
|
|
582
|
+
for attempt in range(self.max_retries + 1):
|
|
583
|
+
try:
|
|
584
|
+
res = await self._http.request(
|
|
585
|
+
method,
|
|
586
|
+
path,
|
|
587
|
+
json=json_body,
|
|
588
|
+
headers=self._build_headers(api_key),
|
|
589
|
+
)
|
|
590
|
+
except httpx.HTTPError as exc:
|
|
591
|
+
last_exc = exc
|
|
592
|
+
if attempt < self.max_retries:
|
|
593
|
+
await asyncio.sleep(0.25 * (2**attempt))
|
|
594
|
+
continue
|
|
595
|
+
raise SmarthiveError(str(exc), status_code=0, response=exc, is_sandbox=is_sandbox) from exc
|
|
596
|
+
|
|
597
|
+
data = _parse_response(res)
|
|
598
|
+
if res.is_success:
|
|
599
|
+
return data if isinstance(data, dict) else {"data": data}
|
|
600
|
+
|
|
601
|
+
message = _extract_error_message(data, f"Request failed with HTTP {res.status_code}")
|
|
602
|
+
|
|
603
|
+
if res.status_code in (401, 403):
|
|
604
|
+
raise SmarthiveAuthError(message, status_code=res.status_code, response=data, is_sandbox=is_sandbox)
|
|
605
|
+
if res.status_code in (400, 422):
|
|
606
|
+
raise SmarthiveValidationError(message, status_code=res.status_code, response=data, is_sandbox=is_sandbox)
|
|
607
|
+
if res.status_code == 429:
|
|
608
|
+
retry_after = _parse_retry_after(res)
|
|
609
|
+
if attempt < self.max_retries:
|
|
610
|
+
await asyncio.sleep(retry_after if retry_after is not None else float(2**attempt))
|
|
611
|
+
continue
|
|
612
|
+
raise SmarthiveRateLimitError(
|
|
613
|
+
message,
|
|
614
|
+
status_code=429,
|
|
615
|
+
response=data,
|
|
616
|
+
retry_after=retry_after,
|
|
617
|
+
is_sandbox=is_sandbox,
|
|
618
|
+
)
|
|
619
|
+
if res.status_code >= 500 and attempt < self.max_retries:
|
|
620
|
+
await asyncio.sleep(0.25 * (2**attempt))
|
|
621
|
+
continue
|
|
622
|
+
|
|
623
|
+
raise SmarthiveError(message, status_code=res.status_code, response=data, is_sandbox=is_sandbox)
|
|
624
|
+
|
|
625
|
+
raise SmarthiveError(
|
|
626
|
+
str(last_exc) if last_exc else "Network request to SmarthiveSMS failed",
|
|
627
|
+
status_code=0,
|
|
628
|
+
response=last_exc,
|
|
629
|
+
is_sandbox=is_sandbox,
|
|
630
|
+
)
|
smarthivesms/errors.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class SmarthiveError(Exception):
|
|
7
|
+
"""Base exception for all SmarthiveSMS API errors."""
|
|
8
|
+
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
message: str,
|
|
12
|
+
*,
|
|
13
|
+
status_code: int = 0,
|
|
14
|
+
response: Any = None,
|
|
15
|
+
is_sandbox: bool = False,
|
|
16
|
+
) -> None:
|
|
17
|
+
super().__init__(message)
|
|
18
|
+
self.message = message
|
|
19
|
+
self.status_code = status_code
|
|
20
|
+
self.response = response
|
|
21
|
+
self.is_sandbox = is_sandbox
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class SmarthiveAuthError(SmarthiveError):
|
|
25
|
+
"""Raised on HTTP 401/403 or missing API key."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class SmarthiveValidationError(SmarthiveError):
|
|
29
|
+
"""Raised on HTTP 400/422 validation or insufficient credit errors."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SmarthiveRateLimitError(SmarthiveError):
|
|
33
|
+
"""Raised on HTTP 429 rate limit responses."""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
message: str,
|
|
38
|
+
*,
|
|
39
|
+
status_code: int = 429,
|
|
40
|
+
response: Any = None,
|
|
41
|
+
retry_after: Optional[float] = None,
|
|
42
|
+
is_sandbox: bool = False,
|
|
43
|
+
) -> None:
|
|
44
|
+
super().__init__(
|
|
45
|
+
message,
|
|
46
|
+
status_code=status_code,
|
|
47
|
+
response=response,
|
|
48
|
+
is_sandbox=is_sandbox,
|
|
49
|
+
)
|
|
50
|
+
self.retry_after = retry_after
|
smarthivesms/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: smarthivesms
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Official Python SDK for SmarthiveSMS — Nigerian & African SMS (TRX DND-bypass & MKT), WhatsApp OTP, Voice OTP, and Transactional Email API.
|
|
5
|
+
Project-URL: Homepage, https://smarthivesms.com
|
|
6
|
+
Project-URL: Documentation, https://docs.smarthivesms.com
|
|
7
|
+
Project-URL: Repository, https://github.com/smarthive-tech-solution/smarthivesms-sdks
|
|
8
|
+
Project-URL: Issues, https://github.com/smarthive-tech-solution/smarthivesms-sdks/issues
|
|
9
|
+
Author-email: Smarthive Tech Solution <support@smarthivesms.com>
|
|
10
|
+
License: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: africa,bulk-sms,cpaas,dnd-bypass,nigeria-sms,otp,smarthivesms,sms,transactional-email,voice-otp,whatsapp-otp
|
|
13
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Communications
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Classifier: Typing :: Typed
|
|
26
|
+
Requires-Python: >=3.9
|
|
27
|
+
Requires-Dist: httpx>=0.25.0
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
|
|
30
|
+
Requires-Dist: pytest>=8.0.0; extra == 'dev'
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# smarthivesms (Official Python SDK)
|
|
34
|
+
|
|
35
|
+
Official Python SDK for [SmarthiveSMS](https://smarthivesms.com) — Nigerian & African omnichannel messaging API for **Transactional DND-bypass SMS (TRX)**, **Marketing Bulk SMS (MKT)**, **WhatsApp OTP**, **Automated Voice OTP**, and **Transactional Email**.
|
|
36
|
+
|
|
37
|
+
- Both **Synchronous (`SmarthiveSMS`)** and **Asynchronous (`AsyncSmarthiveSMS`)** clients powered by `httpx`
|
|
38
|
+
- Full type annotations (`py.typed`)
|
|
39
|
+
- Built-in support for the **free ₦50,000 auto-replenishing Developer Sandbox** (`SMTSBX_...` keys)
|
|
40
|
+
- Automatic retries on transient network / 5xx / 429 errors
|
|
41
|
+
|
|
42
|
+
## Installation
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install smarthivesms
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Quick Start
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import os
|
|
52
|
+
from smarthivesms import SmarthiveSMS
|
|
53
|
+
|
|
54
|
+
# Reads SMARTHIVE_API_KEY automatically, or pass explicitly.
|
|
55
|
+
# Use a Sandbox key (SMTSBX_...) for free ₦50,000 simulated testing.
|
|
56
|
+
client = SmarthiveSMS(api_key=os.getenv("SMARTHIVE_API_KEY"))
|
|
57
|
+
|
|
58
|
+
# Send a DND-bypass Transactional OTP SMS
|
|
59
|
+
res = client.sms.send(
|
|
60
|
+
sender="MyApp",
|
|
61
|
+
recipients="2348012345678",
|
|
62
|
+
msg="Your verification code is 492041.",
|
|
63
|
+
route="TRX",
|
|
64
|
+
)
|
|
65
|
+
print(res["message_id"])
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Async Usage (FastAPI / asyncio)
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from smarthivesms import AsyncSmarthiveSMS
|
|
72
|
+
|
|
73
|
+
async with AsyncSmarthiveSMS(api_key="SMTSBX_your_sandbox_key") as client:
|
|
74
|
+
res = await client.sms.send(
|
|
75
|
+
sender="MyApp",
|
|
76
|
+
recipients="2348012345678",
|
|
77
|
+
msg="Your login code is 849204.",
|
|
78
|
+
route="TRX",
|
|
79
|
+
)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Usage Examples
|
|
83
|
+
|
|
84
|
+
### Bulk SMS
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
client.sms.send_bulk(
|
|
88
|
+
sender="MyApp",
|
|
89
|
+
recipients=["2348012345678", "2348098765432"],
|
|
90
|
+
msg="Flash sale starts at noon!",
|
|
91
|
+
route="MKT",
|
|
92
|
+
)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Check SMS Delivery Status (DLR)
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
status = client.sms.status("msg_9041284")
|
|
99
|
+
print(status["status"]) # DELIVRD | UNDELIV | PENDING
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### WhatsApp OTP
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
client.whatsapp.send_otp(
|
|
106
|
+
recipient="2348012345678",
|
|
107
|
+
code="849204",
|
|
108
|
+
sender="MyApp",
|
|
109
|
+
)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Automated Voice OTP
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
call = client.voice.send_otp(phone="2348012345678", otp="8429")
|
|
116
|
+
status = client.voice.status(call["call_id"])
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Transactional Email
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
client.email.send(
|
|
123
|
+
to="user@example.com",
|
|
124
|
+
subject="Welcome to MyApp",
|
|
125
|
+
html="<h1>Welcome!</h1><p>Thanks for signing up.</p>",
|
|
126
|
+
from_email="no-reply@myapp.com",
|
|
127
|
+
from_name="MyApp",
|
|
128
|
+
)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### Check Balance & Credits
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
bal = client.balance.get()
|
|
135
|
+
print(bal)
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### Error Handling
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
from smarthivesms import (
|
|
142
|
+
SmarthiveAuthError,
|
|
143
|
+
SmarthiveValidationError,
|
|
144
|
+
SmarthiveRateLimitError,
|
|
145
|
+
SmarthiveError,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
try:
|
|
149
|
+
client.sms.send(sender="MyApp", recipients="2348012345678", msg="Hi", route="TRX")
|
|
150
|
+
except SmarthiveAuthError as e:
|
|
151
|
+
print("Invalid API key:", e.message)
|
|
152
|
+
except SmarthiveValidationError as e:
|
|
153
|
+
print("Validation error:", e.message)
|
|
154
|
+
except SmarthiveRateLimitError as e:
|
|
155
|
+
print("Rate limited, retry after:", e.retry_after)
|
|
156
|
+
except SmarthiveError as e:
|
|
157
|
+
print("API error:", e.status_code, e.message)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## Documentation & Links
|
|
161
|
+
|
|
162
|
+
- API Docs: https://docs.smarthivesms.com
|
|
163
|
+
- Dashboard & Free Sandbox: https://app.smarthivesms.com/signup
|
|
164
|
+
- OpenAPI 3.1 Spec: https://smarthivesms.com/openapi.json
|
|
165
|
+
- Official MCP Server for AI Agents: `npx -y smarthivesms-mcp`
|
|
166
|
+
|
|
167
|
+
## License
|
|
168
|
+
|
|
169
|
+
MIT © Smarthive Tech Solution
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
smarthivesms/__init__.py,sha256=x3KE0klXykgcd9OOpxgbmyH8BDIngCc7SZQ9uGVx-fw,418
|
|
2
|
+
smarthivesms/client.py,sha256=t4nLrT7KSsnU5-Tdq4RjMXyUKSyoWTI5RFeafZq1EVQ,20208
|
|
3
|
+
smarthivesms/errors.py,sha256=rngdr09iCpJ0sG_21xaaQSoybyX3A9NVEwft2JLxPZk,1254
|
|
4
|
+
smarthivesms/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
smarthivesms-1.0.0.dist-info/METADATA,sha256=NdJxrtVV-ce0z0OsQKWQb6XPP6zrKNduJQFTWpT3Iqs,4862
|
|
6
|
+
smarthivesms-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
smarthivesms-1.0.0.dist-info/licenses/LICENSE,sha256=9aFrkaAWBkCl0_ghYYFCOw_OCDz8Z5UgW8Vz1N4uf5U,1080
|
|
8
|
+
smarthivesms-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Smarthive Tech Solution
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|