nolio 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.
- nolio-0.1.0/.gitignore +7 -0
- nolio-0.1.0/LICENSE +21 -0
- nolio-0.1.0/PKG-INFO +120 -0
- nolio-0.1.0/README.md +103 -0
- nolio-0.1.0/pyproject.toml +37 -0
- nolio-0.1.0/src/nolio/__init__.py +15 -0
- nolio-0.1.0/src/nolio/client.py +279 -0
- nolio-0.1.0/src/nolio/errors.py +16 -0
- nolio-0.1.0/src/nolio/webhooks.py +27 -0
- nolio-0.1.0/tests/test_client.py +256 -0
- nolio-0.1.0/tests/test_webhooks.py +32 -0
nolio-0.1.0/.gitignore
ADDED
nolio-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cubope
|
|
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.
|
nolio-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: nolio
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Cliente de Python para la API de WhatsApp de Nolio (nolio.pe)
|
|
5
|
+
Project-URL: Homepage, https://nolio.pe
|
|
6
|
+
Project-URL: Documentation, https://nolio.pe/docs
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Topic :: Communications :: Chat
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Requires-Dist: httpx>=0.27
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
15
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# nolio (Python)
|
|
19
|
+
|
|
20
|
+
Cliente de Python para la [API de WhatsApp de Nolio](https://nolio.pe/docs).
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install nolio
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from nolio import Nolio
|
|
28
|
+
|
|
29
|
+
nolio = Nolio(api_key="nolio_sk_...")
|
|
30
|
+
|
|
31
|
+
# Texto (dentro de la ventana de 24 horas) o plantilla aprobada
|
|
32
|
+
nolio.messages.send_text(from_="pn_...", to="+51987654321", body="Hola, ¿en qué te ayudamos?")
|
|
33
|
+
nolio.messages.send_template(from_="pn_...", to="+51987654321", name="pedido_en_camino", variables=["Ana", "A-102"])
|
|
34
|
+
|
|
35
|
+
# Todos los mensajes recibidos (sigue la paginación sola)
|
|
36
|
+
for message in nolio.messages.list(direction="inbound"):
|
|
37
|
+
print(message["from"], message["content"])
|
|
38
|
+
|
|
39
|
+
# Códigos OTP
|
|
40
|
+
nolio.verify.start("vsv_...", "+51987654321")
|
|
41
|
+
# Si el WhatsApp no le llega, reenvía por SMS (el servicio debe tener SMS activado)
|
|
42
|
+
nolio.verify.start("vsv_...", "+51987654321", channel="sms")
|
|
43
|
+
if nolio.verify.check("vsv_...", "+51987654321", "123456")["valid"]:
|
|
44
|
+
...
|
|
45
|
+
|
|
46
|
+
# Consumo del mes
|
|
47
|
+
summary = nolio.usage.summary()
|
|
48
|
+
print(summary["totals"]["messages"], summary["totals"]["meta_cost"])
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Los envíos llevan un `Idempotency-Key` automático (o el tuyo con `idempotency_key=`), así que los reintentos ante
|
|
52
|
+
errores 429 o 5xx no duplican mensajes. Los errores de la API llegan como `NolioError` con `type`, `message`,
|
|
53
|
+
`status_code` y `details`.
|
|
54
|
+
|
|
55
|
+
## Mensajes interactivos (sin plantilla)
|
|
56
|
+
|
|
57
|
+
Dentro de la ventana de 24 horas: botones, listas, enlaces, formularios (WhatsApp Flows) o pedir la ubicación.
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
nolio.messages.send_buttons(
|
|
61
|
+
from_="pn_...",
|
|
62
|
+
to="+51987654321",
|
|
63
|
+
body="¿Confirmas tu cita del lunes?",
|
|
64
|
+
buttons=[{"id": "si", "title": "Sí"}, {"id": "no", "title": "Cambiar hora"}],
|
|
65
|
+
)
|
|
66
|
+
nolio.messages.send_interactive(
|
|
67
|
+
from_="pn_...",
|
|
68
|
+
to="+51987654321",
|
|
69
|
+
interactive={
|
|
70
|
+
"type": "flow",
|
|
71
|
+
"body": "Completa tus datos",
|
|
72
|
+
"button": "Completar",
|
|
73
|
+
"flow_id": "123...",
|
|
74
|
+
"screen": "DATOS",
|
|
75
|
+
},
|
|
76
|
+
)
|
|
77
|
+
# La respuesta llega en el webhook message.received, en data["content"]["reply"]
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Llamadas
|
|
81
|
+
|
|
82
|
+
Con el complemento Llamadas, Nolio pasa la señalización WebRTC (SDP) entre tu aplicación y WhatsApp; el audio va
|
|
83
|
+
directo. Para atender desde el navegador, usa `@nolio/voice`.
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
# ¿Puedo llamar a este cliente? Si no, pídele permiso (dentro de la ventana de 24 horas)
|
|
87
|
+
permission = nolio.phone_numbers.call_permission("pn_...", "+51987654321")
|
|
88
|
+
if not permission["can_call"] and permission["can_request_permission"]:
|
|
89
|
+
nolio.phone_numbers.request_call_permission("pn_...", to="+51987654321", body="¿Podemos llamarte?")
|
|
90
|
+
|
|
91
|
+
# Llamar con tu oferta SDP; la respuesta de WhatsApp llega en el webhook call.status
|
|
92
|
+
call = nolio.calls.start(from_="pn_...", to="+51987654321", sdp=offer_sdp)
|
|
93
|
+
|
|
94
|
+
# Contestar una llamada entrante (webhook call.incoming) con tu respuesta SDP, y colgar
|
|
95
|
+
nolio.calls.accept("call_...", answer_sdp)
|
|
96
|
+
nolio.calls.terminate("call_...")
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Webhooks
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from nolio import WebhookSignatureError, construct_event
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def nolio_webhook(request):
|
|
106
|
+
try:
|
|
107
|
+
event = construct_event(WEBHOOK_SECRET, request.headers["Nolio-Signature"], request.body)
|
|
108
|
+
except WebhookSignatureError:
|
|
109
|
+
return HttpResponse(status=400)
|
|
110
|
+
if event["type"] == "message.received":
|
|
111
|
+
...
|
|
112
|
+
return HttpResponse(status=200)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Desarrollo
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
|
|
119
|
+
.venv/bin/pytest && .venv/bin/ruff check && .venv/bin/ruff format --check
|
|
120
|
+
```
|
nolio-0.1.0/README.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# nolio (Python)
|
|
2
|
+
|
|
3
|
+
Cliente de Python para la [API de WhatsApp de Nolio](https://nolio.pe/docs).
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install nolio
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from nolio import Nolio
|
|
11
|
+
|
|
12
|
+
nolio = Nolio(api_key="nolio_sk_...")
|
|
13
|
+
|
|
14
|
+
# Texto (dentro de la ventana de 24 horas) o plantilla aprobada
|
|
15
|
+
nolio.messages.send_text(from_="pn_...", to="+51987654321", body="Hola, ¿en qué te ayudamos?")
|
|
16
|
+
nolio.messages.send_template(from_="pn_...", to="+51987654321", name="pedido_en_camino", variables=["Ana", "A-102"])
|
|
17
|
+
|
|
18
|
+
# Todos los mensajes recibidos (sigue la paginación sola)
|
|
19
|
+
for message in nolio.messages.list(direction="inbound"):
|
|
20
|
+
print(message["from"], message["content"])
|
|
21
|
+
|
|
22
|
+
# Códigos OTP
|
|
23
|
+
nolio.verify.start("vsv_...", "+51987654321")
|
|
24
|
+
# Si el WhatsApp no le llega, reenvía por SMS (el servicio debe tener SMS activado)
|
|
25
|
+
nolio.verify.start("vsv_...", "+51987654321", channel="sms")
|
|
26
|
+
if nolio.verify.check("vsv_...", "+51987654321", "123456")["valid"]:
|
|
27
|
+
...
|
|
28
|
+
|
|
29
|
+
# Consumo del mes
|
|
30
|
+
summary = nolio.usage.summary()
|
|
31
|
+
print(summary["totals"]["messages"], summary["totals"]["meta_cost"])
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Los envíos llevan un `Idempotency-Key` automático (o el tuyo con `idempotency_key=`), así que los reintentos ante
|
|
35
|
+
errores 429 o 5xx no duplican mensajes. Los errores de la API llegan como `NolioError` con `type`, `message`,
|
|
36
|
+
`status_code` y `details`.
|
|
37
|
+
|
|
38
|
+
## Mensajes interactivos (sin plantilla)
|
|
39
|
+
|
|
40
|
+
Dentro de la ventana de 24 horas: botones, listas, enlaces, formularios (WhatsApp Flows) o pedir la ubicación.
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
nolio.messages.send_buttons(
|
|
44
|
+
from_="pn_...",
|
|
45
|
+
to="+51987654321",
|
|
46
|
+
body="¿Confirmas tu cita del lunes?",
|
|
47
|
+
buttons=[{"id": "si", "title": "Sí"}, {"id": "no", "title": "Cambiar hora"}],
|
|
48
|
+
)
|
|
49
|
+
nolio.messages.send_interactive(
|
|
50
|
+
from_="pn_...",
|
|
51
|
+
to="+51987654321",
|
|
52
|
+
interactive={
|
|
53
|
+
"type": "flow",
|
|
54
|
+
"body": "Completa tus datos",
|
|
55
|
+
"button": "Completar",
|
|
56
|
+
"flow_id": "123...",
|
|
57
|
+
"screen": "DATOS",
|
|
58
|
+
},
|
|
59
|
+
)
|
|
60
|
+
# La respuesta llega en el webhook message.received, en data["content"]["reply"]
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Llamadas
|
|
64
|
+
|
|
65
|
+
Con el complemento Llamadas, Nolio pasa la señalización WebRTC (SDP) entre tu aplicación y WhatsApp; el audio va
|
|
66
|
+
directo. Para atender desde el navegador, usa `@nolio/voice`.
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
# ¿Puedo llamar a este cliente? Si no, pídele permiso (dentro de la ventana de 24 horas)
|
|
70
|
+
permission = nolio.phone_numbers.call_permission("pn_...", "+51987654321")
|
|
71
|
+
if not permission["can_call"] and permission["can_request_permission"]:
|
|
72
|
+
nolio.phone_numbers.request_call_permission("pn_...", to="+51987654321", body="¿Podemos llamarte?")
|
|
73
|
+
|
|
74
|
+
# Llamar con tu oferta SDP; la respuesta de WhatsApp llega en el webhook call.status
|
|
75
|
+
call = nolio.calls.start(from_="pn_...", to="+51987654321", sdp=offer_sdp)
|
|
76
|
+
|
|
77
|
+
# Contestar una llamada entrante (webhook call.incoming) con tu respuesta SDP, y colgar
|
|
78
|
+
nolio.calls.accept("call_...", answer_sdp)
|
|
79
|
+
nolio.calls.terminate("call_...")
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Webhooks
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from nolio import WebhookSignatureError, construct_event
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def nolio_webhook(request):
|
|
89
|
+
try:
|
|
90
|
+
event = construct_event(WEBHOOK_SECRET, request.headers["Nolio-Signature"], request.body)
|
|
91
|
+
except WebhookSignatureError:
|
|
92
|
+
return HttpResponse(status=400)
|
|
93
|
+
if event["type"] == "message.received":
|
|
94
|
+
...
|
|
95
|
+
return HttpResponse(status=200)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Desarrollo
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
|
|
102
|
+
.venv/bin/pytest && .venv/bin/ruff check && .venv/bin/ruff format --check
|
|
103
|
+
```
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "nolio"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Cliente de Python para la API de WhatsApp de Nolio (nolio.pe)"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.10"
|
|
9
|
+
dependencies = ["httpx>=0.27"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Programming Language :: Python :: 3",
|
|
12
|
+
"Topic :: Communications :: Chat",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://nolio.pe"
|
|
17
|
+
Documentation = "https://nolio.pe/docs"
|
|
18
|
+
|
|
19
|
+
[project.optional-dependencies]
|
|
20
|
+
dev = ["pytest>=8", "ruff>=0.6"]
|
|
21
|
+
|
|
22
|
+
[build-system]
|
|
23
|
+
requires = ["hatchling>=1.27"]
|
|
24
|
+
build-backend = "hatchling.build"
|
|
25
|
+
|
|
26
|
+
[tool.hatch.build.targets.wheel]
|
|
27
|
+
packages = ["src/nolio"]
|
|
28
|
+
|
|
29
|
+
[tool.ruff]
|
|
30
|
+
line-length = 120
|
|
31
|
+
target-version = "py310"
|
|
32
|
+
|
|
33
|
+
[tool.ruff.lint]
|
|
34
|
+
select = ["E", "F", "I", "UP", "B"]
|
|
35
|
+
|
|
36
|
+
[tool.pytest.ini_options]
|
|
37
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Python client for Nolio's WhatsApp API (https://nolio.pe/docs)."""
|
|
2
|
+
|
|
3
|
+
from .client import DEFAULT_BASE_URL, Nolio
|
|
4
|
+
from .errors import NolioError, WebhookSignatureError
|
|
5
|
+
from .webhooks import construct_event, verify_signature
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"DEFAULT_BASE_URL",
|
|
9
|
+
"Nolio",
|
|
10
|
+
"NolioError",
|
|
11
|
+
"WebhookSignatureError",
|
|
12
|
+
"construct_event",
|
|
13
|
+
"verify_signature",
|
|
14
|
+
]
|
|
15
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
import uuid
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from .errors import NolioError
|
|
11
|
+
|
|
12
|
+
DEFAULT_BASE_URL = "https://nolio.pe/api/v1"
|
|
13
|
+
RETRY_STATUSES = {429, 500, 502, 503, 504}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _parse(response: httpx.Response) -> Any:
|
|
17
|
+
if response.status_code == 204 or not response.content:
|
|
18
|
+
return None
|
|
19
|
+
data = response.json()
|
|
20
|
+
if response.is_error:
|
|
21
|
+
error = data.get("error", {}) if isinstance(data, dict) else {}
|
|
22
|
+
raise NolioError(
|
|
23
|
+
error.get("message", f"HTTP {response.status_code}"),
|
|
24
|
+
type=error.get("type", "error"),
|
|
25
|
+
status_code=response.status_code,
|
|
26
|
+
details=error.get("details"),
|
|
27
|
+
)
|
|
28
|
+
return data
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Nolio:
|
|
32
|
+
"""Client for the Nolio API.
|
|
33
|
+
|
|
34
|
+
nolio = Nolio(api_key="nolio_sk_...")
|
|
35
|
+
message = nolio.messages.send_text(from_="pn_...", to="+51987654321", body="Hola")
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
api_key: str,
|
|
41
|
+
*,
|
|
42
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
43
|
+
timeout: float = 30.0,
|
|
44
|
+
max_retries: int = 2,
|
|
45
|
+
transport: httpx.BaseTransport | None = None,
|
|
46
|
+
):
|
|
47
|
+
if not api_key:
|
|
48
|
+
raise ValueError("api_key es obligatorio")
|
|
49
|
+
self.max_retries = max_retries
|
|
50
|
+
self._http = httpx.Client(
|
|
51
|
+
base_url=base_url.rstrip("/"),
|
|
52
|
+
headers={"Authorization": f"Bearer {api_key}", "User-Agent": "nolio-python/0.1.0"},
|
|
53
|
+
timeout=timeout,
|
|
54
|
+
transport=transport,
|
|
55
|
+
)
|
|
56
|
+
self.messages = Messages(self)
|
|
57
|
+
self.calls = Calls(self)
|
|
58
|
+
self.media = Media(self)
|
|
59
|
+
self.phone_numbers = PhoneNumbers(self)
|
|
60
|
+
self.templates = Templates(self)
|
|
61
|
+
self.verify = Verify(self)
|
|
62
|
+
self.usage = Usage(self)
|
|
63
|
+
self.webhooks = Webhooks(self)
|
|
64
|
+
|
|
65
|
+
def close(self) -> None:
|
|
66
|
+
self._http.close()
|
|
67
|
+
|
|
68
|
+
def request(self, method: str, path: str, *, json: Any = None, params: dict | None = None, headers=None) -> Any:
|
|
69
|
+
"""Send a request, retrying rate limits and server errors (safe: sends carry an Idempotency-Key)."""
|
|
70
|
+
params = {key: value for key, value in (params or {}).items() if value is not None}
|
|
71
|
+
for attempt in range(self.max_retries + 1):
|
|
72
|
+
try:
|
|
73
|
+
response = self._http.request(method, path, json=json, params=params, headers=headers)
|
|
74
|
+
except httpx.TransportError as exc:
|
|
75
|
+
if attempt < self.max_retries:
|
|
76
|
+
time.sleep(0.5 * 2**attempt)
|
|
77
|
+
continue
|
|
78
|
+
raise NolioError(f"No se pudo conectar con Nolio: {exc}", type="connection_error") from exc
|
|
79
|
+
if response.status_code in RETRY_STATUSES and attempt < self.max_retries:
|
|
80
|
+
time.sleep(float(response.headers.get("Retry-After", 0.5 * 2**attempt)))
|
|
81
|
+
continue
|
|
82
|
+
return _parse(response)
|
|
83
|
+
raise AssertionError("unreachable")
|
|
84
|
+
|
|
85
|
+
def paginate(self, path: str, params: dict | None = None) -> Iterator[dict]:
|
|
86
|
+
"""Iterate every result of a list endpoint, following the cursor."""
|
|
87
|
+
params = dict(params or {})
|
|
88
|
+
while True:
|
|
89
|
+
page = self.request("GET", path, params=params)
|
|
90
|
+
yield from page["results"]
|
|
91
|
+
if not page.get("next"):
|
|
92
|
+
return
|
|
93
|
+
params["cursor"] = httpx.URL(page["next"]).params.get("cursor")
|
|
94
|
+
|
|
95
|
+
def __enter__(self):
|
|
96
|
+
return self
|
|
97
|
+
|
|
98
|
+
def __exit__(self, *exc):
|
|
99
|
+
self.close()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class _Resource:
|
|
103
|
+
def __init__(self, client: Nolio):
|
|
104
|
+
self._client = client
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class Messages(_Resource):
|
|
108
|
+
def send(self, *, from_: str, to: str, type: str, content: dict, idempotency_key: str | None = None, **extra):
|
|
109
|
+
"""Send any message type: `content` is the object for that type (e.g. `{"body": "Hola"}` for text)."""
|
|
110
|
+
body = {"from": from_, "to": to, "type": type, type: content, **extra}
|
|
111
|
+
headers = {"Idempotency-Key": idempotency_key or str(uuid.uuid4())}
|
|
112
|
+
return self._client.request("POST", "/messages", json=body, headers=headers)
|
|
113
|
+
|
|
114
|
+
def send_text(self, *, from_: str, to: str, body: str, **kwargs):
|
|
115
|
+
return self.send(from_=from_, to=to, type="text", content={"body": body}, **kwargs)
|
|
116
|
+
|
|
117
|
+
def send_template(
|
|
118
|
+
self,
|
|
119
|
+
*,
|
|
120
|
+
from_: str,
|
|
121
|
+
to: str,
|
|
122
|
+
name: str,
|
|
123
|
+
language: str = "es",
|
|
124
|
+
variables=None,
|
|
125
|
+
header: dict | None = None,
|
|
126
|
+
buttons: list[dict] | None = None,
|
|
127
|
+
**kwargs,
|
|
128
|
+
):
|
|
129
|
+
"""Send an approved template.
|
|
130
|
+
|
|
131
|
+
`header`: e.g. {"type": "image", "url": ...}; `buttons`: e.g. [{"index": 0, "type": "url", "text": "A-1"}].
|
|
132
|
+
"""
|
|
133
|
+
content = {"name": name, "language": language}
|
|
134
|
+
if variables:
|
|
135
|
+
content["variables"] = [str(value) for value in variables]
|
|
136
|
+
if header:
|
|
137
|
+
content["header"] = header
|
|
138
|
+
if buttons:
|
|
139
|
+
content["buttons"] = buttons
|
|
140
|
+
return self.send(from_=from_, to=to, type="template", content=content, **kwargs)
|
|
141
|
+
|
|
142
|
+
def send_media(self, *, from_: str, to: str, type: str, url: str, caption: str | None = None, **kwargs):
|
|
143
|
+
content = {"url": url, **({"caption": caption} if caption else {})}
|
|
144
|
+
return self.send(from_=from_, to=to, type=type, content=content, **kwargs)
|
|
145
|
+
|
|
146
|
+
def send_interactive(self, *, from_: str, to: str, interactive: dict, **kwargs):
|
|
147
|
+
"""Buttons, a list, a link, a form (WhatsApp Flow) or a location request, inside the 24-hour window.
|
|
148
|
+
|
|
149
|
+
`interactive`: e.g. {"type": "list", "body": "...", "button": "Ver", "sections": [{"rows": [...]}]}.
|
|
150
|
+
"""
|
|
151
|
+
return self.send(from_=from_, to=to, type="interactive", content=interactive, **kwargs)
|
|
152
|
+
|
|
153
|
+
def send_buttons(self, *, from_: str, to: str, body: str, buttons: list[dict], footer: str | None = None, **kwargs):
|
|
154
|
+
"""Up to 3 reply buttons: buttons=[{"id": "si", "title": "Sí"}]."""
|
|
155
|
+
interactive = {"type": "button", "body": body, "buttons": buttons, **({"footer": footer} if footer else {})}
|
|
156
|
+
return self.send_interactive(from_=from_, to=to, interactive=interactive, **kwargs)
|
|
157
|
+
|
|
158
|
+
def get(self, message_id: str):
|
|
159
|
+
return self._client.request("GET", f"/messages/{message_id}")
|
|
160
|
+
|
|
161
|
+
def list(self, **filters) -> Iterator[dict]:
|
|
162
|
+
return self._client.paginate("/messages", filters)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class Media(_Resource):
|
|
166
|
+
def get(self, media_id: str):
|
|
167
|
+
"""The file's metadata and a signed URL valid for one hour."""
|
|
168
|
+
return self._client.request("GET", f"/media/{media_id}")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class PhoneNumbers(_Resource):
|
|
172
|
+
def list(self) -> Iterator[dict]:
|
|
173
|
+
return self._client.paginate("/phone-numbers")
|
|
174
|
+
|
|
175
|
+
def get(self, phone_number_id: str):
|
|
176
|
+
return self._client.request("GET", f"/phone-numbers/{phone_number_id}")
|
|
177
|
+
|
|
178
|
+
def update_calling(self, phone_number_id: str, settings: dict):
|
|
179
|
+
"""Calling settings in Meta's format, e.g. {"status": "ENABLED"} (needs the calls add-on)."""
|
|
180
|
+
return self._client.request("PATCH", f"/phone-numbers/{phone_number_id}/calling", json=settings)
|
|
181
|
+
|
|
182
|
+
def call_permission(self, phone_number_id: str, to: str) -> dict:
|
|
183
|
+
"""Whether you can call `to` now or ask for permission."""
|
|
184
|
+
return self._client.request("GET", f"/phone-numbers/{phone_number_id}/call-permissions", params={"to": to})
|
|
185
|
+
|
|
186
|
+
def request_call_permission(self, phone_number_id: str, *, to: str, body: str, idempotency_key=None):
|
|
187
|
+
"""Ask `to` for permission to call them (a message, inside the 24-hour window)."""
|
|
188
|
+
return self._client.request(
|
|
189
|
+
"POST",
|
|
190
|
+
f"/phone-numbers/{phone_number_id}/call-permissions",
|
|
191
|
+
json={"to": to, "body": body},
|
|
192
|
+
headers={"Idempotency-Key": idempotency_key or str(uuid.uuid4())},
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class Calls(_Resource):
|
|
197
|
+
"""WhatsApp voice calls. Nolio relays the WebRTC signaling (SDP); the audio goes straight to WhatsApp."""
|
|
198
|
+
|
|
199
|
+
def list(self, **filters) -> Iterator[dict]:
|
|
200
|
+
return self._client.paginate("/calls", filters)
|
|
201
|
+
|
|
202
|
+
def get(self, call_id: str):
|
|
203
|
+
return self._client.request("GET", f"/calls/{call_id}")
|
|
204
|
+
|
|
205
|
+
def start(self, *, from_: str, to: str, sdp: str, biz_opaque_callback_data: str | None = None):
|
|
206
|
+
"""Call a customer who gave permission with your SDP offer; WhatsApp's answer arrives in `call.status`."""
|
|
207
|
+
body = {"from": from_, "to": to, "session": {"sdp_type": "offer", "sdp": sdp}}
|
|
208
|
+
if biz_opaque_callback_data:
|
|
209
|
+
body["biz_opaque_callback_data"] = biz_opaque_callback_data
|
|
210
|
+
return self._client.request("POST", "/calls", json=body)
|
|
211
|
+
|
|
212
|
+
def pre_accept(self, call_id: str, sdp: str):
|
|
213
|
+
"""Optional: send your SDP answer early so audio connects as soon as you accept."""
|
|
214
|
+
body = {"session": {"sdp_type": "answer", "sdp": sdp}}
|
|
215
|
+
return self._client.request("POST", f"/calls/{call_id}/pre_accept", json=body)
|
|
216
|
+
|
|
217
|
+
def accept(self, call_id: str, sdp: str, *, biz_opaque_callback_data: str | None = None):
|
|
218
|
+
body = {"session": {"sdp_type": "answer", "sdp": sdp}}
|
|
219
|
+
if biz_opaque_callback_data:
|
|
220
|
+
body["biz_opaque_callback_data"] = biz_opaque_callback_data
|
|
221
|
+
return self._client.request("POST", f"/calls/{call_id}/accept", json=body)
|
|
222
|
+
|
|
223
|
+
def reject(self, call_id: str):
|
|
224
|
+
return self._client.request("POST", f"/calls/{call_id}/reject", json={})
|
|
225
|
+
|
|
226
|
+
def terminate(self, call_id: str):
|
|
227
|
+
return self._client.request("POST", f"/calls/{call_id}/terminate", json={})
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class Templates(_Resource):
|
|
231
|
+
def list(self, **filters) -> Iterator[dict]:
|
|
232
|
+
return self._client.paginate("/templates", filters)
|
|
233
|
+
|
|
234
|
+
def create(self, *, name: str, language: str, category: str, components: list[dict], phone_number=None):
|
|
235
|
+
body = {"name": name, "language": language, "category": category, "components": components}
|
|
236
|
+
if phone_number:
|
|
237
|
+
body["phone_number"] = phone_number
|
|
238
|
+
return self._client.request("POST", "/templates", json=body)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class Verify(_Resource):
|
|
242
|
+
def start(self, service_id: str, to: str, channel: str | None = None):
|
|
243
|
+
"""Send a one-time code to `to`. `channel` is "whatsapp" (default) or "sms" (the service must allow it)."""
|
|
244
|
+
body = {"to": to, **({"channel": channel} if channel else {})}
|
|
245
|
+
return self._client.request("POST", f"/verify/services/{service_id}/verifications", json=body)
|
|
246
|
+
|
|
247
|
+
def check(self, service_id: str, to: str, code: str) -> dict:
|
|
248
|
+
"""Check a code; the result's `valid` is True when it's right."""
|
|
249
|
+
return self._client.request("POST", f"/verify/services/{service_id}/checks", json={"to": to, "code": code})
|
|
250
|
+
|
|
251
|
+
def cancel(self, verification_id: str):
|
|
252
|
+
return self._client.request("POST", f"/verify/verifications/{verification_id}/cancel")
|
|
253
|
+
|
|
254
|
+
def services(self) -> Iterator[dict]:
|
|
255
|
+
return self._client.paginate("/verify/services")
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
class Usage(_Resource):
|
|
259
|
+
def summary(self, *, start_date=None, end_date=None, phone_number=None):
|
|
260
|
+
params = {"start_date": start_date, "end_date": end_date, "phone_number": phone_number}
|
|
261
|
+
return self._client.request(
|
|
262
|
+
"GET", "/usage/summary", params={k: str(v) if v else None for k, v in params.items()}
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
def records(self, **filters) -> Iterator[dict]:
|
|
266
|
+
return self._client.paginate("/usage/records", {k: str(v) for k, v in filters.items() if v is not None})
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class Webhooks(_Resource):
|
|
270
|
+
def list(self) -> Iterator[dict]:
|
|
271
|
+
return self._client.paginate("/webhooks")
|
|
272
|
+
|
|
273
|
+
def create(self, *, url: str, events: list[str] | None = None, description: str = ""):
|
|
274
|
+
"""The response includes the signing `secret`, shown only once."""
|
|
275
|
+
body = {"url": url, "events": events or ["*"], "description": description}
|
|
276
|
+
return self._client.request("POST", "/webhooks", json=body)
|
|
277
|
+
|
|
278
|
+
def delete(self, webhook_id: str) -> None:
|
|
279
|
+
self._client.request("DELETE", f"/webhooks/{webhook_id}")
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
class NolioError(Exception):
|
|
2
|
+
"""An error response from the Nolio API (`{"error": {"type", "message", "details"}}`)."""
|
|
3
|
+
|
|
4
|
+
def __init__(self, message: str, *, type: str = "error", status_code: int | None = None, details=None):
|
|
5
|
+
super().__init__(message)
|
|
6
|
+
self.message = message
|
|
7
|
+
self.type = type
|
|
8
|
+
self.status_code = status_code
|
|
9
|
+
self.details = details
|
|
10
|
+
|
|
11
|
+
def __repr__(self) -> str:
|
|
12
|
+
return f"NolioError(type={self.type!r}, status_code={self.status_code!r}, message={self.message!r})"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class WebhookSignatureError(Exception):
|
|
16
|
+
"""The `Nolio-Signature` header doesn't match the body, or is too old."""
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
from .errors import WebhookSignatureError
|
|
7
|
+
|
|
8
|
+
DEFAULT_TOLERANCE = 300
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def verify_signature(secret: str, header: str, body: bytes, *, tolerance: int = DEFAULT_TOLERANCE) -> bool:
|
|
12
|
+
"""True if `Nolio-Signature` (`t=...,v1=...`) is the HMAC-SHA256 of `"{t}.{body}"` and isn't too old."""
|
|
13
|
+
try:
|
|
14
|
+
parts = dict(item.split("=", 1) for item in header.split(","))
|
|
15
|
+
timestamp = int(parts["t"])
|
|
16
|
+
signature = parts["v1"]
|
|
17
|
+
except (KeyError, ValueError):
|
|
18
|
+
return False
|
|
19
|
+
expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
|
|
20
|
+
return hmac.compare_digest(expected, signature) and abs(time.time() - timestamp) <= tolerance
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def construct_event(secret: str, header: str, body: bytes, *, tolerance: int = DEFAULT_TOLERANCE) -> dict:
|
|
24
|
+
"""Check the signature and return the parsed event, or raise WebhookSignatureError."""
|
|
25
|
+
if not verify_signature(secret, header, body, tolerance=tolerance):
|
|
26
|
+
raise WebhookSignatureError("Firma de webhook inválida o vencida.")
|
|
27
|
+
return json.loads(body)
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from nolio import Nolio, NolioError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def client_with(handler, **kwargs):
|
|
10
|
+
return Nolio(api_key="nolio_sk_test", transport=httpx.MockTransport(handler), **kwargs)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_requires_an_api_key():
|
|
14
|
+
with pytest.raises(ValueError):
|
|
15
|
+
Nolio(api_key="")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def test_send_text_with_idempotency_key():
|
|
19
|
+
seen = {}
|
|
20
|
+
|
|
21
|
+
def handler(request: httpx.Request):
|
|
22
|
+
seen["request"] = request
|
|
23
|
+
return httpx.Response(201, json={"id": "msg_1", "status": "queued"})
|
|
24
|
+
|
|
25
|
+
with client_with(handler) as nolio:
|
|
26
|
+
message = nolio.messages.send_text(from_="pn_1", to="+51987654321", body="Hola", idempotency_key="k-1")
|
|
27
|
+
|
|
28
|
+
request = seen["request"]
|
|
29
|
+
assert message == {"id": "msg_1", "status": "queued"}
|
|
30
|
+
assert request.url == "https://nolio.pe/api/v1/messages"
|
|
31
|
+
assert request.headers["Authorization"] == "Bearer nolio_sk_test"
|
|
32
|
+
assert request.headers["Idempotency-Key"] == "k-1"
|
|
33
|
+
assert json.loads(request.content) == {
|
|
34
|
+
"from": "pn_1",
|
|
35
|
+
"to": "+51987654321",
|
|
36
|
+
"type": "text",
|
|
37
|
+
"text": {"body": "Hola"},
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_send_template_and_media_generate_keys():
|
|
42
|
+
bodies, keys = [], []
|
|
43
|
+
|
|
44
|
+
def handler(request):
|
|
45
|
+
bodies.append(json.loads(request.content))
|
|
46
|
+
keys.append(request.headers["Idempotency-Key"])
|
|
47
|
+
return httpx.Response(201, json={"id": "msg"})
|
|
48
|
+
|
|
49
|
+
nolio = client_with(handler)
|
|
50
|
+
nolio.messages.send_template(
|
|
51
|
+
from_="pn_1",
|
|
52
|
+
to="+51911",
|
|
53
|
+
name="pedido",
|
|
54
|
+
variables=["A-1", 2],
|
|
55
|
+
header={"type": "image", "url": "https://x.pe/p.png"},
|
|
56
|
+
buttons=[{"index": 0, "type": "url", "text": "A-1"}],
|
|
57
|
+
)
|
|
58
|
+
nolio.messages.send_media(from_="pn_1", to="+51911", type="image", url="https://x.pe/a.png", caption="Foto")
|
|
59
|
+
nolio.messages.send_media(from_="pn_1", to="+51911", type="document", url="https://x.pe/a.pdf")
|
|
60
|
+
|
|
61
|
+
assert bodies[0]["template"] == {
|
|
62
|
+
"name": "pedido",
|
|
63
|
+
"language": "es",
|
|
64
|
+
"variables": ["A-1", "2"],
|
|
65
|
+
"header": {"type": "image", "url": "https://x.pe/p.png"},
|
|
66
|
+
"buttons": [{"index": 0, "type": "url", "text": "A-1"}],
|
|
67
|
+
}
|
|
68
|
+
assert bodies[1]["image"] == {"url": "https://x.pe/a.png", "caption": "Foto"}
|
|
69
|
+
assert bodies[2]["document"] == {"url": "https://x.pe/a.pdf"}
|
|
70
|
+
assert len(set(keys)) == 3
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_errors_carry_the_api_error():
|
|
74
|
+
def handler(request):
|
|
75
|
+
return httpx.Response(
|
|
76
|
+
400,
|
|
77
|
+
json={
|
|
78
|
+
"error": {"type": "invalid_request", "message": "La petición no es válida.", "details": {"to": ["x"]}}
|
|
79
|
+
},
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
with pytest.raises(NolioError) as raised:
|
|
83
|
+
client_with(handler).messages.get("msg_1")
|
|
84
|
+
error = raised.value
|
|
85
|
+
assert (error.type, error.status_code, error.details) == ("invalid_request", 400, {"to": ["x"]})
|
|
86
|
+
assert "invalid_request" in repr(error)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_errors_without_body_shape():
|
|
90
|
+
with pytest.raises(NolioError) as raised:
|
|
91
|
+
client_with(lambda request: httpx.Response(500, json=["boom"]), max_retries=0).messages.get("msg_1")
|
|
92
|
+
assert raised.value.message == "HTTP 500"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def test_retries_rate_limits_and_server_errors(monkeypatch):
|
|
96
|
+
monkeypatch.setattr("nolio.client.time.sleep", lambda seconds: None)
|
|
97
|
+
responses = iter(
|
|
98
|
+
[httpx.Response(429, headers={"Retry-After": "0"}), httpx.Response(503), httpx.Response(200, json={"ok": True})]
|
|
99
|
+
)
|
|
100
|
+
assert client_with(lambda request: next(responses)).messages.get("msg_1") == {"ok": True}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def test_connection_errors(monkeypatch):
|
|
104
|
+
monkeypatch.setattr("nolio.client.time.sleep", lambda seconds: None)
|
|
105
|
+
calls = []
|
|
106
|
+
|
|
107
|
+
def handler(request):
|
|
108
|
+
calls.append(1)
|
|
109
|
+
raise httpx.ConnectError("down")
|
|
110
|
+
|
|
111
|
+
with pytest.raises(NolioError) as raised:
|
|
112
|
+
client_with(handler, max_retries=1).messages.get("msg_1")
|
|
113
|
+
assert raised.value.type == "connection_error"
|
|
114
|
+
assert len(calls) == 2
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def test_list_follows_the_cursor():
|
|
118
|
+
pages = {
|
|
119
|
+
None: {"next": "https://nolio.pe/api/v1/messages?cursor=abc&direction=inbound", "results": [{"id": "msg_1"}]},
|
|
120
|
+
"abc": {"next": None, "results": [{"id": "msg_2"}]},
|
|
121
|
+
}
|
|
122
|
+
seen = []
|
|
123
|
+
|
|
124
|
+
def handler(request):
|
|
125
|
+
seen.append(dict(request.url.params))
|
|
126
|
+
return httpx.Response(200, json=pages[request.url.params.get("cursor")])
|
|
127
|
+
|
|
128
|
+
ids = [message["id"] for message in client_with(handler).messages.list(direction="inbound", status=None)]
|
|
129
|
+
assert ids == ["msg_1", "msg_2"]
|
|
130
|
+
assert seen == [{"direction": "inbound"}, {"direction": "inbound", "cursor": "abc"}]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def test_verify_start_sends_the_channel_only_when_given():
|
|
134
|
+
bodies = []
|
|
135
|
+
|
|
136
|
+
def handler(request):
|
|
137
|
+
bodies.append(json.loads(request.content))
|
|
138
|
+
return httpx.Response(200, json={"ok": True})
|
|
139
|
+
|
|
140
|
+
nolio = client_with(handler)
|
|
141
|
+
nolio.verify.start("vsv_1", "+51911")
|
|
142
|
+
nolio.verify.start("vsv_1", "+51911", channel="sms")
|
|
143
|
+
assert bodies == [{"to": "+51911"}, {"to": "+51911", "channel": "sms"}]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def test_verify_usage_and_webhooks():
|
|
147
|
+
calls = []
|
|
148
|
+
|
|
149
|
+
def handler(request):
|
|
150
|
+
calls.append(
|
|
151
|
+
(
|
|
152
|
+
request.method,
|
|
153
|
+
request.url.path,
|
|
154
|
+
request.content and json.loads(request.content),
|
|
155
|
+
dict(request.url.params),
|
|
156
|
+
)
|
|
157
|
+
)
|
|
158
|
+
if request.method == "DELETE":
|
|
159
|
+
return httpx.Response(204)
|
|
160
|
+
if request.url.path.endswith("/checks"):
|
|
161
|
+
return httpx.Response(200, json={"valid": True, "status": "approved"})
|
|
162
|
+
if (
|
|
163
|
+
request.method == "GET"
|
|
164
|
+
and "summary" not in request.url.path
|
|
165
|
+
and "/media/" not in request.url.path
|
|
166
|
+
and "/phone-numbers/" not in request.url.path
|
|
167
|
+
):
|
|
168
|
+
return httpx.Response(200, json={"next": None, "results": []})
|
|
169
|
+
return httpx.Response(200, json={"ok": True})
|
|
170
|
+
|
|
171
|
+
nolio = client_with(handler)
|
|
172
|
+
nolio.verify.start("vsv_1", "+51911")
|
|
173
|
+
assert nolio.verify.check("vsv_1", "+51911", "123456")["valid"] is True
|
|
174
|
+
nolio.verify.cancel("ver_1")
|
|
175
|
+
assert list(nolio.verify.services()) == []
|
|
176
|
+
nolio.usage.summary(start_date="2026-11-01")
|
|
177
|
+
assert list(nolio.usage.records(country="PE", category=None)) == []
|
|
178
|
+
nolio.webhooks.create(url="https://x.pe/hook")
|
|
179
|
+
assert list(nolio.webhooks.list()) == []
|
|
180
|
+
assert nolio.webhooks.delete("whk_1") is None
|
|
181
|
+
nolio.media.get("med_1")
|
|
182
|
+
nolio.phone_numbers.get("pn_1")
|
|
183
|
+
assert list(nolio.phone_numbers.list()) == []
|
|
184
|
+
assert list(nolio.templates.list(status="APPROVED")) == []
|
|
185
|
+
nolio.templates.create(name="t", language="es", category="UTILITY", components=[], phone_number="pn_1")
|
|
186
|
+
|
|
187
|
+
assert calls[0][:3] == ("POST", "/api/v1/verify/services/vsv_1/verifications", {"to": "+51911"})
|
|
188
|
+
assert calls[4][3] == {"start_date": "2026-11-01"}
|
|
189
|
+
assert calls[5][3] == {"country": "PE"}
|
|
190
|
+
assert calls[6][2] == {"url": "https://x.pe/hook", "events": ["*"], "description": ""}
|
|
191
|
+
assert calls[-1][2]["phone_number"] == "pn_1"
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def test_calls_and_call_permissions():
|
|
195
|
+
seen = []
|
|
196
|
+
|
|
197
|
+
def handler(request: httpx.Request):
|
|
198
|
+
seen.append(request)
|
|
199
|
+
if request.url.path.endswith("/call-permissions") and request.method == "GET":
|
|
200
|
+
return httpx.Response(200, json={"to": "+51911", "status": "granted", "can_call": True})
|
|
201
|
+
return httpx.Response(200, json={"id": "call_1"})
|
|
202
|
+
|
|
203
|
+
nolio = client_with(handler)
|
|
204
|
+
nolio.calls.start(from_="pn_1", to="+51911", sdp="offer-sdp", biz_opaque_callback_data="lead-9")
|
|
205
|
+
nolio.calls.pre_accept("call_1", "answer-sdp")
|
|
206
|
+
nolio.calls.accept("call_1", "answer-sdp")
|
|
207
|
+
nolio.calls.reject("call_1")
|
|
208
|
+
nolio.calls.terminate("call_1")
|
|
209
|
+
nolio.calls.get("call_1")
|
|
210
|
+
assert nolio.phone_numbers.call_permission("pn_1", "+51911")["can_call"] is True
|
|
211
|
+
nolio.phone_numbers.request_call_permission("pn_1", to="+51911", body="¿Podemos llamarte?", idempotency_key="p-1")
|
|
212
|
+
nolio.phone_numbers.update_calling("pn_1", {"status": "ENABLED"})
|
|
213
|
+
|
|
214
|
+
assert [f"{r.method} {r.url.path}" for r in seen] == [
|
|
215
|
+
"POST /api/v1/calls",
|
|
216
|
+
"POST /api/v1/calls/call_1/pre_accept",
|
|
217
|
+
"POST /api/v1/calls/call_1/accept",
|
|
218
|
+
"POST /api/v1/calls/call_1/reject",
|
|
219
|
+
"POST /api/v1/calls/call_1/terminate",
|
|
220
|
+
"GET /api/v1/calls/call_1",
|
|
221
|
+
"GET /api/v1/phone-numbers/pn_1/call-permissions",
|
|
222
|
+
"POST /api/v1/phone-numbers/pn_1/call-permissions",
|
|
223
|
+
"PATCH /api/v1/phone-numbers/pn_1/calling",
|
|
224
|
+
]
|
|
225
|
+
assert json.loads(seen[0].content) == {
|
|
226
|
+
"from": "pn_1",
|
|
227
|
+
"to": "+51911",
|
|
228
|
+
"session": {"sdp_type": "offer", "sdp": "offer-sdp"},
|
|
229
|
+
"biz_opaque_callback_data": "lead-9",
|
|
230
|
+
}
|
|
231
|
+
assert json.loads(seen[2].content) == {"session": {"sdp_type": "answer", "sdp": "answer-sdp"}}
|
|
232
|
+
assert seen[6].url.params["to"] == "+51911"
|
|
233
|
+
assert json.loads(seen[7].content) == {"to": "+51911", "body": "¿Podemos llamarte?"}
|
|
234
|
+
assert seen[7].headers["Idempotency-Key"] == "p-1"
|
|
235
|
+
assert json.loads(seen[8].content) == {"status": "ENABLED"}
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def test_interactive_messages():
|
|
239
|
+
bodies = []
|
|
240
|
+
|
|
241
|
+
def handler(request):
|
|
242
|
+
bodies.append(json.loads(request.content))
|
|
243
|
+
return httpx.Response(201, json={"id": "msg_1"})
|
|
244
|
+
|
|
245
|
+
nolio = client_with(handler)
|
|
246
|
+
nolio.messages.send_buttons(from_="pn_1", to="+51911", body="¿Confirmas?", buttons=[{"id": "si", "title": "Sí"}])
|
|
247
|
+
nolio.messages.send_interactive(
|
|
248
|
+
from_="pn_1", to="+51911", interactive={"type": "location_request", "body": "¿A dónde enviamos?"}
|
|
249
|
+
)
|
|
250
|
+
assert bodies[0] == {
|
|
251
|
+
"from": "pn_1",
|
|
252
|
+
"to": "+51911",
|
|
253
|
+
"type": "interactive",
|
|
254
|
+
"interactive": {"type": "button", "body": "¿Confirmas?", "buttons": [{"id": "si", "title": "Sí"}]},
|
|
255
|
+
}
|
|
256
|
+
assert bodies[1]["interactive"] == {"type": "location_request", "body": "¿A dónde enviamos?"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from nolio import WebhookSignatureError, construct_event, verify_signature
|
|
9
|
+
|
|
10
|
+
SECRET = "whsec_test"
|
|
11
|
+
BODY = json.dumps({"id": "evt_1", "type": "message.status"}).encode()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def header(timestamp=None, body=BODY, secret=SECRET):
|
|
15
|
+
timestamp = timestamp or int(time.time())
|
|
16
|
+
digest = hmac.new(secret.encode(), f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
|
|
17
|
+
return f"t={timestamp},v1={digest}"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_valid_signature():
|
|
21
|
+
assert verify_signature(SECRET, header(), BODY)
|
|
22
|
+
assert construct_event(SECRET, header(), BODY)["id"] == "evt_1"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_invalid_signatures():
|
|
26
|
+
assert not verify_signature("other", header(), BODY)
|
|
27
|
+
assert not verify_signature(SECRET, header(), BODY + b" ")
|
|
28
|
+
assert not verify_signature(SECRET, header(timestamp=int(time.time()) - 600), BODY)
|
|
29
|
+
assert not verify_signature(SECRET, "garbage", BODY)
|
|
30
|
+
assert not verify_signature(SECRET, "t=abc,v1=x", BODY)
|
|
31
|
+
with pytest.raises(WebhookSignatureError):
|
|
32
|
+
construct_event(SECRET, "t=1,v1=x", BODY)
|