qmgateway 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.
- qmgateway-0.1.0/LICENSE +21 -0
- qmgateway-0.1.0/PKG-INFO +133 -0
- qmgateway-0.1.0/README.md +117 -0
- qmgateway-0.1.0/pyproject.toml +29 -0
- qmgateway-0.1.0/setup.cfg +4 -0
- qmgateway-0.1.0/src/qmgateway/__init__.py +11 -0
- qmgateway-0.1.0/src/qmgateway/__main__.py +5 -0
- qmgateway-0.1.0/src/qmgateway/_cli.py +89 -0
- qmgateway-0.1.0/src/qmgateway/_http.py +183 -0
- qmgateway-0.1.0/src/qmgateway/client.py +168 -0
- qmgateway-0.1.0/src/qmgateway/errors.py +48 -0
- qmgateway-0.1.0/src/qmgateway/models.py +266 -0
- qmgateway-0.1.0/src/qmgateway/py.typed +0 -0
- qmgateway-0.1.0/src/qmgateway/testing.py +47 -0
- qmgateway-0.1.0/src/qmgateway/webhook.py +65 -0
- qmgateway-0.1.0/src/qmgateway.egg-info/PKG-INFO +133 -0
- qmgateway-0.1.0/src/qmgateway.egg-info/SOURCES.txt +19 -0
- qmgateway-0.1.0/src/qmgateway.egg-info/dependency_links.txt +1 -0
- qmgateway-0.1.0/src/qmgateway.egg-info/entry_points.txt +2 -0
- qmgateway-0.1.0/src/qmgateway.egg-info/top_level.txt +1 -0
- qmgateway-0.1.0/tests/test_sdk.py +189 -0
qmgateway-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 QMGateway
|
|
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.
|
qmgateway-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: qmgateway
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Send SMS and one-time passwords with QMGateway. No dependencies.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/qmgateway-sms/qmgateway-python
|
|
7
|
+
Project-URL: Source, https://github.com/qmgateway-sms/qmgateway-python
|
|
8
|
+
Project-URL: Issues, https://github.com/qmgateway-sms/qmgateway-python/issues
|
|
9
|
+
Project-URL: Security, https://github.com/qmgateway-sms/qmgateway-python/security/policy
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# QMGateway for Python
|
|
18
|
+
|
|
19
|
+
Send SMS and one-time passwords from Python. Needs **Python 3.10 or newer**. It uses only the standard library, so installing it brings nothing else with it. Fully typed.
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
pip install qmgateway
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Send a message
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import os
|
|
29
|
+
from qmgateway import QMGateway
|
|
30
|
+
|
|
31
|
+
qm = QMGateway(os.environ["QMGATEWAY_API_KEY"])
|
|
32
|
+
|
|
33
|
+
sent = qm.messages.send("+265999123456", "Your order is ready.")
|
|
34
|
+
print(f"Queued message {sent.message_id}, {sent.remaining_units} SMS left")
|
|
35
|
+
|
|
36
|
+
print(qm.messages.get(sent.message_id).status)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Use a test key (it starts with `qm_test_`; create one on the API keys page of your account) while you build: nothing reaches a phone and no SMS are used. Keep keys out of your code: read them from the environment.
|
|
40
|
+
Calls wait for the answer (they are not `async`). In an async program, run them with `asyncio.to_thread(...)`.
|
|
41
|
+
|
|
42
|
+
## What you can do
|
|
43
|
+
|
|
44
|
+
| | |
|
|
45
|
+
|---|---|
|
|
46
|
+
| `qm.messages.send(to, text, scheduled_at="2026-12-01 08:00:00")` | one number, or a list for several |
|
|
47
|
+
| `qm.messages.get(id)` / `list(status="Failed")` / `each(status="Failed")` | track delivery; `each()` fetches more pages for you |
|
|
48
|
+
| `qm.messages.scheduled()` / `cancel(id)` / `reschedule(id, time)` | scheduled messages |
|
|
49
|
+
| `qm.inbox.list()` / `each()` | replies received (`message.sender` is the number it came from) |
|
|
50
|
+
| `qm.otp.send(phone="+265999123456")` / `verify(ref, code)` | one-time passwords |
|
|
51
|
+
| `qm.devices.list()` | your gateway phones |
|
|
52
|
+
| `qm.account.get()` / `balance()` / `statistics()` | account and usage |
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
for m in qm.messages.each(status="Failed"):
|
|
56
|
+
print(f"{m.id} to {m.phone_number} failed: {m.failure_reason}")
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Errors
|
|
60
|
+
|
|
61
|
+
Everything the SDK raises is a `QMGatewayError`. API errors are `ApiError`s with a stable `code`, the HTTP `status` and a `request_id` to quote to support.
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from qmgateway import ApiError, RateLimitError, QMConnectionError
|
|
65
|
+
|
|
66
|
+
try:
|
|
67
|
+
qm.messages.send(phone, text)
|
|
68
|
+
except RateLimitError as e:
|
|
69
|
+
print("rate limited, try again in", e.retry_after, "seconds")
|
|
70
|
+
except ApiError as e:
|
|
71
|
+
print(e.code, e.status, e.request_id)
|
|
72
|
+
except QMConnectionError:
|
|
73
|
+
print("no answer; resend with the same idempotency_key to be safe")
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Retries and duplicates
|
|
77
|
+
|
|
78
|
+
Network errors, rate limits (429) and server errors (5xx) are retried up to 4 times, waiting for `Retry-After` when given, otherwise 1, 2, 4, 8 seconds. Other errors are never retried. Every send carries an `Idempotency-Key` (made for you), kept the same across retries, so a retry can never send twice. For jobs that may run again, pass your own: `send(to, text, idempotency_key=f"order-{order_id}")`. Sending a one-time password is retried only after a 429.
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
from qmgateway import Options
|
|
82
|
+
qm = QMGateway(key, Options(timeout=10, max_retries=2))
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Webhooks
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from qmgateway import verify_webhook, SignatureError
|
|
89
|
+
|
|
90
|
+
# Flask: request.get_data() is the untouched body.
|
|
91
|
+
@app.post("/webhooks/qmgateway")
|
|
92
|
+
def hook():
|
|
93
|
+
try:
|
|
94
|
+
event = verify_webhook(request.get_data(), request.headers, os.environ["QMGATEWAY_WEBHOOK_SECRET"])
|
|
95
|
+
except SignatureError:
|
|
96
|
+
return "", 401
|
|
97
|
+
if event.type == "sms.delivered":
|
|
98
|
+
print("delivered", event.message_id)
|
|
99
|
+
return "", 200
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Use the raw body exactly as received. Requests older than 5 minutes are refused.
|
|
103
|
+
|
|
104
|
+
## Testing your own code
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from qmgateway import Options, QMGateway
|
|
108
|
+
from qmgateway.testing import FakeTransport
|
|
109
|
+
|
|
110
|
+
fake = FakeTransport().queue_json({"success": True, "data": {"message_ids": [7], "recipients": 1, "sms_units": 1, "status": "Queued", "remaining_units": 99, "idempotent_replay": False, "numbers": ["+265999123456"]}}, 202)
|
|
111
|
+
qm = QMGateway("qm_test_x", Options(transport=fake))
|
|
112
|
+
|
|
113
|
+
sent = qm.messages.send("+265999123456", "Hello")
|
|
114
|
+
print(sent.message_id) # 7
|
|
115
|
+
print(fake.last.headers["x-api-key"]) # qm_test_x
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
`queue_error()` and `queue_network_error()` play failures; `fake.requests` shows what was sent. `sign_webhook()` builds a correctly signed request for testing your handler.
|
|
119
|
+
|
|
120
|
+
## Command line
|
|
121
|
+
|
|
122
|
+
```
|
|
123
|
+
# paste a test key from the API keys page of your QMGateway account (it starts with qm_test_)
|
|
124
|
+
export QMGATEWAY_API_KEY="<your test key>" # Windows PowerShell: $env:QMGATEWAY_API_KEY = "<your test key>"
|
|
125
|
+
qmgateway send +265999123456 "Hello"
|
|
126
|
+
qmgateway help
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## Developing this SDK
|
|
130
|
+
|
|
131
|
+
`python -m unittest discover -s tests` runs the tests (they use the shared contract files in `tests/contract`, or `QMGATEWAY_CONTRACT_DIR`). `python tests/live.py` checks it against a real server: set `QMGATEWAY_BASE`, `QMGATEWAY_LIVE_KEY` and `QMGATEWAY_TEST_KEY` first. Use the keys of a test organisation, because the live checks queue real messages.
|
|
132
|
+
|
|
133
|
+
Security problems: see [SECURITY.md](SECURITY.md). Licence: MIT.
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# QMGateway for Python
|
|
2
|
+
|
|
3
|
+
Send SMS and one-time passwords from Python. Needs **Python 3.10 or newer**. It uses only the standard library, so installing it brings nothing else with it. Fully typed.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
pip install qmgateway
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Send a message
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
import os
|
|
13
|
+
from qmgateway import QMGateway
|
|
14
|
+
|
|
15
|
+
qm = QMGateway(os.environ["QMGATEWAY_API_KEY"])
|
|
16
|
+
|
|
17
|
+
sent = qm.messages.send("+265999123456", "Your order is ready.")
|
|
18
|
+
print(f"Queued message {sent.message_id}, {sent.remaining_units} SMS left")
|
|
19
|
+
|
|
20
|
+
print(qm.messages.get(sent.message_id).status)
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Use a test key (it starts with `qm_test_`; create one on the API keys page of your account) while you build: nothing reaches a phone and no SMS are used. Keep keys out of your code: read them from the environment.
|
|
24
|
+
Calls wait for the answer (they are not `async`). In an async program, run them with `asyncio.to_thread(...)`.
|
|
25
|
+
|
|
26
|
+
## What you can do
|
|
27
|
+
|
|
28
|
+
| | |
|
|
29
|
+
|---|---|
|
|
30
|
+
| `qm.messages.send(to, text, scheduled_at="2026-12-01 08:00:00")` | one number, or a list for several |
|
|
31
|
+
| `qm.messages.get(id)` / `list(status="Failed")` / `each(status="Failed")` | track delivery; `each()` fetches more pages for you |
|
|
32
|
+
| `qm.messages.scheduled()` / `cancel(id)` / `reschedule(id, time)` | scheduled messages |
|
|
33
|
+
| `qm.inbox.list()` / `each()` | replies received (`message.sender` is the number it came from) |
|
|
34
|
+
| `qm.otp.send(phone="+265999123456")` / `verify(ref, code)` | one-time passwords |
|
|
35
|
+
| `qm.devices.list()` | your gateway phones |
|
|
36
|
+
| `qm.account.get()` / `balance()` / `statistics()` | account and usage |
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
for m in qm.messages.each(status="Failed"):
|
|
40
|
+
print(f"{m.id} to {m.phone_number} failed: {m.failure_reason}")
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Errors
|
|
44
|
+
|
|
45
|
+
Everything the SDK raises is a `QMGatewayError`. API errors are `ApiError`s with a stable `code`, the HTTP `status` and a `request_id` to quote to support.
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from qmgateway import ApiError, RateLimitError, QMConnectionError
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
qm.messages.send(phone, text)
|
|
52
|
+
except RateLimitError as e:
|
|
53
|
+
print("rate limited, try again in", e.retry_after, "seconds")
|
|
54
|
+
except ApiError as e:
|
|
55
|
+
print(e.code, e.status, e.request_id)
|
|
56
|
+
except QMConnectionError:
|
|
57
|
+
print("no answer; resend with the same idempotency_key to be safe")
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Retries and duplicates
|
|
61
|
+
|
|
62
|
+
Network errors, rate limits (429) and server errors (5xx) are retried up to 4 times, waiting for `Retry-After` when given, otherwise 1, 2, 4, 8 seconds. Other errors are never retried. Every send carries an `Idempotency-Key` (made for you), kept the same across retries, so a retry can never send twice. For jobs that may run again, pass your own: `send(to, text, idempotency_key=f"order-{order_id}")`. Sending a one-time password is retried only after a 429.
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from qmgateway import Options
|
|
66
|
+
qm = QMGateway(key, Options(timeout=10, max_retries=2))
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Webhooks
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from qmgateway import verify_webhook, SignatureError
|
|
73
|
+
|
|
74
|
+
# Flask: request.get_data() is the untouched body.
|
|
75
|
+
@app.post("/webhooks/qmgateway")
|
|
76
|
+
def hook():
|
|
77
|
+
try:
|
|
78
|
+
event = verify_webhook(request.get_data(), request.headers, os.environ["QMGATEWAY_WEBHOOK_SECRET"])
|
|
79
|
+
except SignatureError:
|
|
80
|
+
return "", 401
|
|
81
|
+
if event.type == "sms.delivered":
|
|
82
|
+
print("delivered", event.message_id)
|
|
83
|
+
return "", 200
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Use the raw body exactly as received. Requests older than 5 minutes are refused.
|
|
87
|
+
|
|
88
|
+
## Testing your own code
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from qmgateway import Options, QMGateway
|
|
92
|
+
from qmgateway.testing import FakeTransport
|
|
93
|
+
|
|
94
|
+
fake = FakeTransport().queue_json({"success": True, "data": {"message_ids": [7], "recipients": 1, "sms_units": 1, "status": "Queued", "remaining_units": 99, "idempotent_replay": False, "numbers": ["+265999123456"]}}, 202)
|
|
95
|
+
qm = QMGateway("qm_test_x", Options(transport=fake))
|
|
96
|
+
|
|
97
|
+
sent = qm.messages.send("+265999123456", "Hello")
|
|
98
|
+
print(sent.message_id) # 7
|
|
99
|
+
print(fake.last.headers["x-api-key"]) # qm_test_x
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`queue_error()` and `queue_network_error()` play failures; `fake.requests` shows what was sent. `sign_webhook()` builds a correctly signed request for testing your handler.
|
|
103
|
+
|
|
104
|
+
## Command line
|
|
105
|
+
|
|
106
|
+
```
|
|
107
|
+
# paste a test key from the API keys page of your QMGateway account (it starts with qm_test_)
|
|
108
|
+
export QMGATEWAY_API_KEY="<your test key>" # Windows PowerShell: $env:QMGATEWAY_API_KEY = "<your test key>"
|
|
109
|
+
qmgateway send +265999123456 "Hello"
|
|
110
|
+
qmgateway help
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Developing this SDK
|
|
114
|
+
|
|
115
|
+
`python -m unittest discover -s tests` runs the tests (they use the shared contract files in `tests/contract`, or `QMGATEWAY_CONTRACT_DIR`). `python tests/live.py` checks it against a real server: set `QMGATEWAY_BASE`, `QMGATEWAY_LIVE_KEY` and `QMGATEWAY_TEST_KEY` first. Use the keys of a test organisation, because the live checks queue real messages.
|
|
116
|
+
|
|
117
|
+
Security problems: see [SECURITY.md](SECURITY.md). Licence: MIT.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "qmgateway"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Send SMS and one-time passwords with QMGateway. No dependencies."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
dependencies = []
|
|
14
|
+
classifiers = ["Programming Language :: Python :: 3", "Typing :: Typed"]
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Homepage = "https://github.com/qmgateway-sms/qmgateway-python"
|
|
18
|
+
Source = "https://github.com/qmgateway-sms/qmgateway-python"
|
|
19
|
+
Issues = "https://github.com/qmgateway-sms/qmgateway-python/issues"
|
|
20
|
+
Security = "https://github.com/qmgateway-sms/qmgateway-python/security/policy"
|
|
21
|
+
|
|
22
|
+
[project.scripts]
|
|
23
|
+
qmgateway = "qmgateway._cli:main"
|
|
24
|
+
|
|
25
|
+
[tool.setuptools.packages.find]
|
|
26
|
+
where = ["src"]
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.package-data]
|
|
29
|
+
qmgateway = ["py.typed"]
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""QMGateway: send SMS and one-time passwords. Standard library only."""
|
|
2
|
+
from ._http import VERSION as __version__
|
|
3
|
+
from ._http import Options, Transport, TransportRequest, TransportResponse
|
|
4
|
+
from .client import Account, Devices, Inbox, Messages, Otp, QMGateway
|
|
5
|
+
from .errors import (ApiError, AuthenticationError, ConflictError, InvalidRequestError, NotFoundError, PermissionDeniedError, QMConnectionError,
|
|
6
|
+
QMGatewayError, RateLimitError, ServerError, SignatureError)
|
|
7
|
+
from .models import (Account as AccountInfo, Balance, Device, EmailOtpBalance, InboxMessage, Message, OtpRequest, OtpVerification, Page,
|
|
8
|
+
ScheduledMessage, SendResult, Service, Statistics, parse_time, to_malawi_time)
|
|
9
|
+
from .webhook import WEBHOOK_TOLERANCE, WebhookEvent, sign_webhook, verify_webhook
|
|
10
|
+
|
|
11
|
+
__all__ = [n for n in dir() if not n.startswith("_") or n == "__version__"]
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Command-line tool. QMGATEWAY_API_KEY=qm_live_... qmgateway account
|
|
2
|
+
|
|
3
|
+
The key is read from the environment on purpose: a key typed as an argument stays in your shell history.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from . import ApiError, Options, QMGateway, QMGatewayError, SignatureError, verify_webhook
|
|
12
|
+
|
|
13
|
+
HELP = """qmgateway command-line tool
|
|
14
|
+
|
|
15
|
+
Set QMGATEWAY_API_KEY (and QMGATEWAY_BASE_URL for a non-default server), then:
|
|
16
|
+
account who the key belongs to and which services are ready
|
|
17
|
+
balance what is left of your plan
|
|
18
|
+
devices your gateway phones
|
|
19
|
+
send <phone> <message> queue a message (add --at="2026-12-01 08:00:00" to schedule it)
|
|
20
|
+
status <id> where a message is now
|
|
21
|
+
messages [--status=Failed] the latest messages
|
|
22
|
+
verify-webhook --secret=... check a webhook: raw body on standard input, --header="Name: value" for each header
|
|
23
|
+
Add --json for machine-readable output."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _out(v: object, as_json: bool) -> None:
|
|
27
|
+
if as_json:
|
|
28
|
+
print(json.dumps(v, indent=2, ensure_ascii=False, default=str))
|
|
29
|
+
elif isinstance(v, str):
|
|
30
|
+
print(v)
|
|
31
|
+
else:
|
|
32
|
+
for k, x in v.items(): # type: ignore[union-attr]
|
|
33
|
+
print(str(k).ljust(18) + (json.dumps(x) if isinstance(x, (dict, list)) else str(x)))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _opt(args: list[str], name: str) -> str | None:
|
|
37
|
+
return next((a[len(name) + 3:] for a in args if a.startswith(f"--{name}=")), None)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def main(argv: list[str] | None = None) -> int:
|
|
41
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
42
|
+
cmd = argv.pop(0) if argv else "help"
|
|
43
|
+
as_json = "--json" in argv
|
|
44
|
+
args = [a for a in argv if a != "--json"]
|
|
45
|
+
if cmd in ("help", "--help", "-h"):
|
|
46
|
+
print(HELP); return 0
|
|
47
|
+
if cmd == "verify-webhook":
|
|
48
|
+
secret = _opt(args, "secret") or os.environ.get("QMGATEWAY_WEBHOOK_SECRET")
|
|
49
|
+
if not secret:
|
|
50
|
+
print("Give --secret=... or set QMGATEWAY_WEBHOOK_SECRET.", file=sys.stderr); return 2
|
|
51
|
+
headers = {n.strip(): v.strip() for a in args if a.startswith("--header=") and ":" in a for n, v in [a[9:].split(":", 1)]}
|
|
52
|
+
try:
|
|
53
|
+
e = verify_webhook(sys.stdin.buffer.read(), headers, secret)
|
|
54
|
+
_out({"verified": True, "event": e.type, "event_id": e.id, "message_id": e.message_id}, as_json); return 0
|
|
55
|
+
except SignatureError as e:
|
|
56
|
+
_out({"verified": False, "reason": e.reason}, as_json); return 3
|
|
57
|
+
key = os.environ.get("QMGATEWAY_API_KEY")
|
|
58
|
+
if not key:
|
|
59
|
+
print("Set the QMGATEWAY_API_KEY environment variable.", file=sys.stderr); return 2
|
|
60
|
+
try:
|
|
61
|
+
qm = QMGateway(key, Options(base_url=os.environ["QMGATEWAY_BASE_URL"]) if os.environ.get("QMGATEWAY_BASE_URL") else None)
|
|
62
|
+
if cmd == "account":
|
|
63
|
+
a = qm.account.get(); sms = a.service("sms")
|
|
64
|
+
_out(a.raw if as_json else {"organisation": a.organisation_name, "key": a.key_mode, "sms_ready": bool(sms and sms.ready_to_send)}, as_json)
|
|
65
|
+
elif cmd == "balance":
|
|
66
|
+
b = qm.account.balance()
|
|
67
|
+
_out(b.raw if as_json else {"plan": b.plan, "remaining": f"{b.remaining} of {b.quota}", "level": b.level, "expires_at": b.expires_at}, as_json)
|
|
68
|
+
elif cmd == "devices":
|
|
69
|
+
for d in qm.devices.list(): _out(d.raw if as_json else f"#{d.id} {d.name} ({d.status}, {d.queued} queued)", as_json)
|
|
70
|
+
elif cmd == "send":
|
|
71
|
+
at = _opt(args, "at"); p = [a for a in args if not a.startswith("--at=")]
|
|
72
|
+
if len(p) < 2:
|
|
73
|
+
print('Usage: qmgateway send <phone> <message> [--at="YYYY-MM-DD HH:MM:SS"]', file=sys.stderr); return 2
|
|
74
|
+
r = qm.messages.send(p[0], " ".join(p[1:]), scheduled_at=at)
|
|
75
|
+
_out(r.raw if as_json else f"Queued message {r.message_id} ({r.remaining_units} units left)", as_json)
|
|
76
|
+
elif cmd == "status":
|
|
77
|
+
m = qm.messages.get(int(args[0]) if args else 0)
|
|
78
|
+
_out(m.raw if as_json else f"#{m.id} {m.phone_number}: {m.status}" + (f" ({m.failure_reason})" if m.failure_reason else ""), as_json)
|
|
79
|
+
elif cmd == "messages":
|
|
80
|
+
for m in qm.messages.list(status=_opt(args, "status"), limit=20).items: _out(m.raw if as_json else f"#{m.id} {m.phone_number} {m.status}", as_json)
|
|
81
|
+
else:
|
|
82
|
+
print(f'Unknown command "{cmd}". Run qmgateway help.', file=sys.stderr); return 2
|
|
83
|
+
except QMGatewayError as e:
|
|
84
|
+
print(f"Error: {e}" + (f" [{e.code}]" if isinstance(e, ApiError) else ""), file=sys.stderr); return 1
|
|
85
|
+
return 0
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
if __name__ == "__main__":
|
|
89
|
+
sys.exit(main())
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import random
|
|
5
|
+
import time
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import Any, Callable, Mapping, Protocol
|
|
11
|
+
from urllib.parse import urlsplit
|
|
12
|
+
|
|
13
|
+
from .errors import (ApiError, AuthenticationError, ConflictError, InvalidRequestError, NotFoundError, PermissionDeniedError,
|
|
14
|
+
QMConnectionError, RateLimitError, ServerError)
|
|
15
|
+
|
|
16
|
+
VERSION = "0.1.0"
|
|
17
|
+
MAX_WAIT = 60.0
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class TransportRequest:
|
|
22
|
+
method: str
|
|
23
|
+
url: str
|
|
24
|
+
headers: Mapping[str, str]
|
|
25
|
+
body: bytes | None
|
|
26
|
+
timeout: float
|
|
27
|
+
retryable: bool = True
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class TransportResponse:
|
|
32
|
+
status: int
|
|
33
|
+
headers: Mapping[str, str] # lower-case names
|
|
34
|
+
body: bytes
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Transport(Protocol):
|
|
38
|
+
def __call__(self, request: TransportRequest) -> TransportResponse:
|
|
39
|
+
"""Send one request. Raise QMConnectionError when no answer could be read."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Options:
|
|
44
|
+
"""How a client behaves.
|
|
45
|
+
|
|
46
|
+
base_url: where the API lives. https only; plain http is accepted for localhost (testing).
|
|
47
|
+
timeout: seconds to wait for one request. A timeout counts as a network error.
|
|
48
|
+
max_retries: extra tries after the first, for network errors, 429 and 5xx (0 turns retries off).
|
|
49
|
+
transport: replaces the network (tests use qmgateway.testing.FakeTransport).
|
|
50
|
+
sleep: replaces the real pause between retries (tests use it to run fast).
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
base_url: str = "https://qmgateway.com"
|
|
54
|
+
timeout: float = 30.0
|
|
55
|
+
max_retries: int = 4
|
|
56
|
+
transport: Transport | None = None
|
|
57
|
+
sleep: Callable[[float], None] | None = None
|
|
58
|
+
user_agent: str | None = None
|
|
59
|
+
|
|
60
|
+
def __post_init__(self) -> None:
|
|
61
|
+
try:
|
|
62
|
+
u = urlsplit(self.base_url)
|
|
63
|
+
host = (u.hostname or "").lower()
|
|
64
|
+
except ValueError:
|
|
65
|
+
raise ValueError("base_url is not a valid web address.") from None
|
|
66
|
+
local = host in ("localhost", "127.0.0.1", "::1")
|
|
67
|
+
if not (u.scheme == "https" or (u.scheme == "http" and local)) or not host:
|
|
68
|
+
raise ValueError("base_url must use https (plain http is only allowed for localhost).")
|
|
69
|
+
if u.username or u.password:
|
|
70
|
+
raise ValueError("base_url must not contain a user name or password.")
|
|
71
|
+
if not (0 < self.timeout <= 300):
|
|
72
|
+
raise ValueError("timeout must be between 0 and 300 seconds.")
|
|
73
|
+
if not (isinstance(self.max_retries, int) and 0 <= self.max_retries <= 10):
|
|
74
|
+
raise ValueError("max_retries must be a whole number from 0 to 10.")
|
|
75
|
+
if self.user_agent and ("\n" in self.user_agent or "\r" in self.user_agent):
|
|
76
|
+
raise ValueError("user_agent must be one line.")
|
|
77
|
+
|
|
78
|
+
def root(self) -> str:
|
|
79
|
+
return self.base_url.rstrip("/")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
83
|
+
def redirect_request(self, *a: Any, **k: Any) -> None: # a redirect would resend the API key somewhere else
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
_opener = urllib.request.build_opener(_NoRedirect)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def urllib_transport(r: TransportRequest) -> TransportResponse:
|
|
91
|
+
"""The built-in transport: standard library only, no redirects, certificates always checked."""
|
|
92
|
+
req = urllib.request.Request(r.url, data=r.body, method=r.method, headers=dict(r.headers))
|
|
93
|
+
try:
|
|
94
|
+
with _opener.open(req, timeout=r.timeout) as res:
|
|
95
|
+
return TransportResponse(res.status, {k.lower(): v for k, v in res.headers.items()}, res.read(8_000_001))
|
|
96
|
+
except urllib.error.HTTPError as e: # an answer with an error status is still an answer
|
|
97
|
+
with e:
|
|
98
|
+
return TransportResponse(e.code, {k.lower(): v for k, v in e.headers.items()}, e.read(8_000_001))
|
|
99
|
+
except TimeoutError as e:
|
|
100
|
+
raise QMConnectionError("The request timed out.") from e
|
|
101
|
+
except (urllib.error.URLError, OSError) as e:
|
|
102
|
+
raise QMConnectionError(f"Could not reach QMGateway ({getattr(e, 'reason', e)}).") from e
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _backoff(attempt: int) -> float:
|
|
106
|
+
return min(2.0**attempt, MAX_WAIT) * (1 + random.SystemRandom().randint(0, 200) / 1000)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _wait_for(res: TransportResponse, attempt: int) -> float:
|
|
110
|
+
after = res.headers.get("retry-after")
|
|
111
|
+
return min(float(after), MAX_WAIT) if after is not None and after.isdigit() else _backoff(attempt)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class HttpClient:
|
|
115
|
+
"""Sends requests and does what every call needs: the key, the retries, and turning an error answer into the right error.
|
|
116
|
+
|
|
117
|
+
Retry rules (the shared SDK contract): network errors, 429 and 5xx are retried, other 4xx never; wait Retry-After (max 60 s)
|
|
118
|
+
or 1, 2, 4, 8 s plus up to 20% jitter; same Idempotency-Key every try. A request that is not safe to repeat is retried only on 429.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
def __init__(self, api_key: str, options: Options) -> None:
|
|
122
|
+
if not api_key or any(c.isspace() for c in api_key):
|
|
123
|
+
raise ValueError("The API key is missing or has spaces in it.")
|
|
124
|
+
self._key = api_key
|
|
125
|
+
self.options = options
|
|
126
|
+
|
|
127
|
+
def request(self, method: str, path: str, *, query: Mapping[str, Any] | None = None, body: Mapping[str, Any] | None = None,
|
|
128
|
+
headers: Mapping[str, str] | None = None, safe_to_repeat: bool = True) -> dict[str, Any]:
|
|
129
|
+
q = {k: v for k, v in (query or {}).items() if v is not None}
|
|
130
|
+
url = self.options.root() + path + ("?" + urllib.parse.urlencode(q, quote_via=urllib.parse.quote) if q else "")
|
|
131
|
+
ua = f"qmgateway-python/{VERSION} python/{__import__('platform').python_version()}" + (f" {self.options.user_agent}" if self.options.user_agent else "")
|
|
132
|
+
h = {"x-api-key": self._key, "accept": "application/json", "user-agent": ua, **(headers or {})}
|
|
133
|
+
data = None
|
|
134
|
+
if body is not None:
|
|
135
|
+
h["content-type"] = "application/json"
|
|
136
|
+
data = json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode()
|
|
137
|
+
request = TransportRequest(method, url, h, data, self.options.timeout, safe_to_repeat)
|
|
138
|
+
transport = self.options.transport or urllib_transport
|
|
139
|
+
attempt = 0
|
|
140
|
+
while True:
|
|
141
|
+
last = attempt >= self.options.max_retries
|
|
142
|
+
try:
|
|
143
|
+
res = transport(request)
|
|
144
|
+
except QMConnectionError:
|
|
145
|
+
if last or not request.retryable:
|
|
146
|
+
raise
|
|
147
|
+
self._pause(_backoff(attempt))
|
|
148
|
+
attempt += 1
|
|
149
|
+
continue
|
|
150
|
+
if (res.status == 429 or (res.status >= 500 and request.retryable)) and not last:
|
|
151
|
+
self._pause(_wait_for(res, attempt))
|
|
152
|
+
attempt += 1
|
|
153
|
+
continue
|
|
154
|
+
return _decode(res)
|
|
155
|
+
|
|
156
|
+
def _pause(self, seconds: float) -> None:
|
|
157
|
+
(self.options.sleep or time.sleep)(seconds)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _decode(res: TransportResponse) -> dict[str, Any]:
|
|
161
|
+
try:
|
|
162
|
+
data = json.loads(res.body.decode("utf-8", "replace"))
|
|
163
|
+
except ValueError:
|
|
164
|
+
data = None
|
|
165
|
+
obj = data if isinstance(data, dict) else None
|
|
166
|
+
if 200 <= res.status < 300 and obj is not None and obj.get("success") is True:
|
|
167
|
+
return obj
|
|
168
|
+
e = obj.get("error") if obj and isinstance(obj.get("error"), dict) else {}
|
|
169
|
+
s = res.status
|
|
170
|
+
code = e["code"] if isinstance(e.get("code"), str) else ("SERVER_ERROR" if s >= 500 else "INVALID_RESPONSE")
|
|
171
|
+
message = e["message"] if isinstance(e.get("message"), str) else ("QMGateway had a problem. Please try again shortly." if s >= 500 else "QMGateway sent an answer this SDK cannot read.")
|
|
172
|
+
rid = e["request_id"] if isinstance(e.get("request_id"), str) else res.headers.get("x-request-id")
|
|
173
|
+
details = e["details"] if isinstance(e.get("details"), dict) else {}
|
|
174
|
+
if s == 401: raise AuthenticationError(message, s, code, rid, details)
|
|
175
|
+
if s == 403: raise PermissionDeniedError(message, s, code, rid, details)
|
|
176
|
+
if s == 404: raise NotFoundError(message, s, code, rid, details)
|
|
177
|
+
if s == 409: raise ConflictError(message, s, code, rid, details)
|
|
178
|
+
if s == 429:
|
|
179
|
+
ra = res.headers.get("retry-after")
|
|
180
|
+
raise RateLimitError(message, s, code, rid, details, int(ra) if ra is not None and ra.isdigit() else None)
|
|
181
|
+
if s >= 500: raise ServerError(message, s, code, rid, details)
|
|
182
|
+
if s >= 400: raise InvalidRequestError(message, s, code, rid, details)
|
|
183
|
+
raise ApiError(message, s, code, rid, details)
|