diotp 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.
diotp/__init__.py ADDED
@@ -0,0 +1,76 @@
1
+ """Official Python client for the DiOTP OTP API.
2
+
3
+ Send one-time passwords by SMS or WhatsApp and verify them::
4
+
5
+ from diotp import DiOTP
6
+
7
+ client = DiOTP() # reads DIOTP_API_KEY
8
+ otp = client.send("9876543210")
9
+ client.verify(otp.request_id, "482913")
10
+
11
+ Docs: https://diotp.diorbit.com/docs
12
+ """
13
+
14
+ from ._client import DEFAULT_BASE_URL, ERROR_CODES, AsyncDiOTP, Channel, DiOTP
15
+ from ._version import __version__
16
+ from .errors import (
17
+ AuthenticationError,
18
+ ConfigurationError,
19
+ ConflictError,
20
+ DiOTPError,
21
+ ExpiredError,
22
+ InsufficientBalanceError,
23
+ InvalidCodeError,
24
+ NetworkError,
25
+ NotFoundError,
26
+ PermissionDeniedError,
27
+ RateLimitError,
28
+ ServerError,
29
+ TrialError,
30
+ ValidationError,
31
+ WebhookSignatureError,
32
+ )
33
+ from .models import (
34
+ Account,
35
+ AccountClient,
36
+ AccountKey,
37
+ SendResult,
38
+ Usage,
39
+ VerifyResult,
40
+ WebhookEvent,
41
+ )
42
+ from .webhooks import compute_signature, verify_webhook, verify_webhook_headers
43
+
44
+ __all__ = [
45
+ "DEFAULT_BASE_URL",
46
+ "ERROR_CODES",
47
+ "Account",
48
+ "AccountClient",
49
+ "AccountKey",
50
+ "AsyncDiOTP",
51
+ "AuthenticationError",
52
+ "Channel",
53
+ "ConfigurationError",
54
+ "ConflictError",
55
+ "DiOTP",
56
+ "DiOTPError",
57
+ "ExpiredError",
58
+ "InsufficientBalanceError",
59
+ "InvalidCodeError",
60
+ "NetworkError",
61
+ "NotFoundError",
62
+ "PermissionDeniedError",
63
+ "RateLimitError",
64
+ "SendResult",
65
+ "ServerError",
66
+ "TrialError",
67
+ "Usage",
68
+ "ValidationError",
69
+ "VerifyResult",
70
+ "WebhookEvent",
71
+ "WebhookSignatureError",
72
+ "__version__",
73
+ "compute_signature",
74
+ "verify_webhook",
75
+ "verify_webhook_headers",
76
+ ]
diotp/_client.py ADDED
@@ -0,0 +1,608 @@
1
+ """Synchronous and asynchronous DiOTP API clients."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import email.utils
7
+ import json
8
+ import math
9
+ import os
10
+ import random
11
+ import time
12
+ import uuid
13
+ from datetime import datetime, timezone
14
+ from types import TracebackType
15
+ from typing import Any, Callable, Literal, Mapping, Optional
16
+
17
+ import httpx
18
+
19
+ from ._version import __version__
20
+ from .errors import (
21
+ AuthenticationError,
22
+ ConfigurationError,
23
+ ConflictError,
24
+ DiOTPError,
25
+ ExpiredError,
26
+ InsufficientBalanceError,
27
+ InvalidCodeError,
28
+ NetworkError,
29
+ NotFoundError,
30
+ PermissionDeniedError,
31
+ RateLimitError,
32
+ ServerError,
33
+ TrialError,
34
+ ValidationError,
35
+ )
36
+ from .models import Account, SendResult, Usage, VerifyResult
37
+
38
+ __all__ = ["DEFAULT_BASE_URL", "ERROR_CODES", "AsyncDiOTP", "Channel", "DiOTP"]
39
+
40
+ DEFAULT_BASE_URL = "https://api-diotp.diorbit.com/v1"
41
+ DEFAULT_TIMEOUT = 10.0
42
+ DEFAULT_MAX_RETRIES = 2
43
+ API_KEY_ENV = "DIOTP_API_KEY"
44
+ USER_AGENT = f"diotp-python/{__version__}"
45
+
46
+ BACKOFF_BASE = 0.5
47
+ BACKOFF_FACTOR = 2.0
48
+ BACKOFF_CAP = 8.0
49
+
50
+ TEST_MODE_STATUSES = frozenset({"trial", "pending_review"})
51
+ _VERIFY_RETRY_STATUSES = frozenset({502, 503, 504})
52
+
53
+ Channel = Literal["sms", "whatsapp"]
54
+
55
+
56
+ def _mask(api_key: str) -> str:
57
+ return f"dio_...{api_key[-4:]}" if len(api_key) >= 8 else "dio_...****"
58
+
59
+
60
+ def _parse_retry_after(value: Optional[str]) -> Optional[int]:
61
+ """Seconds from a Retry-After header (delta-seconds or HTTP-date), or None."""
62
+ if value is None or not value.strip():
63
+ return None
64
+ value = value.strip()
65
+ if value.isdigit():
66
+ return int(value)
67
+ try:
68
+ when = email.utils.parsedate_to_datetime(value)
69
+ except (TypeError, ValueError):
70
+ return None
71
+ if when.tzinfo is None:
72
+ when = when.replace(tzinfo=timezone.utc)
73
+ return max(0, math.ceil((when - datetime.now(timezone.utc)).total_seconds()))
74
+
75
+
76
+ #: Every error code the API documents (https://diotp.diorbit.com/docs/errors) and its class.
77
+ ERROR_CODES: Mapping[str, type[DiOTPError]] = {
78
+ "invalid_code": InvalidCodeError,
79
+ "unauthorized": AuthenticationError,
80
+ "trial_used_up": TrialError,
81
+ "insufficient_balance": InsufficientBalanceError,
82
+ "trial_restricted": TrialError,
83
+ "account_suspended": PermissionDeniedError,
84
+ "not_found": NotFoundError,
85
+ "already_verified": ConflictError,
86
+ "not_pending": ConflictError,
87
+ "idempotency_key_reused": ConflictError,
88
+ "channel_not_enabled": ConflictError,
89
+ "expired": ExpiredError,
90
+ "invalid_request": ValidationError,
91
+ "template_not_available": ValidationError,
92
+ "resend_cooldown": RateLimitError,
93
+ "phone_hourly_limit": RateLimitError,
94
+ "phone_daily_limit": RateLimitError,
95
+ "api_key_minute_limit": RateLimitError,
96
+ "rate_limited": RateLimitError,
97
+ "test_limit": TrialError,
98
+ "too_many_attempts": RateLimitError,
99
+ "sending_unavailable": ServerError,
100
+ }
101
+
102
+
103
+ def _error_class(status: int, code: Optional[str]) -> type[DiOTPError]:
104
+ if code is not None and code in ERROR_CODES:
105
+ return ERROR_CODES[code]
106
+ if status == 401:
107
+ return AuthenticationError
108
+ if status == 402:
109
+ return InsufficientBalanceError
110
+ if status == 403:
111
+ return PermissionDeniedError
112
+ if status == 404:
113
+ return NotFoundError
114
+ if status == 409:
115
+ return ConflictError
116
+ if status == 410:
117
+ return ExpiredError
118
+ if status in (400, 422):
119
+ return ValidationError
120
+ if status == 429:
121
+ return RateLimitError
122
+ if status >= 500:
123
+ return ServerError
124
+ return DiOTPError
125
+
126
+
127
+ def _error_from_response(response: httpx.Response) -> DiOTPError:
128
+ status = response.status_code
129
+ code: Optional[str] = None
130
+ message: Optional[str] = None
131
+ request_id: Optional[str] = response.headers.get("x-request-id")
132
+ try:
133
+ body = response.json()
134
+ except ValueError:
135
+ body = None
136
+ if isinstance(body, dict) and isinstance(body.get("error"), dict):
137
+ err = body["error"]
138
+ code = str(err["code"]) if err.get("code") is not None else None
139
+ message = str(err["message"]) if err.get("message") is not None else None
140
+ if err.get("request_id"):
141
+ request_id = str(err["request_id"])
142
+ if code is None:
143
+ code = f"http_{status}"
144
+ if message is None:
145
+ message = f"HTTP {status} {response.reason_phrase}".strip()
146
+ cls = _error_class(status, code)
147
+ if cls is RateLimitError:
148
+ return RateLimitError(
149
+ message,
150
+ code=code,
151
+ status=status,
152
+ request_id=request_id,
153
+ retry_after=_parse_retry_after(response.headers.get("retry-after")),
154
+ )
155
+ return cls(message, code=code, status=status, request_id=request_id)
156
+
157
+
158
+ def _decode(response: httpx.Response) -> Mapping[str, Any]:
159
+ try:
160
+ data = response.json()
161
+ except ValueError:
162
+ data = None
163
+ if not isinstance(data, dict):
164
+ raise DiOTPError(
165
+ "the API returned a response that is not a JSON object",
166
+ code="invalid_response",
167
+ status=response.status_code,
168
+ request_id=response.headers.get("x-request-id"),
169
+ )
170
+ return data
171
+
172
+
173
+ def _send_body(
174
+ to: str, country_code: int, channel: str, purpose: str, template: Optional[str]
175
+ ) -> dict[str, Any]:
176
+ body: dict[str, Any] = {
177
+ "to": to,
178
+ "country_code": country_code,
179
+ "channel": channel,
180
+ "purpose": purpose,
181
+ }
182
+ if template is not None:
183
+ body["template"] = template
184
+ return body
185
+
186
+
187
+ class _BaseClient:
188
+ """Configuration and retry policy shared by the sync and async clients."""
189
+
190
+ def __init__(
191
+ self,
192
+ api_key: Optional[str],
193
+ base_url: str,
194
+ timeout: float,
195
+ max_retries: int,
196
+ ) -> None:
197
+ key = api_key if api_key is not None else os.environ.get(API_KEY_ENV)
198
+ if not key:
199
+ raise ConfigurationError(
200
+ f"No DiOTP API key. Pass api_key=... or set the {API_KEY_ENV} environment variable."
201
+ )
202
+ if max_retries < 0:
203
+ raise ConfigurationError("max_retries must be 0 or more")
204
+ self._api_key = key
205
+ self.base_url = base_url.rstrip("/")
206
+ self.timeout = timeout
207
+ self.max_retries = max_retries
208
+
209
+ def __repr__(self) -> str:
210
+ return (
211
+ f"{type(self).__name__}(api_key={_mask(self._api_key)!r}, "
212
+ f"base_url={self.base_url!r}, timeout={self.timeout!r}, "
213
+ f"max_retries={self.max_retries!r})"
214
+ )
215
+
216
+ def _headers(self, idempotency_key: Optional[str] = None) -> dict[str, str]:
217
+ headers = {
218
+ "Authorization": f"Bearer {self._api_key}",
219
+ "User-Agent": USER_AGENT,
220
+ "Accept": "application/json",
221
+ }
222
+ if idempotency_key is not None:
223
+ headers["Idempotency-Key"] = idempotency_key
224
+ return headers
225
+
226
+ def _url(self, path: str) -> str:
227
+ return f"{self.base_url}{path}"
228
+
229
+ @staticmethod
230
+ def _should_retry_status(status: int, verify: bool) -> bool:
231
+ if verify:
232
+ return status in _VERIFY_RETRY_STATUSES
233
+ return status >= 500
234
+
235
+ @staticmethod
236
+ def _backoff(attempt: int) -> float:
237
+ """Full-jitter exponential backoff: uniform(0, min(cap, base * factor**attempt))."""
238
+ return random.uniform(0, min(BACKOFF_CAP, BACKOFF_BASE * BACKOFF_FACTOR**attempt)) # noqa: S311
239
+
240
+ @staticmethod
241
+ def _network_error(exc: httpx.TransportError) -> NetworkError:
242
+ kind = "timed out" if isinstance(exc, httpx.TimeoutException) else "failed"
243
+ return NetworkError(f"the request to the DiOTP API {kind}: {type(exc).__name__}")
244
+
245
+
246
+ class DiOTP(_BaseClient):
247
+ """Synchronous client for the DiOTP OTP API.
248
+
249
+ Args:
250
+ api_key: Your API key. Defaults to the ``DIOTP_API_KEY`` environment variable.
251
+ base_url: The API base URL. Defaults to ``https://api-diotp.diorbit.com/v1``.
252
+ timeout: Seconds to wait for each HTTP attempt. Defaults to 10.
253
+ max_retries: Automatic retries on network errors and 5xx responses. Defaults to 2;
254
+ 0 disables retries. 4xx responses (including 429) are never retried.
255
+ http_client: An ``httpx.Client`` to use instead of the one the client creates. You own
256
+ it: ``close()`` does not close a client you pass in.
257
+
258
+ Raises:
259
+ ConfigurationError: No API key was passed and ``DIOTP_API_KEY`` is not set.
260
+
261
+ Use it as a context manager, or call ``close()`` when done::
262
+
263
+ with DiOTP() as client:
264
+ otp = client.send("9876543210")
265
+ """
266
+
267
+ def __init__(
268
+ self,
269
+ api_key: Optional[str] = None,
270
+ *,
271
+ base_url: str = DEFAULT_BASE_URL,
272
+ timeout: float = DEFAULT_TIMEOUT,
273
+ max_retries: int = DEFAULT_MAX_RETRIES,
274
+ http_client: Optional[httpx.Client] = None,
275
+ ) -> None:
276
+ super().__init__(api_key, base_url, timeout, max_retries)
277
+ self._owns_client = http_client is None
278
+ self._client = http_client if http_client is not None else httpx.Client()
279
+ self._sleep: Callable[[float], None] = time.sleep
280
+
281
+ def __enter__(self) -> DiOTP:
282
+ return self
283
+
284
+ def __exit__(
285
+ self,
286
+ exc_type: Optional[type[BaseException]],
287
+ exc: Optional[BaseException],
288
+ tb: Optional[TracebackType],
289
+ ) -> None:
290
+ self.close()
291
+
292
+ def close(self) -> None:
293
+ """Close the underlying HTTP client, unless it was passed in."""
294
+ if self._owns_client:
295
+ self._client.close()
296
+
297
+ def _request(
298
+ self,
299
+ method: str,
300
+ path: str,
301
+ *,
302
+ json_body: Optional[Mapping[str, Any]] = None,
303
+ params: Optional[Mapping[str, str]] = None,
304
+ idempotency_key: Optional[str] = None,
305
+ verify: bool = False,
306
+ ) -> Mapping[str, Any]:
307
+ content = json.dumps(json_body).encode() if json_body is not None else None
308
+ headers = self._headers(idempotency_key)
309
+ if content is not None:
310
+ headers["Content-Type"] = "application/json"
311
+ attempt = 0
312
+ while True:
313
+ try:
314
+ response = self._client.request(
315
+ method,
316
+ self._url(path),
317
+ content=content,
318
+ params=params,
319
+ headers=headers,
320
+ timeout=self.timeout,
321
+ )
322
+ except httpx.TransportError as exc:
323
+ if attempt < self.max_retries:
324
+ self._sleep(self._backoff(attempt))
325
+ attempt += 1
326
+ continue
327
+ raise self._network_error(exc) from exc
328
+ if response.is_success:
329
+ return _decode(response)
330
+ if attempt < self.max_retries and self._should_retry_status(
331
+ response.status_code, verify
332
+ ):
333
+ self._sleep(self._backoff(attempt))
334
+ attempt += 1
335
+ continue
336
+ raise _error_from_response(response)
337
+
338
+ def send(
339
+ self,
340
+ to: str,
341
+ *,
342
+ country_code: int = 91,
343
+ channel: Channel = "sms",
344
+ purpose: str = "login",
345
+ template: Optional[str] = None,
346
+ idempotency_key: Optional[str] = None,
347
+ ) -> SendResult:
348
+ """Send an OTP to a mobile number (``POST /otp/send``).
349
+
350
+ Args:
351
+ to: The mobile number, digits only, 6 to 15 digits. For India, the 10-digit number
352
+ without +91.
353
+ country_code: The country calling code, without +. Defaults to 91.
354
+ channel: ``"sms"`` (default) or ``"whatsapp"``. WhatsApp must be switched on for
355
+ the account, otherwise ``ConflictError`` ``channel_not_enabled``.
356
+ purpose: A free label for your own reporting, such as login or signup.
357
+ template: Optional template id from the Templates page in the dashboard.
358
+ idempotency_key: Optional ``Idempotency-Key``. A random UUID v4 is generated when
359
+ omitted. The same key is reused on this call's automatic retries, so a retry
360
+ never sends a second code.
361
+
362
+ Returns:
363
+ SendResult with the ``request_id`` to pass to ``verify``.
364
+ """
365
+ key = idempotency_key if idempotency_key is not None else str(uuid.uuid4())
366
+ data = self._request(
367
+ "POST",
368
+ "/otp/send",
369
+ json_body=_send_body(to, country_code, channel, purpose, template),
370
+ idempotency_key=key,
371
+ )
372
+ return SendResult.from_dict(data, idempotency_key=key)
373
+
374
+ def resend(
375
+ self,
376
+ to: str,
377
+ *,
378
+ country_code: int = 91,
379
+ channel: Channel = "sms",
380
+ purpose: str = "login",
381
+ template: Optional[str] = None,
382
+ ) -> SendResult:
383
+ """Send a new code to the same number. A convenience over ``POST /otp/send``.
384
+
385
+ There is no resend endpoint. This sends a brand-new code with a NEW
386
+ ``Idempotency-Key`` and returns a NEW ``request_id``; verify against that one. The
387
+ API allows one code to the same number every 30 seconds: call this sooner and it
388
+ raises ``RateLimitError`` with code ``resend_cooldown``. Show a 30-second resend timer
389
+ in your app.
390
+ """
391
+ return self.send(
392
+ to,
393
+ country_code=country_code,
394
+ channel=channel,
395
+ purpose=purpose,
396
+ template=template,
397
+ idempotency_key=str(uuid.uuid4()),
398
+ )
399
+
400
+ def verify(self, request_id: str, code: str) -> VerifyResult:
401
+ """Check the code the user typed (``POST /otp/verify``).
402
+
403
+ Returns a VerifyResult when the code matches; every failure raises, for example
404
+ ``InvalidCodeError``, ``ExpiredError`` or ``RateLimitError`` ``too_many_attempts``.
405
+
406
+ The server counts every verify attempt (five per request), so this method retries
407
+ only on network errors and 502, 503 and 504, never on other 5xx responses.
408
+ """
409
+ data = self._request(
410
+ "POST",
411
+ "/otp/verify",
412
+ json_body={"request_id": request_id, "code": code},
413
+ verify=True,
414
+ )
415
+ return VerifyResult.from_dict(data)
416
+
417
+ #: Other names for :meth:`send`, :meth:`resend` and :meth:`verify`.
418
+ send_otp = send
419
+ resend_otp = resend
420
+ verify_otp = verify
421
+
422
+ def me(self) -> Account:
423
+ """Return the account and API key the client uses (``GET /me``)."""
424
+ return Account.from_dict(self._request("GET", "/me"))
425
+
426
+ def usage(self, period: Optional[str] = None) -> Usage:
427
+ """Return usage for one month (``GET /usage``).
428
+
429
+ Args:
430
+ period: The month as ``YYYY-MM``. Defaults to the current month.
431
+ """
432
+ params = {"period": period} if period is not None else None
433
+ return Usage.from_dict(self._request("GET", "/usage", params=params))
434
+
435
+ def is_test_mode(self) -> bool:
436
+ """True when the account status is ``trial`` or ``pending_review``.
437
+
438
+ In test mode codes go only to the number verified at sign-up. A live account that
439
+ was switched back to test mode in the dashboard still reports ``live``, so this
440
+ returns False for it.
441
+ """
442
+ return self.me().client.status in TEST_MODE_STATUSES
443
+
444
+
445
+ class AsyncDiOTP(_BaseClient):
446
+ """Asynchronous client for the DiOTP OTP API, with the same methods as :class:`DiOTP`.
447
+
448
+ Args:
449
+ api_key: Your API key. Defaults to the ``DIOTP_API_KEY`` environment variable.
450
+ base_url: The API base URL. Defaults to ``https://api-diotp.diorbit.com/v1``.
451
+ timeout: Seconds to wait for each HTTP attempt. Defaults to 10.
452
+ max_retries: Automatic retries on network errors and 5xx responses. Defaults to 2;
453
+ 0 disables retries.
454
+ http_client: An ``httpx.AsyncClient`` to use. You own it: ``aclose()`` does not close
455
+ a client you pass in.
456
+
457
+ Use it as an async context manager, or call ``await aclose()`` when done::
458
+
459
+ async with AsyncDiOTP() as client:
460
+ otp = await client.send("9876543210")
461
+ """
462
+
463
+ def __init__(
464
+ self,
465
+ api_key: Optional[str] = None,
466
+ *,
467
+ base_url: str = DEFAULT_BASE_URL,
468
+ timeout: float = DEFAULT_TIMEOUT,
469
+ max_retries: int = DEFAULT_MAX_RETRIES,
470
+ http_client: Optional[httpx.AsyncClient] = None,
471
+ ) -> None:
472
+ super().__init__(api_key, base_url, timeout, max_retries)
473
+ self._owns_client = http_client is None
474
+ self._client = http_client if http_client is not None else httpx.AsyncClient()
475
+ self._sleep: Callable[[float], Any] = asyncio.sleep
476
+
477
+ async def __aenter__(self) -> AsyncDiOTP:
478
+ return self
479
+
480
+ async def __aexit__(
481
+ self,
482
+ exc_type: Optional[type[BaseException]],
483
+ exc: Optional[BaseException],
484
+ tb: Optional[TracebackType],
485
+ ) -> None:
486
+ await self.aclose()
487
+
488
+ async def aclose(self) -> None:
489
+ """Close the underlying HTTP client, unless it was passed in."""
490
+ if self._owns_client:
491
+ await self._client.aclose()
492
+
493
+ async def _request(
494
+ self,
495
+ method: str,
496
+ path: str,
497
+ *,
498
+ json_body: Optional[Mapping[str, Any]] = None,
499
+ params: Optional[Mapping[str, str]] = None,
500
+ idempotency_key: Optional[str] = None,
501
+ verify: bool = False,
502
+ ) -> Mapping[str, Any]:
503
+ content = json.dumps(json_body).encode() if json_body is not None else None
504
+ headers = self._headers(idempotency_key)
505
+ if content is not None:
506
+ headers["Content-Type"] = "application/json"
507
+ attempt = 0
508
+ while True:
509
+ try:
510
+ response = await self._client.request(
511
+ method,
512
+ self._url(path),
513
+ content=content,
514
+ params=params,
515
+ headers=headers,
516
+ timeout=self.timeout,
517
+ )
518
+ except httpx.TransportError as exc:
519
+ if attempt < self.max_retries:
520
+ await self._sleep(self._backoff(attempt))
521
+ attempt += 1
522
+ continue
523
+ raise self._network_error(exc) from exc
524
+ if response.is_success:
525
+ return _decode(response)
526
+ if attempt < self.max_retries and self._should_retry_status(
527
+ response.status_code, verify
528
+ ):
529
+ await self._sleep(self._backoff(attempt))
530
+ attempt += 1
531
+ continue
532
+ raise _error_from_response(response)
533
+
534
+ async def send(
535
+ self,
536
+ to: str,
537
+ *,
538
+ country_code: int = 91,
539
+ channel: Channel = "sms",
540
+ purpose: str = "login",
541
+ template: Optional[str] = None,
542
+ idempotency_key: Optional[str] = None,
543
+ ) -> SendResult:
544
+ """Send an OTP to a mobile number. See :meth:`DiOTP.send`."""
545
+ key = idempotency_key if idempotency_key is not None else str(uuid.uuid4())
546
+ data = await self._request(
547
+ "POST",
548
+ "/otp/send",
549
+ json_body=_send_body(to, country_code, channel, purpose, template),
550
+ idempotency_key=key,
551
+ )
552
+ return SendResult.from_dict(data, idempotency_key=key)
553
+
554
+ async def resend(
555
+ self,
556
+ to: str,
557
+ *,
558
+ country_code: int = 91,
559
+ channel: Channel = "sms",
560
+ purpose: str = "login",
561
+ template: Optional[str] = None,
562
+ ) -> SendResult:
563
+ """Send a new code to the same number. A convenience over ``POST /otp/send``.
564
+
565
+ There is no resend endpoint. This sends a brand-new code with a NEW
566
+ ``Idempotency-Key`` and returns a NEW ``request_id``. Wait for the 30-second cooldown
567
+ first, otherwise it raises ``RateLimitError`` with code ``resend_cooldown``.
568
+ """
569
+ return await self.send(
570
+ to,
571
+ country_code=country_code,
572
+ channel=channel,
573
+ purpose=purpose,
574
+ template=template,
575
+ idempotency_key=str(uuid.uuid4()),
576
+ )
577
+
578
+ async def verify(self, request_id: str, code: str) -> VerifyResult:
579
+ """Check the code the user typed. See :meth:`DiOTP.verify`.
580
+
581
+ Retries only on network errors and 502, 503 and 504, because the server counts
582
+ every verify attempt.
583
+ """
584
+ data = await self._request(
585
+ "POST",
586
+ "/otp/verify",
587
+ json_body={"request_id": request_id, "code": code},
588
+ verify=True,
589
+ )
590
+ return VerifyResult.from_dict(data)
591
+
592
+ #: Other names for :meth:`send`, :meth:`resend` and :meth:`verify`.
593
+ send_otp = send
594
+ resend_otp = resend
595
+ verify_otp = verify
596
+
597
+ async def me(self) -> Account:
598
+ """Return the account and API key the client uses (``GET /me``)."""
599
+ return Account.from_dict(await self._request("GET", "/me"))
600
+
601
+ async def usage(self, period: Optional[str] = None) -> Usage:
602
+ """Return usage for one month (``GET /usage``); ``period`` is ``YYYY-MM``."""
603
+ params = {"period": period} if period is not None else None
604
+ return Usage.from_dict(await self._request("GET", "/usage", params=params))
605
+
606
+ async def is_test_mode(self) -> bool:
607
+ """True when the account status is ``trial`` or ``pending_review``."""
608
+ return (await self.me()).client.status in TEST_MODE_STATUSES
diotp/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"