reachflow 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
reachflow/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ """Client officiel Python pour l'API publique ReachFlow."""
2
+
3
+ from reachflow.client import ReachFlow, AsyncReachFlow
4
+ from reachflow.errors import ReachFlowError
5
+ from reachflow.types import (
6
+ DEFAULT_BASE_URL,
7
+ TERMINAL_MESSAGE_STATUSES,
8
+ MessageStatus,
9
+ MediaType,
10
+ )
11
+
12
+ __all__ = [
13
+ "ReachFlow",
14
+ "AsyncReachFlow",
15
+ "ReachFlowError",
16
+ "DEFAULT_BASE_URL",
17
+ "TERMINAL_MESSAGE_STATUSES",
18
+ "MessageStatus",
19
+ "MediaType",
20
+ ]
21
+
22
+ __version__ = "0.1.0"
reachflow/client.py ADDED
@@ -0,0 +1,113 @@
1
+ from __future__ import annotations
2
+
3
+ from types import TracebackType
4
+
5
+ import httpx
6
+
7
+ from reachflow.http import (
8
+ AsyncHttpClient,
9
+ ClientConfig,
10
+ HttpClient,
11
+ resolve_config,
12
+ )
13
+ from reachflow.resources.messages import AsyncMessagesResource, MessagesResource
14
+ from reachflow.resources.otp import AsyncOtpResource, OtpResource
15
+ from reachflow.resources.providers import AsyncProvidersResource, ProvidersResource
16
+
17
+
18
+ class ReachFlow:
19
+ """Client synchrone pour l'API publique ReachFlow (REST v1)."""
20
+
21
+ def __init__(
22
+ self,
23
+ *,
24
+ api_key: str,
25
+ base_url: str | None = None,
26
+ timeout_ms: int = 30_000,
27
+ max_retries: int = 2,
28
+ http_client: httpx.Client | None = None,
29
+ ) -> None:
30
+ if not api_key or not api_key.strip():
31
+ raise ValueError("ReachFlow: api_key is required")
32
+
33
+ self._config: ClientConfig = resolve_config(
34
+ api_key=api_key,
35
+ base_url=base_url,
36
+ timeout_ms=timeout_ms,
37
+ max_retries=max_retries,
38
+ )
39
+ self._owns_client = http_client is None
40
+ self._httpx = http_client or httpx.Client()
41
+ self._http = HttpClient(self._config, self._httpx)
42
+
43
+ self.messages = MessagesResource(self._http)
44
+ self.providers = ProvidersResource(self._http)
45
+ self.otp = OtpResource(self._http)
46
+
47
+ @property
48
+ def base_url(self) -> str:
49
+ return self._config.base_url
50
+
51
+ def close(self) -> None:
52
+ if self._owns_client:
53
+ self._httpx.close()
54
+
55
+ def __enter__(self) -> ReachFlow:
56
+ return self
57
+
58
+ def __exit__(
59
+ self,
60
+ exc_type: type[BaseException] | None,
61
+ exc: BaseException | None,
62
+ tb: TracebackType | None,
63
+ ) -> None:
64
+ self.close()
65
+
66
+
67
+ class AsyncReachFlow:
68
+ """Client asynchrone pour l'API publique ReachFlow (REST v1)."""
69
+
70
+ def __init__(
71
+ self,
72
+ *,
73
+ api_key: str,
74
+ base_url: str | None = None,
75
+ timeout_ms: int = 30_000,
76
+ max_retries: int = 2,
77
+ http_client: httpx.AsyncClient | None = None,
78
+ ) -> None:
79
+ if not api_key or not api_key.strip():
80
+ raise ValueError("ReachFlow: api_key is required")
81
+
82
+ self._config: ClientConfig = resolve_config(
83
+ api_key=api_key,
84
+ base_url=base_url,
85
+ timeout_ms=timeout_ms,
86
+ max_retries=max_retries,
87
+ )
88
+ self._owns_client = http_client is None
89
+ self._httpx = http_client or httpx.AsyncClient()
90
+ self._http = AsyncHttpClient(self._config, self._httpx)
91
+
92
+ self.messages = AsyncMessagesResource(self._http)
93
+ self.providers = AsyncProvidersResource(self._http)
94
+ self.otp = AsyncOtpResource(self._http)
95
+
96
+ @property
97
+ def base_url(self) -> str:
98
+ return self._config.base_url
99
+
100
+ async def close(self) -> None:
101
+ if self._owns_client:
102
+ await self._httpx.aclose()
103
+
104
+ async def __aenter__(self) -> AsyncReachFlow:
105
+ return self
106
+
107
+ async def __aexit__(
108
+ self,
109
+ exc_type: type[BaseException] | None,
110
+ exc: BaseException | None,
111
+ tb: TracebackType | None,
112
+ ) -> None:
113
+ await self.close()
reachflow/errors.py ADDED
@@ -0,0 +1,114 @@
1
+ from __future__ import annotations
2
+
3
+ from email.utils import parsedate_to_datetime
4
+ from typing import Any, Literal
5
+
6
+ ReachFlowErrorCode = Literal[
7
+ "unauthorized",
8
+ "plan_required",
9
+ "insufficient_scope",
10
+ "rate_limit_exceeded",
11
+ "too_many_auth_failures",
12
+ "validation_error",
13
+ "not_found",
14
+ "api_error",
15
+ "network_error",
16
+ "timeout",
17
+ ]
18
+
19
+
20
+ class ReachFlowError(Exception):
21
+ """Erreur levée par le client ReachFlow."""
22
+
23
+ def __init__(
24
+ self,
25
+ message: str,
26
+ *,
27
+ status_code: int,
28
+ code: ReachFlowErrorCode,
29
+ retryable: bool = False,
30
+ retry_after_ms: int | None = None,
31
+ body: Any = None,
32
+ ) -> None:
33
+ super().__init__(message)
34
+ self.message = message
35
+ self.status_code = status_code
36
+ self.code = code
37
+ self.retryable = retryable
38
+ self.retry_after_ms = retry_after_ms
39
+ self.body = body
40
+
41
+ @classmethod
42
+ def from_response(cls, status: int, body: Any, fallback: str | None = None) -> ReachFlowError:
43
+ parsed = body if isinstance(body, dict) else {}
44
+ api_error = parsed.get("error")
45
+ message = parsed.get("message") or fallback or f"ReachFlow API error (HTTP {status})"
46
+ code = _map_api_error_to_code(status, api_error)
47
+ retryable = status == 429 or status == 408 or 500 <= status < 600
48
+ return cls(
49
+ message,
50
+ status_code=status,
51
+ code=code,
52
+ retryable=retryable,
53
+ body=body,
54
+ )
55
+
56
+ @classmethod
57
+ def network(cls, cause: BaseException) -> ReachFlowError:
58
+ return cls(
59
+ "Network error while calling ReachFlow API",
60
+ status_code=0,
61
+ code="network_error",
62
+ retryable=True,
63
+ )
64
+
65
+ @classmethod
66
+ def timeout(cls, timeout_ms: int) -> ReachFlowError:
67
+ return cls(
68
+ f"Request timed out after {timeout_ms}ms",
69
+ status_code=408,
70
+ code="timeout",
71
+ retryable=True,
72
+ )
73
+
74
+
75
+ def parse_retry_after_ms(header: str | None) -> int | None:
76
+ if not header:
77
+ return None
78
+ try:
79
+ return max(0, int(float(header.strip())) * 1000)
80
+ except ValueError:
81
+ pass
82
+ try:
83
+ dt = parsedate_to_datetime(header)
84
+ from datetime import datetime, timezone
85
+
86
+ now = datetime.now(timezone.utc)
87
+ if dt.tzinfo is None:
88
+ dt = dt.replace(tzinfo=timezone.utc)
89
+ return max(0, int((dt - now).total_seconds() * 1000))
90
+ except (TypeError, ValueError, OverflowError):
91
+ return None
92
+
93
+
94
+ def _map_api_error_to_code(status: int, api_error: str | None) -> ReachFlowErrorCode:
95
+ mapping: dict[str, ReachFlowErrorCode] = {
96
+ "unauthorized": "unauthorized",
97
+ "plan_required": "plan_required",
98
+ "insufficient_scope": "insufficient_scope",
99
+ "rate_limit_exceeded": "rate_limit_exceeded",
100
+ "too_many_auth_failures": "too_many_auth_failures",
101
+ }
102
+ if api_error in mapping:
103
+ return mapping[api_error]
104
+ if status == 401:
105
+ return "unauthorized"
106
+ if status == 403:
107
+ return "insufficient_scope"
108
+ if status == 404:
109
+ return "not_found"
110
+ if status in (400, 422):
111
+ return "validation_error"
112
+ if status == 429:
113
+ return "rate_limit_exceeded"
114
+ return "api_error"
reachflow/http.py ADDED
@@ -0,0 +1,238 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from dataclasses import dataclass
5
+ from typing import Any, Literal
6
+
7
+ import httpx
8
+
9
+ from reachflow.errors import ReachFlowError, parse_retry_after_ms
10
+ from reachflow.types import DEFAULT_BASE_URL
11
+
12
+ HttpMethod = Literal["GET", "POST"]
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class ClientConfig:
17
+ api_key: str
18
+ base_url: str
19
+ api_prefix: str
20
+ timeout_ms: int
21
+ max_retries: int
22
+
23
+
24
+ def resolve_config(
25
+ *,
26
+ api_key: str,
27
+ base_url: str | None = None,
28
+ timeout_ms: int = 30_000,
29
+ max_retries: int = 2,
30
+ ) -> ClientConfig:
31
+ normalized_base = (base_url or DEFAULT_BASE_URL).rstrip("/")
32
+ return ClientConfig(
33
+ api_key=api_key.strip(),
34
+ base_url=normalized_base,
35
+ api_prefix=f"{normalized_base}/api/v1",
36
+ timeout_ms=timeout_ms,
37
+ max_retries=max_retries,
38
+ )
39
+
40
+
41
+ class HttpClient:
42
+ def __init__(self, config: ClientConfig, client: httpx.Client) -> None:
43
+ self._config = config
44
+ self._client = client
45
+
46
+ def request(
47
+ self,
48
+ method: HttpMethod,
49
+ path: str,
50
+ *,
51
+ body: dict[str, Any] | None = None,
52
+ idempotency_key: str | None = None,
53
+ ) -> Any:
54
+ attempt = 0
55
+ last_error: ReachFlowError | None = None
56
+
57
+ while attempt <= self._config.max_retries:
58
+ try:
59
+ return self._request_once(
60
+ method, path, body=body, idempotency_key=idempotency_key
61
+ )
62
+ except ReachFlowError as err:
63
+ last_error = err
64
+ if not err.retryable or attempt >= self._config.max_retries:
65
+ raise
66
+ delay_ms = (
67
+ err.retry_after_ms
68
+ if err.retry_after_ms is not None
69
+ else _backoff_ms(attempt)
70
+ )
71
+ time.sleep(delay_ms / 1000)
72
+ attempt += 1
73
+
74
+ if last_error is not None:
75
+ raise last_error
76
+ raise ReachFlowError("Request failed", status_code=0, code="api_error")
77
+
78
+ def _request_once(
79
+ self,
80
+ method: HttpMethod,
81
+ path: str,
82
+ *,
83
+ body: dict[str, Any] | None,
84
+ idempotency_key: str | None,
85
+ ) -> Any:
86
+ headers = {
87
+ "Accept": "application/json",
88
+ "X-API-Key": self._config.api_key,
89
+ }
90
+ if body is not None:
91
+ headers["Content-Type"] = "application/json"
92
+ if idempotency_key:
93
+ headers["Idempotency-Key"] = idempotency_key
94
+
95
+ url = f"{self._config.api_prefix}{path}"
96
+ timeout = httpx.Timeout(self._config.timeout_ms / 1000)
97
+
98
+ try:
99
+ response = self._client.request(
100
+ method,
101
+ url,
102
+ headers=headers,
103
+ json=body,
104
+ timeout=timeout,
105
+ )
106
+ except httpx.TimeoutException as exc:
107
+ raise ReachFlowError.timeout(self._config.timeout_ms) from exc
108
+ except httpx.HTTPError as exc:
109
+ raise ReachFlowError.network(exc) from exc
110
+
111
+ data: Any
112
+ text = response.text
113
+ if text:
114
+ try:
115
+ data = response.json()
116
+ except ValueError:
117
+ data = {"raw": text[:500]}
118
+ else:
119
+ data = None
120
+
121
+ if response.is_error:
122
+ err = ReachFlowError.from_response(response.status_code, data)
123
+ retry_after_ms = parse_retry_after_ms(response.headers.get("Retry-After"))
124
+ if retry_after_ms is not None:
125
+ raise ReachFlowError(
126
+ err.message,
127
+ status_code=err.status_code,
128
+ code=err.code,
129
+ retryable=err.retryable,
130
+ retry_after_ms=retry_after_ms,
131
+ body=err.body,
132
+ )
133
+ raise err
134
+
135
+ return data
136
+
137
+
138
+ class AsyncHttpClient:
139
+ def __init__(self, config: ClientConfig, client: httpx.AsyncClient) -> None:
140
+ self._config = config
141
+ self._client = client
142
+
143
+ async def request(
144
+ self,
145
+ method: HttpMethod,
146
+ path: str,
147
+ *,
148
+ body: dict[str, Any] | None = None,
149
+ idempotency_key: str | None = None,
150
+ ) -> Any:
151
+ attempt = 0
152
+ last_error: ReachFlowError | None = None
153
+
154
+ while attempt <= self._config.max_retries:
155
+ try:
156
+ return await self._request_once(
157
+ method, path, body=body, idempotency_key=idempotency_key
158
+ )
159
+ except ReachFlowError as err:
160
+ last_error = err
161
+ if not err.retryable or attempt >= self._config.max_retries:
162
+ raise
163
+ delay_ms = (
164
+ err.retry_after_ms
165
+ if err.retry_after_ms is not None
166
+ else _backoff_ms(attempt)
167
+ )
168
+ import asyncio
169
+
170
+ await asyncio.sleep(delay_ms / 1000)
171
+ attempt += 1
172
+
173
+ if last_error is not None:
174
+ raise last_error
175
+ raise ReachFlowError("Request failed", status_code=0, code="api_error")
176
+
177
+ async def _request_once(
178
+ self,
179
+ method: HttpMethod,
180
+ path: str,
181
+ *,
182
+ body: dict[str, Any] | None,
183
+ idempotency_key: str | None,
184
+ ) -> Any:
185
+ headers = {
186
+ "Accept": "application/json",
187
+ "X-API-Key": self._config.api_key,
188
+ }
189
+ if body is not None:
190
+ headers["Content-Type"] = "application/json"
191
+ if idempotency_key:
192
+ headers["Idempotency-Key"] = idempotency_key
193
+
194
+ url = f"{self._config.api_prefix}{path}"
195
+ timeout = httpx.Timeout(self._config.timeout_ms / 1000)
196
+
197
+ try:
198
+ response = await self._client.request(
199
+ method,
200
+ url,
201
+ headers=headers,
202
+ json=body,
203
+ timeout=timeout,
204
+ )
205
+ except httpx.TimeoutException as exc:
206
+ raise ReachFlowError.timeout(self._config.timeout_ms) from exc
207
+ except httpx.HTTPError as exc:
208
+ raise ReachFlowError.network(exc) from exc
209
+
210
+ data: Any
211
+ text = response.text
212
+ if text:
213
+ try:
214
+ data = response.json()
215
+ except ValueError:
216
+ data = {"raw": text[:500]}
217
+ else:
218
+ data = None
219
+
220
+ if response.is_error:
221
+ err = ReachFlowError.from_response(response.status_code, data)
222
+ retry_after_ms = parse_retry_after_ms(response.headers.get("Retry-After"))
223
+ if retry_after_ms is not None:
224
+ raise ReachFlowError(
225
+ err.message,
226
+ status_code=err.status_code,
227
+ code=err.code,
228
+ retryable=err.retryable,
229
+ retry_after_ms=retry_after_ms,
230
+ body=err.body,
231
+ )
232
+ raise err
233
+
234
+ return data
235
+
236
+
237
+ def _backoff_ms(attempt: int) -> int:
238
+ return int(min(1000 * (2**attempt), 10_000))
reachflow/py.typed ADDED
File without changes
@@ -0,0 +1 @@
1
+ """Ressources API ReachFlow."""
@@ -0,0 +1,220 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from typing import Any, cast
5
+
6
+ from reachflow.errors import ReachFlowError
7
+ from reachflow.http import AsyncHttpClient, HttpClient
8
+ from reachflow.types import (
9
+ MessageStatusResponse,
10
+ SendAcceptedResponse,
11
+ SendBulkResponse,
12
+ TERMINAL_MESSAGE_STATUSES,
13
+ )
14
+
15
+
16
+ class MessagesResource:
17
+ def __init__(self, http: HttpClient) -> None:
18
+ self._http = http
19
+
20
+ def send(
21
+ self,
22
+ *,
23
+ provider_id: str,
24
+ to: str,
25
+ message: str,
26
+ variables: dict[str, str] | None = None,
27
+ schedule_at: str | None = None,
28
+ save_contact: bool | None = None,
29
+ idempotency_key: str | None = None,
30
+ ) -> SendAcceptedResponse:
31
+ body = _send_body(
32
+ provider_id=provider_id,
33
+ to=to,
34
+ message=message,
35
+ variables=variables,
36
+ schedule_at=schedule_at,
37
+ save_contact=save_contact,
38
+ )
39
+ return cast(
40
+ SendAcceptedResponse,
41
+ self._http.request(
42
+ "POST",
43
+ "/messages/send",
44
+ body=body,
45
+ idempotency_key=idempotency_key,
46
+ ),
47
+ )
48
+
49
+ def send_media(
50
+ self,
51
+ *,
52
+ provider_id: str,
53
+ to: str,
54
+ media_url: str,
55
+ media_type: str,
56
+ caption: str | None = None,
57
+ save_contact: bool | None = None,
58
+ idempotency_key: str | None = None,
59
+ ) -> SendAcceptedResponse:
60
+ body: dict[str, Any] = {
61
+ "providerId": provider_id,
62
+ "to": to,
63
+ "mediaUrl": media_url,
64
+ "mediaType": media_type,
65
+ }
66
+ if caption is not None:
67
+ body["caption"] = caption
68
+ if save_contact is not None:
69
+ body["saveContact"] = save_contact
70
+ return cast(
71
+ SendAcceptedResponse,
72
+ self._http.request(
73
+ "POST",
74
+ "/messages/send-media",
75
+ body=body,
76
+ idempotency_key=idempotency_key,
77
+ ),
78
+ )
79
+
80
+ def send_bulk(
81
+ self,
82
+ *,
83
+ provider_id: str,
84
+ message_template: str,
85
+ recipients: list[dict[str, Any]],
86
+ schedule_at: str | None = None,
87
+ save_contact: bool | None = None,
88
+ idempotency_key: str | None = None,
89
+ ) -> SendBulkResponse:
90
+ body: dict[str, Any] = {
91
+ "providerId": provider_id,
92
+ "messageTemplate": message_template,
93
+ "recipients": recipients,
94
+ }
95
+ if schedule_at is not None:
96
+ body["scheduleAt"] = schedule_at
97
+ if save_contact is not None:
98
+ body["saveContact"] = save_contact
99
+ return cast(
100
+ SendBulkResponse,
101
+ self._http.request(
102
+ "POST",
103
+ "/messages/send-bulk",
104
+ body=body,
105
+ idempotency_key=idempotency_key,
106
+ ),
107
+ )
108
+
109
+ def get_status(self, message_id: str) -> MessageStatusResponse:
110
+ return cast(
111
+ MessageStatusResponse,
112
+ self._http.request("GET", f"/messages/{message_id}"),
113
+ )
114
+
115
+ def wait_for_terminal(
116
+ self,
117
+ message_id: str,
118
+ *,
119
+ poll_interval_ms: int = 2_000,
120
+ timeout_ms: int = 120_000,
121
+ ) -> MessageStatusResponse:
122
+ started = time.monotonic()
123
+ while (time.monotonic() - started) * 1000 < timeout_ms:
124
+ status = self.get_status(message_id)
125
+ if status.get("status") in TERMINAL_MESSAGE_STATUSES:
126
+ return status
127
+ time.sleep(poll_interval_ms / 1000)
128
+
129
+ raise ReachFlowError(
130
+ f"Message {message_id} did not reach a terminal status within {timeout_ms}ms",
131
+ status_code=408,
132
+ code="timeout",
133
+ retryable=False,
134
+ )
135
+
136
+
137
+ class AsyncMessagesResource:
138
+ def __init__(self, http: AsyncHttpClient) -> None:
139
+ self._http = http
140
+
141
+ async def send(
142
+ self,
143
+ *,
144
+ provider_id: str,
145
+ to: str,
146
+ message: str,
147
+ variables: dict[str, str] | None = None,
148
+ schedule_at: str | None = None,
149
+ save_contact: bool | None = None,
150
+ idempotency_key: str | None = None,
151
+ ) -> SendAcceptedResponse:
152
+ body = _send_body(
153
+ provider_id=provider_id,
154
+ to=to,
155
+ message=message,
156
+ variables=variables,
157
+ schedule_at=schedule_at,
158
+ save_contact=save_contact,
159
+ )
160
+ return cast(
161
+ SendAcceptedResponse,
162
+ await self._http.request(
163
+ "POST",
164
+ "/messages/send",
165
+ body=body,
166
+ idempotency_key=idempotency_key,
167
+ ),
168
+ )
169
+
170
+ async def get_status(self, message_id: str) -> MessageStatusResponse:
171
+ return cast(
172
+ MessageStatusResponse,
173
+ await self._http.request("GET", f"/messages/{message_id}"),
174
+ )
175
+
176
+ async def wait_for_terminal(
177
+ self,
178
+ message_id: str,
179
+ *,
180
+ poll_interval_ms: int = 2_000,
181
+ timeout_ms: int = 120_000,
182
+ ) -> MessageStatusResponse:
183
+ import asyncio
184
+
185
+ started = time.monotonic()
186
+ while (time.monotonic() - started) * 1000 < timeout_ms:
187
+ status = await self.get_status(message_id)
188
+ if status.get("status") in TERMINAL_MESSAGE_STATUSES:
189
+ return status
190
+ await asyncio.sleep(poll_interval_ms / 1000)
191
+
192
+ raise ReachFlowError(
193
+ f"Message {message_id} did not reach a terminal status within {timeout_ms}ms",
194
+ status_code=408,
195
+ code="timeout",
196
+ retryable=False,
197
+ )
198
+
199
+
200
+ def _send_body(
201
+ *,
202
+ provider_id: str,
203
+ to: str,
204
+ message: str,
205
+ variables: dict[str, str] | None,
206
+ schedule_at: str | None,
207
+ save_contact: bool | None,
208
+ ) -> dict[str, Any]:
209
+ body: dict[str, Any] = {
210
+ "providerId": provider_id,
211
+ "to": to,
212
+ "message": message,
213
+ }
214
+ if variables is not None:
215
+ body["variables"] = variables
216
+ if schedule_at is not None:
217
+ body["scheduleAt"] = schedule_at
218
+ if save_contact is not None:
219
+ body["saveContact"] = save_contact
220
+ return body
@@ -0,0 +1,110 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, cast
4
+
5
+ from reachflow.http import AsyncHttpClient, HttpClient
6
+ from reachflow.types import OtpSendResponse, OtpVerifyResponse
7
+
8
+
9
+ class OtpResource:
10
+ def __init__(self, http: HttpClient) -> None:
11
+ self._http = http
12
+
13
+ def send(
14
+ self,
15
+ *,
16
+ provider_id: str,
17
+ phone_number: str,
18
+ code_length: int | None = None,
19
+ expires_in: int | None = None,
20
+ brand_name: str | None = None,
21
+ template: str | None = None,
22
+ save_contact: bool | None = None,
23
+ ) -> OtpSendResponse:
24
+ body = _otp_send_body(
25
+ provider_id=provider_id,
26
+ phone_number=phone_number,
27
+ code_length=code_length,
28
+ expires_in=expires_in,
29
+ brand_name=brand_name,
30
+ template=template,
31
+ save_contact=save_contact,
32
+ )
33
+ return cast(OtpSendResponse, self._http.request("POST", "/otp/send", body=body))
34
+
35
+ def verify(self, *, otp_id: str, code: str) -> OtpVerifyResponse:
36
+ return cast(
37
+ OtpVerifyResponse,
38
+ self._http.request(
39
+ "POST",
40
+ "/otp/verify",
41
+ body={"otpId": otp_id, "code": code},
42
+ ),
43
+ )
44
+
45
+
46
+ class AsyncOtpResource:
47
+ def __init__(self, http: AsyncHttpClient) -> None:
48
+ self._http = http
49
+
50
+ async def send(
51
+ self,
52
+ *,
53
+ provider_id: str,
54
+ phone_number: str,
55
+ code_length: int | None = None,
56
+ expires_in: int | None = None,
57
+ brand_name: str | None = None,
58
+ template: str | None = None,
59
+ save_contact: bool | None = None,
60
+ ) -> OtpSendResponse:
61
+ body = _otp_send_body(
62
+ provider_id=provider_id,
63
+ phone_number=phone_number,
64
+ code_length=code_length,
65
+ expires_in=expires_in,
66
+ brand_name=brand_name,
67
+ template=template,
68
+ save_contact=save_contact,
69
+ )
70
+ return cast(
71
+ OtpSendResponse,
72
+ await self._http.request("POST", "/otp/send", body=body),
73
+ )
74
+
75
+ async def verify(self, *, otp_id: str, code: str) -> OtpVerifyResponse:
76
+ return cast(
77
+ OtpVerifyResponse,
78
+ await self._http.request(
79
+ "POST",
80
+ "/otp/verify",
81
+ body={"otpId": otp_id, "code": code},
82
+ ),
83
+ )
84
+
85
+
86
+ def _otp_send_body(
87
+ *,
88
+ provider_id: str,
89
+ phone_number: str,
90
+ code_length: int | None,
91
+ expires_in: int | None,
92
+ brand_name: str | None,
93
+ template: str | None,
94
+ save_contact: bool | None,
95
+ ) -> dict[str, Any]:
96
+ body: dict[str, Any] = {
97
+ "providerId": provider_id,
98
+ "phoneNumber": phone_number,
99
+ }
100
+ if code_length is not None:
101
+ body["codeLength"] = code_length
102
+ if expires_in is not None:
103
+ body["expiresIn"] = expires_in
104
+ if brand_name is not None:
105
+ body["brandName"] = brand_name
106
+ if template is not None:
107
+ body["template"] = template
108
+ if save_contact is not None:
109
+ body["saveContact"] = save_contact
110
+ return body
@@ -0,0 +1,47 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import cast
4
+
5
+ from reachflow.http import AsyncHttpClient, HttpClient
6
+ from reachflow.types import ProviderDetail, ProviderListResponse, ProviderSummary
7
+
8
+
9
+ class ProvidersResource:
10
+ def __init__(self, http: HttpClient) -> None:
11
+ self._http = http
12
+
13
+ def list(self) -> ProviderListResponse:
14
+ return cast(ProviderListResponse, self._http.request("GET", "/providers"))
15
+
16
+ def get(self, provider_id: str) -> ProviderDetail:
17
+ return cast(
18
+ ProviderDetail,
19
+ self._http.request("GET", f"/providers/{provider_id}"),
20
+ )
21
+
22
+ def find_connected(self) -> ProviderSummary | None:
23
+ data = self.list()
24
+ providers = data.get("providers", [])
25
+ if not providers:
26
+ return None
27
+ for provider in providers:
28
+ if str(provider.get("status", "")).lower() == "connected":
29
+ return provider
30
+ return providers[0]
31
+
32
+
33
+ class AsyncProvidersResource:
34
+ def __init__(self, http: AsyncHttpClient) -> None:
35
+ self._http = http
36
+
37
+ async def list(self) -> ProviderListResponse:
38
+ return cast(
39
+ ProviderListResponse,
40
+ await self._http.request("GET", "/providers"),
41
+ )
42
+
43
+ async def get(self, provider_id: str) -> ProviderDetail:
44
+ return cast(
45
+ ProviderDetail,
46
+ await self._http.request("GET", f"/providers/{provider_id}"),
47
+ )
reachflow/types.py ADDED
@@ -0,0 +1,111 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Literal, TypedDict
4
+
5
+ DEFAULT_BASE_URL = "https://sandbox-api.reachflow.me"
6
+
7
+ MessageStatus = Literal[
8
+ "queued",
9
+ "processing",
10
+ "sent",
11
+ "delivered",
12
+ "failed",
13
+ "cancelled",
14
+ ]
15
+
16
+ MediaType = Literal["image", "document", "audio", "video"]
17
+
18
+ FailureCode = Literal[
19
+ "warmup_daily_limit",
20
+ "risk_circuit_open",
21
+ "provider_disconnected",
22
+ "provider_banned",
23
+ "send_not_allowed",
24
+ "instance_busy",
25
+ "delivery_timeout",
26
+ "delivery_failed",
27
+ "send_error",
28
+ "provider_not_found",
29
+ ]
30
+
31
+ OtpVerifyReason = Literal[
32
+ "invalidated",
33
+ "already_used",
34
+ "expired",
35
+ "max_attempts_reached",
36
+ "invalid_code",
37
+ "not_found",
38
+ ]
39
+
40
+ TERMINAL_MESSAGE_STATUSES: frozenset[MessageStatus] = frozenset(
41
+ {"sent", "delivered", "failed", "cancelled"}
42
+ )
43
+
44
+
45
+ class SendAcceptedResponse(TypedDict):
46
+ messageId: str
47
+ status: Literal["queued"]
48
+ queuedAt: str
49
+
50
+
51
+ class BulkRejection(TypedDict):
52
+ to: str
53
+ reason: str
54
+
55
+
56
+ class SendBulkResponse(TypedDict):
57
+ bulkId: str
58
+ accepted: int
59
+ rejected: int
60
+ rejections: list[BulkRejection]
61
+ messageIds: list[str]
62
+
63
+
64
+ class MessageStatusResponse(TypedDict, total=False):
65
+ messageId: str
66
+ status: MessageStatus
67
+ to: str
68
+ providerId: str
69
+ queuedAt: str
70
+ sentAt: str | None
71
+ deliveredAt: str | None
72
+ failedAt: str | None
73
+ failureCode: FailureCode | None
74
+ failureReason: str | None
75
+
76
+
77
+ class ProviderSummary(TypedDict):
78
+ id: str
79
+ name: str
80
+ phoneNumber: str | None
81
+ status: str
82
+ warmupDay: int
83
+ riskScore: int
84
+
85
+
86
+ class ProviderDailyStats(TypedDict):
87
+ sent: int
88
+ delivered: int
89
+ failed: int
90
+ messagesLimit: int | None
91
+ newContactsLimit: int | None
92
+
93
+
94
+ class ProviderDetail(ProviderSummary, total=False):
95
+ dailyStats: ProviderDailyStats
96
+
97
+
98
+ class ProviderListResponse(TypedDict):
99
+ providers: list[ProviderSummary]
100
+
101
+
102
+ class OtpSendResponse(TypedDict):
103
+ otpId: str
104
+ messageId: str
105
+ expiresAt: str
106
+
107
+
108
+ class OtpVerifyResponse(TypedDict, total=False):
109
+ valid: bool
110
+ reason: OtpVerifyReason
111
+ attemptsLeft: int
@@ -0,0 +1,134 @@
1
+ Metadata-Version: 2.4
2
+ Name: reachflow
3
+ Version: 0.1.0
4
+ Summary: Client officiel Python pour l'API publique ReachFlow
5
+ Project-URL: Homepage, https://docs.reachflow.me/developpeurs
6
+ Project-URL: Documentation, https://docs.reachflow.me/developpeurs
7
+ Project-URL: Repository, https://github.com/reachflow/reachflow-python
8
+ Project-URL: Issues, https://github.com/reachflow/reachflow-python/issues
9
+ Author-email: ReachFlow <contact@reachflow.me>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: api,otp,reachflow,sdk,whatsapp
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: httpx>=0.27.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: mypy>=1.13.0; extra == 'dev'
26
+ Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
27
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
28
+ Requires-Dist: respx>=0.21.0; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # reachflow
32
+
33
+ Client officiel **Python** pour l’[API publique ReachFlow](https://docs.reachflow.me/developpeurs) (REST v1).
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install reachflow
39
+ ```
40
+
41
+ **Prérequis :** Python ≥ 3.10.
42
+
43
+ ## Configuration
44
+
45
+ ```python
46
+ from reachflow import ReachFlow
47
+
48
+ client = ReachFlow(
49
+ api_key="rfl_live_…", # ou rfl_test_…
50
+ base_url="https://sandbox-api.reachflow.me", # optionnel
51
+ timeout_ms=30_000, # optionnel
52
+ max_retries=2, # optionnel — 429 / 5xx
53
+ )
54
+ ```
55
+
56
+ Utilisez le client comme context manager pour fermer la connexion HTTP :
57
+
58
+ ```python
59
+ with ReachFlow(api_key="rfl_live_…") as client:
60
+ ...
61
+ ```
62
+
63
+ ## Exemples
64
+
65
+ ### Envoyer un message
66
+
67
+ ```python
68
+ with ReachFlow(api_key="rfl_live_…") as client:
69
+ result = client.messages.send(
70
+ provider_id="uuid-du-provider",
71
+ to="22996123456",
72
+ message="Votre commande est confirmée.",
73
+ )
74
+ status = client.messages.wait_for_terminal(result["messageId"])
75
+ print(status["status"])
76
+ ```
77
+
78
+ ### OTP
79
+
80
+ ```python
81
+ with ReachFlow(api_key="rfl_live_…") as client:
82
+ sent = client.otp.send(
83
+ provider_id="uuid-du-provider",
84
+ phone_number="22996123456",
85
+ brand_name="Mon App",
86
+ )
87
+ # Le code arrive sur WhatsApp — jamais dans la réponse JSON.
88
+ verified = client.otp.verify(otp_id=sent["otpId"], code="482910")
89
+ print(verified["valid"])
90
+ ```
91
+
92
+ ### Client asynchrone
93
+
94
+ ```python
95
+ from reachflow import AsyncReachFlow
96
+
97
+ async with AsyncReachFlow(api_key="rfl_live_…") as client:
98
+ providers = await client.providers.list()
99
+ ```
100
+
101
+ ## Gestion des erreurs
102
+
103
+ ```python
104
+ from reachflow import ReachFlow, ReachFlowError
105
+
106
+ try:
107
+ client.messages.send(...)
108
+ except ReachFlowError as err:
109
+ print(err.status_code, err.code, err.message)
110
+ if err.retryable:
111
+ ...
112
+ ```
113
+
114
+ ## Idempotence
115
+
116
+ ```python
117
+ client.messages.send(
118
+ provider_id=provider_id,
119
+ to=to,
120
+ message=message,
121
+ idempotency_key="order-12345",
122
+ )
123
+ ```
124
+
125
+ ## Développement
126
+
127
+ ```bash
128
+ pip install -e ".[dev]"
129
+ pytest
130
+ ```
131
+
132
+ ## Licence
133
+
134
+ MIT
@@ -0,0 +1,14 @@
1
+ reachflow/__init__.py,sha256=VJsKAJSzloPpqR9Ob6DwHr8w8tFIVix1OX0Q63G584s,473
2
+ reachflow/client.py,sha256=keUt4Slo4UrRtsfQ0H39Muj1CDC8s0Zh5f8LMBQ3-KA,3200
3
+ reachflow/errors.py,sha256=N2zhwOBIfyv1SJQFdVSLzFg-s8pi6UBQYaeT0WuJaHo,3340
4
+ reachflow/http.py,sha256=jQvaWBwev4e_EoHkGkFtcDdfJB9JFwt9vGztJibdAJo,7085
5
+ reachflow/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ reachflow/types.py,sha256=71sT8LY7cJILBZJAcQYNziP4TssYNe_EkRyUiThhil8,2121
7
+ reachflow/resources/__init__.py,sha256=uoEG8Y9o6wd1_n6R1P24MLdJXhjLwUQZ1NCw5nLxO7I,32
8
+ reachflow/resources/messages.py,sha256=FjKFqpts3VdOmPESqoGzqIE60KabwgkoA6WS_-Ykiew,6261
9
+ reachflow/resources/otp.py,sha256=6tIQ0vS6RtdF0yWav4nkm2QttUrRmSaEMsntfIFzgog,3137
10
+ reachflow/resources/providers.py,sha256=1oVm_2R5TQKzg7vo7Y6S0td4JUCMRcwdwCseLp_Mlz0,1441
11
+ reachflow-0.1.0.dist-info/METADATA,sha256=-r_QssP-wWgRIJ1HiMoZe0oLSNG1sBt2YNbJTrNbLPY,3268
12
+ reachflow-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
13
+ reachflow-0.1.0.dist-info/licenses/LICENSE,sha256=0DNSEXAHyOVVF3BLEQelnrEyWKAlvHaFbu8hQAEPDo8,1066
14
+ reachflow-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ReachFlow
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.