numberotp 0.1.0__tar.gz
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.
- numberotp-0.1.0/.gitignore +33 -0
- numberotp-0.1.0/LICENSE +21 -0
- numberotp-0.1.0/PKG-INFO +71 -0
- numberotp-0.1.0/README.md +46 -0
- numberotp-0.1.0/numberotp/__init__.py +48 -0
- numberotp-0.1.0/numberotp/_client.py +380 -0
- numberotp-0.1.0/numberotp/_core.py +256 -0
- numberotp-0.1.0/numberotp/_errors.py +97 -0
- numberotp-0.1.0/numberotp/_generated.py +836 -0
- numberotp-0.1.0/numberotp/py.typed +0 -0
- numberotp-0.1.0/numberotp/webhooks.py +27 -0
- numberotp-0.1.0/pyproject.toml +38 -0
- numberotp-0.1.0/tests/test_client.py +179 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Secrets — never commit
|
|
2
|
+
.env
|
|
3
|
+
.env.*
|
|
4
|
+
!.env.example
|
|
5
|
+
*.pem
|
|
6
|
+
*.key
|
|
7
|
+
*.p12
|
|
8
|
+
credentials.json
|
|
9
|
+
*.secret
|
|
10
|
+
.npmrc
|
|
11
|
+
.pypirc
|
|
12
|
+
*.gpg
|
|
13
|
+
secring.*
|
|
14
|
+
|
|
15
|
+
# Build output / dependencies
|
|
16
|
+
node_modules/
|
|
17
|
+
dist/
|
|
18
|
+
build/
|
|
19
|
+
target/
|
|
20
|
+
bin/
|
|
21
|
+
obj/
|
|
22
|
+
vendor/
|
|
23
|
+
__pycache__/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.venv/
|
|
26
|
+
.gradle/
|
|
27
|
+
*.gem
|
|
28
|
+
coverage/
|
|
29
|
+
|
|
30
|
+
# OS / editors
|
|
31
|
+
.DS_Store
|
|
32
|
+
.idea/
|
|
33
|
+
.vscode/
|
numberotp-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 NumberOTP
|
|
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.
|
numberotp-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: numberotp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official NumberOTP API client — virtual numbers for SMS / OTP verification
|
|
5
|
+
Project-URL: Homepage, https://www.numberotp.com/developers/sdks
|
|
6
|
+
Project-URL: Documentation, https://www.numberotp.com/docs/sdks
|
|
7
|
+
Project-URL: API reference, https://www.numberotp.com/docs/api
|
|
8
|
+
Project-URL: Source, https://github.com/DishantSinghDev2/numberotp-python
|
|
9
|
+
Author-email: NumberOTP <support@numberotp.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: numberotp,otp,phone verification,sms,virtual number
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Requires-Dist: httpx<1,>=0.27
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
23
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# numberotp (Python)
|
|
27
|
+
|
|
28
|
+
The official Python client for the [NumberOTP API](https://www.numberotp.com/docs/api): real phone numbers for SMS / OTP verification. It has sync and async clients, is fully typed, and supports Python 3.9+.
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install numberotp
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Get an API key at [numberotp.com/dashboard/developer](https://www.numberotp.com/dashboard/developer) and set it as `NOTP_API_KEY`. Guides: [numberotp.com/docs/sdks](https://www.numberotp.com/docs/sdks).
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from numberotp import NumberOTP
|
|
38
|
+
|
|
39
|
+
client = NumberOTP() # reads NOTP_API_KEY
|
|
40
|
+
|
|
41
|
+
act = client.activations.create_and_wait(
|
|
42
|
+
service="wa", country="16",
|
|
43
|
+
on_number=lambda n: print("Use this number:", n["phoneNumber"]),
|
|
44
|
+
)
|
|
45
|
+
print("Code:", act["otp"])
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Async
|
|
49
|
+
```python
|
|
50
|
+
from numberotp import AsyncNumberOTP
|
|
51
|
+
|
|
52
|
+
async with AsyncNumberOTP() as client:
|
|
53
|
+
n = await client.activations.create(service="tg", country="187")
|
|
54
|
+
act = await client.activations.wait_for_code(n["data"]["id"], timeout=600)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### More
|
|
58
|
+
```python
|
|
59
|
+
client.services.search(q="discord.com")
|
|
60
|
+
client.prices.get(service="wa")
|
|
61
|
+
client.activations.resend(id) / finish(id) / cancel(id) # cancel → full refund
|
|
62
|
+
for event in client.events.stream(): # live events, reconnects by itself
|
|
63
|
+
...
|
|
64
|
+
from numberotp import verify_webhook # check x-numberotp-signature
|
|
65
|
+
client.auth.device_login(lambda c: print(c["user_code"])) # sign a user in (CLI-style)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Errors and reliability
|
|
69
|
+
- Errors carry `.status` and a stable `.code`: `InsufficientBalanceError`, `NotFoundError`, `ConflictError`, `ActivationClosedError`, `WaitTimeoutError` and others.
|
|
70
|
+
- Purchases send an `Idempotency-Key`, so retries never buy twice.
|
|
71
|
+
- Expired access tokens refresh automatically.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# numberotp (Python)
|
|
2
|
+
|
|
3
|
+
The official Python client for the [NumberOTP API](https://www.numberotp.com/docs/api): real phone numbers for SMS / OTP verification. It has sync and async clients, is fully typed, and supports Python 3.9+.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install numberotp
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Get an API key at [numberotp.com/dashboard/developer](https://www.numberotp.com/dashboard/developer) and set it as `NOTP_API_KEY`. Guides: [numberotp.com/docs/sdks](https://www.numberotp.com/docs/sdks).
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from numberotp import NumberOTP
|
|
13
|
+
|
|
14
|
+
client = NumberOTP() # reads NOTP_API_KEY
|
|
15
|
+
|
|
16
|
+
act = client.activations.create_and_wait(
|
|
17
|
+
service="wa", country="16",
|
|
18
|
+
on_number=lambda n: print("Use this number:", n["phoneNumber"]),
|
|
19
|
+
)
|
|
20
|
+
print("Code:", act["otp"])
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### Async
|
|
24
|
+
```python
|
|
25
|
+
from numberotp import AsyncNumberOTP
|
|
26
|
+
|
|
27
|
+
async with AsyncNumberOTP() as client:
|
|
28
|
+
n = await client.activations.create(service="tg", country="187")
|
|
29
|
+
act = await client.activations.wait_for_code(n["data"]["id"], timeout=600)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### More
|
|
33
|
+
```python
|
|
34
|
+
client.services.search(q="discord.com")
|
|
35
|
+
client.prices.get(service="wa")
|
|
36
|
+
client.activations.resend(id) / finish(id) / cancel(id) # cancel → full refund
|
|
37
|
+
for event in client.events.stream(): # live events, reconnects by itself
|
|
38
|
+
...
|
|
39
|
+
from numberotp import verify_webhook # check x-numberotp-signature
|
|
40
|
+
client.auth.device_login(lambda c: print(c["user_code"])) # sign a user in (CLI-style)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Errors and reliability
|
|
44
|
+
- Errors carry `.status` and a stable `.code`: `InsufficientBalanceError`, `NotFoundError`, `ConflictError`, `ActivationClosedError`, `WaitTimeoutError` and others.
|
|
45
|
+
- Purchases send an `Idempotency-Key`, so retries never buy twice.
|
|
46
|
+
- Expired access tokens refresh automatically.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Official Python client for the NumberOTP API — virtual numbers for SMS / OTP verification.
|
|
2
|
+
|
|
3
|
+
::
|
|
4
|
+
|
|
5
|
+
from numberotp import NumberOTP
|
|
6
|
+
|
|
7
|
+
client = NumberOTP() # reads NOTP_API_KEY
|
|
8
|
+
act = client.activations.create_and_wait(service="wa", country="16")
|
|
9
|
+
print(act["phone_number"], act["otp"])
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from ._client import AsyncNumberOTP, NumberOTP
|
|
13
|
+
from ._core import DEFAULT_BASE_URL, VERSION
|
|
14
|
+
from ._errors import (
|
|
15
|
+
ActivationClosedError,
|
|
16
|
+
APIConnectionError,
|
|
17
|
+
AuthenticationError,
|
|
18
|
+
ConflictError,
|
|
19
|
+
InsufficientBalanceError,
|
|
20
|
+
NotFoundError,
|
|
21
|
+
NumberOTPError,
|
|
22
|
+
PermissionDeniedError,
|
|
23
|
+
RateLimitError,
|
|
24
|
+
ServerError,
|
|
25
|
+
WaitTimeoutError,
|
|
26
|
+
)
|
|
27
|
+
from .webhooks import verify_webhook
|
|
28
|
+
|
|
29
|
+
__version__ = VERSION
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"NumberOTP",
|
|
33
|
+
"AsyncNumberOTP",
|
|
34
|
+
"verify_webhook",
|
|
35
|
+
"NumberOTPError",
|
|
36
|
+
"APIConnectionError",
|
|
37
|
+
"AuthenticationError",
|
|
38
|
+
"InsufficientBalanceError",
|
|
39
|
+
"PermissionDeniedError",
|
|
40
|
+
"NotFoundError",
|
|
41
|
+
"ConflictError",
|
|
42
|
+
"RateLimitError",
|
|
43
|
+
"ServerError",
|
|
44
|
+
"ActivationClosedError",
|
|
45
|
+
"WaitTimeoutError",
|
|
46
|
+
"DEFAULT_BASE_URL",
|
|
47
|
+
"VERSION",
|
|
48
|
+
]
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
"""The NumberOTP clients (sync and async) and their hand-written helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any, AsyncIterator, Awaitable, Callable, Dict, Iterator, Mapping, Optional, Union
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from ._core import AsyncTransport, SyncTransport, TokenCallback
|
|
13
|
+
from ._errors import ActivationClosedError, NumberOTPError, WaitTimeoutError, error_from_response
|
|
14
|
+
from ._generated import (
|
|
15
|
+
ActivationsResource,
|
|
16
|
+
AsyncActivationsResource,
|
|
17
|
+
AsyncAuthResource,
|
|
18
|
+
AsyncEventsResource,
|
|
19
|
+
AsyncResources,
|
|
20
|
+
AuthResource,
|
|
21
|
+
EventsResource,
|
|
22
|
+
Resources,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
_CLOSED = {"expired", "canceled", "finished"}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _wait_outcome(err: NumberOTPError) -> str:
|
|
29
|
+
"""'again' (window still open), 'closed', or 'raise'."""
|
|
30
|
+
status = err.body.get("status") if isinstance(err.body, dict) else None
|
|
31
|
+
if err.status == 408 or status == "waiting" or err.code == "TIMEOUT":
|
|
32
|
+
return "again"
|
|
33
|
+
if err.status == 400 and status in _CLOSED:
|
|
34
|
+
return "closed"
|
|
35
|
+
return "raise"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# ── SSE ──────────────────────────────────────────────────────────────────────
|
|
39
|
+
|
|
40
|
+
class _SseParser:
|
|
41
|
+
def __init__(self) -> None:
|
|
42
|
+
self.id: Optional[str] = None
|
|
43
|
+
self.event: Optional[str] = None
|
|
44
|
+
self.data: list = []
|
|
45
|
+
|
|
46
|
+
def feed(self, line: str) -> Optional[Dict[str, Any]]:
|
|
47
|
+
if line == "":
|
|
48
|
+
if not self.data:
|
|
49
|
+
return None
|
|
50
|
+
msg = {"id": self.id, "event": self.event, "data": "\n".join(self.data)}
|
|
51
|
+
self.id, self.event, self.data = None, None, []
|
|
52
|
+
return msg
|
|
53
|
+
if line.startswith(":"):
|
|
54
|
+
return None
|
|
55
|
+
field, _, value = line.partition(":")
|
|
56
|
+
value = value[1:] if value.startswith(" ") else value
|
|
57
|
+
if field == "data":
|
|
58
|
+
self.data.append(value)
|
|
59
|
+
elif field == "id":
|
|
60
|
+
self.id = value
|
|
61
|
+
elif field == "event":
|
|
62
|
+
self.event = value
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _event_from(msg: Dict[str, Any]) -> Dict[str, Any]:
|
|
67
|
+
event = json.loads(msg["data"])
|
|
68
|
+
event["stream_id"] = msg["id"]
|
|
69
|
+
return event
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# ── Sync ─────────────────────────────────────────────────────────────────────
|
|
73
|
+
|
|
74
|
+
class Activations(ActivationsResource):
|
|
75
|
+
def wait_once(self, id: str, request_options: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: # type: ignore[override]
|
|
76
|
+
"""One long-poll round (up to ~55 s). Prefer wait_for_code()."""
|
|
77
|
+
return super().wait_once(id, request_options={"timeout": 70.0, "max_retries": 0, **(request_options or {})})
|
|
78
|
+
|
|
79
|
+
def wait_for_code(self, id: str, *, timeout: float = 1200.0) -> Dict[str, Any]:
|
|
80
|
+
"""Waits until the code arrives and returns the whole activation (code, full SMS, all
|
|
81
|
+
messages). Raises ActivationClosedError if it expired or was canceled first (refunded),
|
|
82
|
+
WaitTimeoutError if ``timeout`` seconds pass."""
|
|
83
|
+
deadline = time.monotonic() + timeout
|
|
84
|
+
while time.monotonic() < deadline:
|
|
85
|
+
try:
|
|
86
|
+
self.wait_once(id, request_options={"timeout": min(70.0, deadline - time.monotonic() + 5)})
|
|
87
|
+
return self.get(id)["data"]
|
|
88
|
+
except NumberOTPError as e:
|
|
89
|
+
outcome = _wait_outcome(e)
|
|
90
|
+
if outcome == "again":
|
|
91
|
+
continue
|
|
92
|
+
if outcome == "closed":
|
|
93
|
+
raise ActivationClosedError(e.body["status"], e.body) from e
|
|
94
|
+
raise
|
|
95
|
+
raise WaitTimeoutError()
|
|
96
|
+
|
|
97
|
+
def create_and_wait(self, *, service: str, country: str, timeout: float = 1200.0,
|
|
98
|
+
on_number: Optional[Callable[[Dict[str, Any]], None]] = None, **params: Any) -> Dict[str, Any]:
|
|
99
|
+
"""Buys a number, then waits for its code — the common case in one call."""
|
|
100
|
+
created = self.create(service=service, country=country, **params)
|
|
101
|
+
if on_number:
|
|
102
|
+
on_number(created["data"])
|
|
103
|
+
return self.wait_for_code(created["data"]["id"], timeout=timeout)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class Events(EventsResource):
|
|
107
|
+
def stream(self, *, since: Optional[str] = None) -> Iterator[Dict[str, Any]]:
|
|
108
|
+
"""Live events, forever (reconnects by itself, never skips one)::
|
|
109
|
+
|
|
110
|
+
for event in client.events.stream():
|
|
111
|
+
if event["type"] == "activation.code_received": ...
|
|
112
|
+
"""
|
|
113
|
+
cursor = since
|
|
114
|
+
failures = 0
|
|
115
|
+
while True:
|
|
116
|
+
try:
|
|
117
|
+
resp = self._t.send("GET", "/events", query={"since": cursor} if cursor else None, stream=True,
|
|
118
|
+
options={"timeout": httpx.Timeout(75.0, connect=10.0), "max_retries": 0,
|
|
119
|
+
"headers": {"Accept": "text/event-stream"}})
|
|
120
|
+
except NumberOTPError:
|
|
121
|
+
failures += 1
|
|
122
|
+
if failures > 5:
|
|
123
|
+
raise
|
|
124
|
+
time.sleep(min(30, 2**failures))
|
|
125
|
+
continue
|
|
126
|
+
try:
|
|
127
|
+
if resp.is_error:
|
|
128
|
+
resp.read()
|
|
129
|
+
raise error_from_response(resp.status_code, resp.json() if resp.content else None)
|
|
130
|
+
failures = 0
|
|
131
|
+
parser = _SseParser()
|
|
132
|
+
for line in resp.iter_lines():
|
|
133
|
+
msg = parser.feed(line)
|
|
134
|
+
if msg:
|
|
135
|
+
if msg["id"]:
|
|
136
|
+
cursor = msg["id"]
|
|
137
|
+
yield _event_from(msg)
|
|
138
|
+
except httpx.HTTPError:
|
|
139
|
+
pass # dropped connection — reconnect from the cursor
|
|
140
|
+
finally:
|
|
141
|
+
resp.close()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class Auth(AuthResource):
|
|
145
|
+
def _sign_in(self, **fields: Any) -> Dict[str, Any]:
|
|
146
|
+
tokens = self.token(**fields)
|
|
147
|
+
self._t.set_tokens(tokens)
|
|
148
|
+
if self._t.on_tokens:
|
|
149
|
+
self._t.on_tokens(tokens)
|
|
150
|
+
return tokens
|
|
151
|
+
|
|
152
|
+
def device_login(self, on_code: Callable[[Dict[str, Any]], None], *, client: str = "cli",
|
|
153
|
+
device_name: Optional[str] = None) -> Dict[str, Any]:
|
|
154
|
+
"""Device sign-in (RFC 8628): ``on_code`` shows the person a code; they approve it on
|
|
155
|
+
numberotp.com/device; this returns the tokens (and signs the client in)."""
|
|
156
|
+
code = self.start_device_sign_in(client=client, device_name=device_name)
|
|
157
|
+
on_code(code)
|
|
158
|
+
interval = max(1, int(code["interval"]))
|
|
159
|
+
deadline = time.monotonic() + int(code["expires_in"])
|
|
160
|
+
while time.monotonic() < deadline:
|
|
161
|
+
time.sleep(interval)
|
|
162
|
+
try:
|
|
163
|
+
return self._sign_in(grant_type="urn:ietf:params:oauth:grant-type:device_code",
|
|
164
|
+
device_code=code["device_code"], platform=client, device_name=device_name)
|
|
165
|
+
except NumberOTPError as e:
|
|
166
|
+
if e.code == "authorization_pending":
|
|
167
|
+
continue
|
|
168
|
+
if e.code == "slow_down":
|
|
169
|
+
interval += 5
|
|
170
|
+
continue
|
|
171
|
+
raise
|
|
172
|
+
raise NumberOTPError("The sign-in code expired before it was approved", 400, "expired_token")
|
|
173
|
+
|
|
174
|
+
def sign_in_with_email_code(self, email: str, code: str, *, name: Optional[str] = None,
|
|
175
|
+
platform: Optional[str] = None, device_name: Optional[str] = None) -> Dict[str, Any]:
|
|
176
|
+
"""Signs in with the 6-digit code from send_email_code() — creates the account if it's new."""
|
|
177
|
+
return self._sign_in(grant_type="urn:numberotp:params:grant-type:email_code", email=email, code=code,
|
|
178
|
+
name=name, platform=platform, device_name=device_name)
|
|
179
|
+
|
|
180
|
+
def sign_in_with_password(self, email: str, password: str, *, platform: Optional[str] = None,
|
|
181
|
+
device_name: Optional[str] = None) -> Dict[str, Any]:
|
|
182
|
+
return self._sign_in(grant_type="password", email=email, password=password, platform=platform, device_name=device_name)
|
|
183
|
+
|
|
184
|
+
def sign_out(self) -> None:
|
|
185
|
+
"""Revokes the refresh token server-side and forgets the tokens."""
|
|
186
|
+
if self._t.refresh_token:
|
|
187
|
+
try:
|
|
188
|
+
self.revoke(token=self._t.refresh_token)
|
|
189
|
+
except NumberOTPError:
|
|
190
|
+
pass
|
|
191
|
+
self._t.clear_tokens()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class NumberOTP(Resources):
|
|
195
|
+
"""The NumberOTP API client.
|
|
196
|
+
|
|
197
|
+
::
|
|
198
|
+
|
|
199
|
+
client = NumberOTP() # reads NOTP_API_KEY
|
|
200
|
+
n = client.activations.create(service="wa", country="16")
|
|
201
|
+
act = client.activations.wait_for_code(n["data"]["id"])
|
|
202
|
+
print(act["otp"])
|
|
203
|
+
"""
|
|
204
|
+
|
|
205
|
+
activations: Activations # type: ignore[assignment]
|
|
206
|
+
events: Events # type: ignore[assignment]
|
|
207
|
+
auth: Auth # type: ignore[assignment]
|
|
208
|
+
|
|
209
|
+
def __init__(self, api_key: Optional[str] = None, *, access_token: Optional[str] = None,
|
|
210
|
+
refresh_token: Optional[str] = None, on_tokens: Optional[TokenCallback] = None,
|
|
211
|
+
base_url: Optional[str] = None, timeout: float = 30.0, max_retries: int = 2,
|
|
212
|
+
http_client: Optional[httpx.Client] = None, default_headers: Optional[Mapping[str, str]] = None) -> None:
|
|
213
|
+
self._transport = SyncTransport(api_key=api_key, access_token=access_token, refresh_token=refresh_token,
|
|
214
|
+
on_tokens=on_tokens, base_url=base_url, timeout=timeout,
|
|
215
|
+
max_retries=max_retries, http_client=http_client, default_headers=default_headers)
|
|
216
|
+
self._init_resources(self._transport)
|
|
217
|
+
self.activations = Activations(self._transport)
|
|
218
|
+
self.events = Events(self._transport)
|
|
219
|
+
self.auth = Auth(self._transport)
|
|
220
|
+
|
|
221
|
+
def set_tokens(self, tokens: Mapping[str, Any]) -> None:
|
|
222
|
+
self._transport.set_tokens(tokens)
|
|
223
|
+
|
|
224
|
+
def close(self) -> None:
|
|
225
|
+
self._transport.close()
|
|
226
|
+
|
|
227
|
+
def __enter__(self) -> "NumberOTP":
|
|
228
|
+
return self
|
|
229
|
+
|
|
230
|
+
def __exit__(self, *exc: Any) -> None:
|
|
231
|
+
self.close()
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
# ── Async ────────────────────────────────────────────────────────────────────
|
|
235
|
+
|
|
236
|
+
class AsyncActivations(AsyncActivationsResource):
|
|
237
|
+
async def wait_once(self, id: str, request_options: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: # type: ignore[override]
|
|
238
|
+
return await super().wait_once(id, request_options={"timeout": 70.0, "max_retries": 0, **(request_options or {})})
|
|
239
|
+
|
|
240
|
+
async def wait_for_code(self, id: str, *, timeout: float = 1200.0) -> Dict[str, Any]:
|
|
241
|
+
loop = asyncio.get_running_loop()
|
|
242
|
+
deadline = loop.time() + timeout
|
|
243
|
+
while loop.time() < deadline:
|
|
244
|
+
try:
|
|
245
|
+
await self.wait_once(id, request_options={"timeout": min(70.0, deadline - loop.time() + 5)})
|
|
246
|
+
return (await self.get(id))["data"]
|
|
247
|
+
except NumberOTPError as e:
|
|
248
|
+
outcome = _wait_outcome(e)
|
|
249
|
+
if outcome == "again":
|
|
250
|
+
continue
|
|
251
|
+
if outcome == "closed":
|
|
252
|
+
raise ActivationClosedError(e.body["status"], e.body) from e
|
|
253
|
+
raise
|
|
254
|
+
raise WaitTimeoutError()
|
|
255
|
+
|
|
256
|
+
async def create_and_wait(self, *, service: str, country: str, timeout: float = 1200.0,
|
|
257
|
+
on_number: Optional[Callable[[Dict[str, Any]], Union[None, Awaitable[None]]]] = None,
|
|
258
|
+
**params: Any) -> Dict[str, Any]:
|
|
259
|
+
created = await self.create(service=service, country=country, **params)
|
|
260
|
+
if on_number:
|
|
261
|
+
result = on_number(created["data"])
|
|
262
|
+
if asyncio.iscoroutine(result):
|
|
263
|
+
await result
|
|
264
|
+
return await self.wait_for_code(created["data"]["id"], timeout=timeout)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
class AsyncEvents(AsyncEventsResource):
|
|
268
|
+
async def stream(self, *, since: Optional[str] = None) -> AsyncIterator[Dict[str, Any]]:
|
|
269
|
+
cursor = since
|
|
270
|
+
failures = 0
|
|
271
|
+
while True:
|
|
272
|
+
try:
|
|
273
|
+
resp = await self._t.send("GET", "/events", query={"since": cursor} if cursor else None, stream=True,
|
|
274
|
+
options={"timeout": httpx.Timeout(75.0, connect=10.0), "max_retries": 0,
|
|
275
|
+
"headers": {"Accept": "text/event-stream"}})
|
|
276
|
+
except NumberOTPError:
|
|
277
|
+
failures += 1
|
|
278
|
+
if failures > 5:
|
|
279
|
+
raise
|
|
280
|
+
await asyncio.sleep(min(30, 2**failures))
|
|
281
|
+
continue
|
|
282
|
+
try:
|
|
283
|
+
if resp.is_error:
|
|
284
|
+
await resp.aread()
|
|
285
|
+
raise error_from_response(resp.status_code, resp.json() if resp.content else None)
|
|
286
|
+
failures = 0
|
|
287
|
+
parser = _SseParser()
|
|
288
|
+
async for line in resp.aiter_lines():
|
|
289
|
+
msg = parser.feed(line)
|
|
290
|
+
if msg:
|
|
291
|
+
if msg["id"]:
|
|
292
|
+
cursor = msg["id"]
|
|
293
|
+
yield _event_from(msg)
|
|
294
|
+
except httpx.HTTPError:
|
|
295
|
+
pass
|
|
296
|
+
finally:
|
|
297
|
+
await resp.aclose()
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
class AsyncAuth(AsyncAuthResource):
|
|
301
|
+
async def _sign_in(self, **fields: Any) -> Dict[str, Any]:
|
|
302
|
+
tokens = await self.token(**fields)
|
|
303
|
+
self._t.set_tokens(tokens)
|
|
304
|
+
if self._t.on_tokens:
|
|
305
|
+
result = self._t.on_tokens(tokens)
|
|
306
|
+
if asyncio.iscoroutine(result):
|
|
307
|
+
await result
|
|
308
|
+
return tokens
|
|
309
|
+
|
|
310
|
+
async def device_login(self, on_code: Callable[[Dict[str, Any]], Union[None, Awaitable[None]]], *,
|
|
311
|
+
client: str = "cli", device_name: Optional[str] = None) -> Dict[str, Any]:
|
|
312
|
+
code = await self.start_device_sign_in(client=client, device_name=device_name)
|
|
313
|
+
result = on_code(code)
|
|
314
|
+
if asyncio.iscoroutine(result):
|
|
315
|
+
await result
|
|
316
|
+
interval = max(1, int(code["interval"]))
|
|
317
|
+
loop = asyncio.get_running_loop()
|
|
318
|
+
deadline = loop.time() + int(code["expires_in"])
|
|
319
|
+
while loop.time() < deadline:
|
|
320
|
+
await asyncio.sleep(interval)
|
|
321
|
+
try:
|
|
322
|
+
return await self._sign_in(grant_type="urn:ietf:params:oauth:grant-type:device_code",
|
|
323
|
+
device_code=code["device_code"], platform=client, device_name=device_name)
|
|
324
|
+
except NumberOTPError as e:
|
|
325
|
+
if e.code == "authorization_pending":
|
|
326
|
+
continue
|
|
327
|
+
if e.code == "slow_down":
|
|
328
|
+
interval += 5
|
|
329
|
+
continue
|
|
330
|
+
raise
|
|
331
|
+
raise NumberOTPError("The sign-in code expired before it was approved", 400, "expired_token")
|
|
332
|
+
|
|
333
|
+
async def sign_in_with_email_code(self, email: str, code: str, *, name: Optional[str] = None,
|
|
334
|
+
platform: Optional[str] = None, device_name: Optional[str] = None) -> Dict[str, Any]:
|
|
335
|
+
return await self._sign_in(grant_type="urn:numberotp:params:grant-type:email_code", email=email, code=code,
|
|
336
|
+
name=name, platform=platform, device_name=device_name)
|
|
337
|
+
|
|
338
|
+
async def sign_in_with_password(self, email: str, password: str, *, platform: Optional[str] = None,
|
|
339
|
+
device_name: Optional[str] = None) -> Dict[str, Any]:
|
|
340
|
+
return await self._sign_in(grant_type="password", email=email, password=password, platform=platform, device_name=device_name)
|
|
341
|
+
|
|
342
|
+
async def sign_out(self) -> None:
|
|
343
|
+
if self._t.refresh_token:
|
|
344
|
+
try:
|
|
345
|
+
await self.revoke(token=self._t.refresh_token)
|
|
346
|
+
except NumberOTPError:
|
|
347
|
+
pass
|
|
348
|
+
self._t.clear_tokens()
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
class AsyncNumberOTP(AsyncResources):
|
|
352
|
+
"""Async NumberOTP client — same API as NumberOTP, with ``await``."""
|
|
353
|
+
|
|
354
|
+
activations: AsyncActivations # type: ignore[assignment]
|
|
355
|
+
events: AsyncEvents # type: ignore[assignment]
|
|
356
|
+
auth: AsyncAuth # type: ignore[assignment]
|
|
357
|
+
|
|
358
|
+
def __init__(self, api_key: Optional[str] = None, *, access_token: Optional[str] = None,
|
|
359
|
+
refresh_token: Optional[str] = None, on_tokens: Optional[TokenCallback] = None,
|
|
360
|
+
base_url: Optional[str] = None, timeout: float = 30.0, max_retries: int = 2,
|
|
361
|
+
http_client: Optional[httpx.AsyncClient] = None, default_headers: Optional[Mapping[str, str]] = None) -> None:
|
|
362
|
+
self._transport = AsyncTransport(api_key=api_key, access_token=access_token, refresh_token=refresh_token,
|
|
363
|
+
on_tokens=on_tokens, base_url=base_url, timeout=timeout,
|
|
364
|
+
max_retries=max_retries, http_client=http_client, default_headers=default_headers)
|
|
365
|
+
self._init_resources(self._transport)
|
|
366
|
+
self.activations = AsyncActivations(self._transport)
|
|
367
|
+
self.events = AsyncEvents(self._transport)
|
|
368
|
+
self.auth = AsyncAuth(self._transport)
|
|
369
|
+
|
|
370
|
+
def set_tokens(self, tokens: Mapping[str, Any]) -> None:
|
|
371
|
+
self._transport.set_tokens(tokens)
|
|
372
|
+
|
|
373
|
+
async def close(self) -> None:
|
|
374
|
+
await self._transport.close()
|
|
375
|
+
|
|
376
|
+
async def __aenter__(self) -> "AsyncNumberOTP":
|
|
377
|
+
return self
|
|
378
|
+
|
|
379
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
380
|
+
await self.close()
|