qmgateway 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.
qmgateway/__init__.py ADDED
@@ -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__"]
qmgateway/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from ._cli import main
4
+
5
+ sys.exit(main())
qmgateway/_cli.py ADDED
@@ -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())
qmgateway/_http.py ADDED
@@ -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)
qmgateway/client.py ADDED
@@ -0,0 +1,168 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import secrets
5
+ from datetime import datetime
6
+ from typing import Any, Iterator, Literal
7
+
8
+ from . import models as M
9
+ from ._http import HttpClient, Options
10
+
11
+ Raw = dict[str, Any]
12
+
13
+
14
+ def _data(a: Raw) -> Raw:
15
+ return a["data"] if isinstance(a.get("data"), dict) else {}
16
+
17
+
18
+ def _list(a: Raw) -> list[Raw]:
19
+ return a["data"] if isinstance(a.get("data"), list) else []
20
+
21
+
22
+ def _cursor(v: Any) -> int | None:
23
+ return None if v is None else int(v)
24
+
25
+
26
+ def _at(v: str | datetime) -> str:
27
+ return M.to_malawi_time(v) if isinstance(v, datetime) else v
28
+
29
+
30
+ class Messages:
31
+ def __init__(self, http: HttpClient) -> None:
32
+ self._http = http
33
+
34
+ def send(self, to: str | list[str], message: str, *, type: str | None = None, device_id: int | None = None,
35
+ scheduled_at: str | datetime | None = None, idempotency_key: str | None = None) -> M.SendResult:
36
+ """Queue a message for one number or a list of numbers.
37
+
38
+ An Idempotency-Key is added for you, so a retry after a timeout can never send twice. For jobs that may run again, pass your own.
39
+ ``scheduled_at`` is Malawi time as text ("2026-12-01 08:00:00") or a datetime.
40
+ """
41
+ body: Raw = ({"recipients": list(to)} if isinstance(to, (list, tuple)) else {"phone": to}) | {"message": message}
42
+ if type is not None: body["type"] = type
43
+ if device_id is not None: body["device_id"] = device_id
44
+ if scheduled_at is not None: body["scheduled_at"] = _at(scheduled_at)
45
+ if idempotency_key is not None and not re.fullmatch(r"[!-~]{1,255}", idempotency_key):
46
+ raise ValueError("idempotency_key must be 1 to 255 visible characters with no spaces.")
47
+ key = idempotency_key or secrets.token_hex(16)
48
+ return M.SendResult.from_dict(_data(self._http.request("POST", "/api/v1/messages", body=body, headers={"idempotency-key": key})))
49
+
50
+ def get(self, id: int) -> M.Message:
51
+ """One message and where it is now."""
52
+ return M.Message.from_dict(_data(self._http.request("GET", "/api/v1/message_status", query={"id": id})))
53
+
54
+ def list(self, *, status: str | None = None, phone: str | None = None, since: str | None = None, limit: int | None = None, before_id: int | None = None) -> M.Page[M.Message]:
55
+ """One page of messages, newest first. Pass ``next_cursor`` as ``before_id`` for the next page."""
56
+ a = self._http.request("GET", "/api/v1/messages", query={"status": status, "phone": phone, "since": since, "limit": limit, "before_id": before_id})
57
+ return M.Page([M.Message.from_dict(x) for x in _list(a)], _cursor(a.get("next_before_id")))
58
+
59
+ def each(self, *, status: str | None = None, phone: str | None = None, since: str | None = None, page_size: int = 100) -> Iterator[M.Message]:
60
+ """Every matching message, newest first. Fetches the next page when you reach the end of the one before."""
61
+ cursor: int | None = None
62
+ while True:
63
+ page = self.list(status=status, phone=phone, since=since, limit=page_size, before_id=cursor)
64
+ yield from page.items
65
+ cursor = page.next_cursor
66
+ if cursor is None:
67
+ return
68
+
69
+ def scheduled(self, *, limit: int | None = None, after_id: int | None = None) -> M.Page[M.ScheduledMessage]:
70
+ a = self._http.request("GET", "/api/v1/scheduled", query={"limit": limit, "after_id": after_id})
71
+ return M.Page([M.ScheduledMessage.from_dict(x) for x in _list(a)], _cursor(a.get("next_after_id")))
72
+
73
+ def each_scheduled(self, *, page_size: int = 100) -> Iterator[M.ScheduledMessage]:
74
+ cursor: int | None = None
75
+ while True:
76
+ page = self.scheduled(limit=page_size, after_id=cursor)
77
+ yield from page.items
78
+ cursor = page.next_cursor
79
+ if cursor is None:
80
+ return
81
+
82
+ def cancel(self, id: int) -> Raw:
83
+ """Cancel a scheduled message. Its SMS units go back to your balance. Returns id, status, remaining_units."""
84
+ return _data(self._http.request("POST", "/api/v1/message_cancel", body={"id": id}))
85
+
86
+ def reschedule(self, id: int, scheduled_at: str | datetime) -> Raw:
87
+ """Move a scheduled message to a new time. Returns id, status, scheduled_at."""
88
+ return _data(self._http.request("POST", "/api/v1/message_reschedule", body={"id": id, "scheduled_at": _at(scheduled_at)}))
89
+
90
+
91
+ class Inbox:
92
+ """Replies received on your gateway phones, oldest first."""
93
+
94
+ def __init__(self, http: HttpClient) -> None:
95
+ self._http = http
96
+
97
+ def list(self, *, after_id: int | None = None, sender: str | None = None, limit: int | None = None) -> M.Page[M.InboxMessage]:
98
+ a = self._http.request("GET", "/api/v1/inbox", query={"after_id": after_id, "from": sender, "limit": limit})
99
+ return M.Page([M.InboxMessage.from_dict(x) for x in _list(a)], _cursor(a.get("next_after_id")))
100
+
101
+ def each(self, *, sender: str | None = None, after_id: int | None = None, page_size: int = 100) -> Iterator[M.InboxMessage]:
102
+ cursor = after_id
103
+ while True:
104
+ page = self.list(after_id=cursor, sender=sender, limit=page_size)
105
+ yield from page.items
106
+ cursor = page.next_cursor
107
+ if cursor is None:
108
+ return
109
+
110
+
111
+ class Devices:
112
+ def __init__(self, http: HttpClient) -> None:
113
+ self._http = http
114
+
115
+ def list(self) -> list[M.Device]:
116
+ return [M.Device.from_dict(x) for x in _list(self._http.request("GET", "/api/v1/devices"))]
117
+
118
+
119
+ class Otp:
120
+ """One-time passwords by SMS or email."""
121
+
122
+ def __init__(self, http: HttpClient) -> None:
123
+ self._http = http
124
+
125
+ def send(self, *, channel: Literal["sms", "email"] = "sms", phone: str | None = None, email: str | None = None, purpose: str | None = None, expiry_seconds: int | None = None) -> M.OtpRequest:
126
+ """Send a code. Retried only after a 429, so a code is never sent twice by accident."""
127
+ body = {k: v for k, v in {"channel": channel, "phone": phone, "email": email, "purpose": purpose, "expiry_seconds": expiry_seconds}.items() if v is not None}
128
+ return M.OtpRequest.from_dict(_data(self._http.request("POST", "/api/v1/otp/send", body=body, safe_to_repeat=False)))
129
+
130
+ def verify(self, request_reference: str, code: str) -> M.OtpVerification:
131
+ """A wrong or expired code gives verified = False. It is only an error when the request itself is wrong."""
132
+ return M.OtpVerification.from_dict(_data(self._http.request("POST", "/api/v1/otp/verify", body={"request_reference": request_reference, "code": code}, safe_to_repeat=False)))
133
+
134
+
135
+ class Account:
136
+ def __init__(self, http: HttpClient) -> None:
137
+ self._http = http
138
+
139
+ def get(self) -> M.Account:
140
+ return M.Account.from_dict(_data(self._http.request("GET", "/api/v1/account")))
141
+
142
+ def balance(self) -> M.Balance:
143
+ return M.Balance.from_dict(_data(self._http.request("GET", "/api/v1/balance")))
144
+
145
+ def statistics(self, *, period: str | None = None, start_date: str | None = None, end_date: str | None = None) -> M.Statistics:
146
+ return M.Statistics.from_dict(self._http.request("GET", "/api/v1/statistics", query={"period": period, "start_date": start_date, "end_date": end_date}))
147
+
148
+
149
+ class QMGateway:
150
+ """The entry point.
151
+
152
+ qm = QMGateway(os.environ["QMGATEWAY_API_KEY"])
153
+ sent = qm.messages.send("+265999123456", "Your order is ready.")
154
+ """
155
+
156
+ def __init__(self, api_key: str, options: Options | None = None) -> None:
157
+ http = HttpClient(api_key, options or Options())
158
+ self.options = http.options
159
+ self.messages = Messages(http)
160
+ self.inbox = Inbox(http)
161
+ self.devices = Devices(http)
162
+ self.otp = Otp(http)
163
+ self.account = Account(http)
164
+
165
+ @classmethod
166
+ def for_test(cls, api_key: str, options: Options | None = None) -> QMGateway:
167
+ """Same as the constructor; reads better with a test key (qm_test_...): nothing reaches a phone and no units are used."""
168
+ return cls(api_key, options)
qmgateway/errors.py ADDED
@@ -0,0 +1,48 @@
1
+ """Everything this SDK raises is a QMGatewayError, so one ``except`` can handle it all."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Literal
5
+
6
+
7
+ class QMGatewayError(Exception):
8
+ pass
9
+
10
+
11
+ class ApiError(QMGatewayError):
12
+ """QMGateway answered with an error. Branch on ``code`` (stable); show ``message`` to people (it may be reworded)."""
13
+
14
+ def __init__(self, message: str, status: int, code: str, request_id: str | None = None, details: dict[str, Any] | None = None) -> None:
15
+ super().__init__(f"{message} (request {request_id})" if request_id else message)
16
+ self.message = message
17
+ self.status = status
18
+ self.code = code
19
+ self.request_id = request_id
20
+ #: Extra facts for some codes, for example remaining_units for INSUFFICIENT_BALANCE.
21
+ self.details = details or {}
22
+
23
+
24
+ class AuthenticationError(ApiError): ...
25
+ class PermissionDeniedError(ApiError): ...
26
+ class InvalidRequestError(ApiError): ...
27
+ class NotFoundError(ApiError): ...
28
+ class ConflictError(ApiError): ...
29
+ class ServerError(ApiError): ...
30
+
31
+
32
+ class RateLimitError(ApiError):
33
+ def __init__(self, message: str, status: int, code: str, request_id: str | None, details: dict[str, Any] | None, retry_after: int | None) -> None:
34
+ super().__init__(message, status, code, request_id, details)
35
+ #: Seconds the server asked you to wait, when it said.
36
+ self.retry_after = retry_after
37
+
38
+
39
+ class QMConnectionError(QMGatewayError):
40
+ """No answer could be read (DNS, connection, TLS or timeout), after the retries were used up."""
41
+
42
+
43
+ class SignatureError(QMGatewayError):
44
+ """A webhook request is not genuine. ``reason`` is bad_signature, stale_timestamp or missing_header. Answer 401 and do nothing else."""
45
+
46
+ def __init__(self, reason: Literal["bad_signature", "stale_timestamp", "missing_header"]) -> None:
47
+ super().__init__(f"The webhook could not be verified: {reason}")
48
+ self.reason = reason
qmgateway/models.py ADDED
@@ -0,0 +1,266 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass, field
5
+ from datetime import datetime, timedelta, timezone
6
+ from typing import Any, Generic, TypeVar
7
+
8
+ Raw = dict[str, Any]
9
+ MALAWI = timezone(timedelta(hours=2), "Africa/Blantyre")
10
+ T = TypeVar("T")
11
+
12
+
13
+ def parse_time(v: Any) -> datetime | None:
14
+ """Reads the dates QMGateway sends. "2026-11-19 10:29:41" is Malawi time (UTC+2); "2026-12-01T08:00:00+02:00" has its own offset."""
15
+ if not isinstance(v, str) or not v:
16
+ return None
17
+ try:
18
+ d = datetime.fromisoformat(v)
19
+ except ValueError:
20
+ return None
21
+ return d if d.tzinfo else d.replace(tzinfo=MALAWI)
22
+
23
+
24
+ def to_malawi_time(d: datetime) -> str:
25
+ """Malawi time as the API wants it when you schedule: "2026-12-01 08:00:00". A naive datetime is taken as Malawi time."""
26
+ if d.tzinfo is not None:
27
+ d = d.astimezone(MALAWI)
28
+ return d.strftime("%Y-%m-%d %H:%M:%S")
29
+
30
+
31
+ def _s(v: Any) -> str: return "" if v is None else str(v)
32
+ def _i(v: Any, d: int = 0) -> int: return d if v is None else int(v)
33
+ def _n(v: Any) -> str | None: return None if v is None else str(v)
34
+
35
+
36
+ @dataclass(frozen=True, slots=True)
37
+ class Message:
38
+ id: int
39
+ phone_number: str
40
+ status: str
41
+ message_type: str
42
+ sms_units: int
43
+ scheduled_time: datetime | None
44
+ created_at: datetime | None
45
+ sent_at: datetime | None
46
+ delivered_at: datetime | None
47
+ failed_at: datetime | None
48
+ failure_reason: str | None
49
+ mode: str | None
50
+ raw: Raw = field(repr=False, compare=False)
51
+
52
+ @classmethod
53
+ def from_dict(cls, d: Raw) -> Message:
54
+ return cls(_i(d["id"]), _s(d["phone_number"]), _s(d["status"]), _s(d.get("message_type")), _i(d.get("sms_units"), 1), parse_time(d.get("scheduled_time")),
55
+ parse_time(d.get("created_at")), parse_time(d.get("sent_at")), parse_time(d.get("delivered_at")), parse_time(d.get("failed_at")),
56
+ _n(d.get("failure_reason")), _n(d.get("mode")), d)
57
+
58
+ @property
59
+ def is_delivered(self) -> bool: return self.status == "Delivered"
60
+ @property
61
+ def is_failed(self) -> bool: return self.status == "Failed"
62
+ @property
63
+ def is_finished(self) -> bool:
64
+ """Delivered, failed or cancelled: nothing more will happen to it."""
65
+ return self.status in ("Delivered", "Failed", "Cancelled")
66
+
67
+
68
+ @dataclass(frozen=True, slots=True)
69
+ class SendResult:
70
+ message_ids: list[int]
71
+ recipients: int
72
+ sms_units: int
73
+ status: str
74
+ remaining_units: int
75
+ idempotent_replay: bool
76
+ numbers: list[str]
77
+ raw: Raw = field(repr=False, compare=False)
78
+
79
+ @classmethod
80
+ def from_dict(cls, d: Raw) -> SendResult:
81
+ return cls([int(x) for x in d.get("message_ids", [])], _i(d.get("recipients")), _i(d.get("sms_units")), _s(d.get("status")), _i(d.get("remaining_units")),
82
+ bool(d.get("idempotent_replay", False)), [str(x) for x in d.get("numbers", [])], d)
83
+
84
+ @property
85
+ def message_id(self) -> int:
86
+ """The id of the message, when you sent to one number."""
87
+ if not self.message_ids:
88
+ raise LookupError("No message was queued.")
89
+ return self.message_ids[0]
90
+
91
+
92
+ @dataclass(frozen=True, slots=True)
93
+ class InboxMessage:
94
+ id: int
95
+ sender: str # the API calls it "from"
96
+ message: str
97
+ received_at: datetime | None
98
+ raw: Raw = field(repr=False, compare=False)
99
+
100
+ @classmethod
101
+ def from_dict(cls, d: Raw) -> InboxMessage:
102
+ return cls(_i(d["id"]), _s(d["from"]), _s(d["message"]), parse_time(d.get("received_at")), d)
103
+
104
+
105
+ @dataclass(frozen=True, slots=True)
106
+ class ScheduledMessage:
107
+ id: int
108
+ phone_number: str
109
+ message: str
110
+ sms_units: int
111
+ scheduled_at: datetime | None
112
+ created_at: datetime | None
113
+ raw: Raw = field(repr=False, compare=False)
114
+
115
+ @classmethod
116
+ def from_dict(cls, d: Raw) -> ScheduledMessage:
117
+ return cls(_i(d["id"]), _s(d["phone_number"]), _s(d.get("message")), _i(d.get("sms_units"), 1), parse_time(d.get("scheduled_at")), parse_time(d.get("created_at")), d)
118
+
119
+
120
+ @dataclass(frozen=True, slots=True)
121
+ class Device:
122
+ id: int
123
+ name: str
124
+ status: str
125
+ last_seen_at: datetime | None
126
+ networks: list[str]
127
+ capacity: int
128
+ queued: int
129
+ raw: Raw = field(repr=False, compare=False)
130
+
131
+ @classmethod
132
+ def from_dict(cls, d: Raw) -> Device:
133
+ return cls(_i(d["id"]), _s(d["name"]), _s(d["status"]), parse_time(d.get("last_seen_at")), [str(x) for x in d.get("networks", [])], _i(d.get("capacity"), 1), _i(d.get("queued")), d)
134
+
135
+ @property
136
+ def is_online(self) -> bool: return self.status == "online"
137
+
138
+
139
+ @dataclass(frozen=True, slots=True)
140
+ class EmailOtpBalance:
141
+ included: bool
142
+ quota: int
143
+ used: int
144
+ remaining: int
145
+ period_start: str | None
146
+ resets_at: str | None
147
+
148
+
149
+ @dataclass(frozen=True, slots=True)
150
+ class Balance:
151
+ active: bool
152
+ plan: str | None
153
+ quota: int
154
+ used: int
155
+ reserved: int
156
+ remaining: int
157
+ percent_left: int
158
+ level: str
159
+ starts_at: str | None
160
+ expires_at: str | None
161
+ days_left: int | None
162
+ email_otp: EmailOtpBalance | None
163
+ raw: Raw = field(repr=False, compare=False)
164
+
165
+ @classmethod
166
+ def from_dict(cls, d: Raw) -> Balance:
167
+ e = d.get("email_otp")
168
+ eo = EmailOtpBalance(bool(e.get("included")), _i(e.get("quota")), _i(e.get("used")), _i(e.get("remaining")), _n(e.get("period_start")), _n(e.get("resets_at"))) if isinstance(e, dict) else None
169
+ return cls(bool(d["active"]), _n(d.get("plan")), _i(d["quota"]), _i(d["used"]), _i(d["reserved"]), _i(d["remaining"]), _i(d["percent_left"]), _s(d["level"]),
170
+ _n(d.get("starts_at")), _n(d.get("expires_at")), None if d.get("days_left") is None else int(d["days_left"]), eo, d)
171
+
172
+ @property
173
+ def is_low(self) -> bool: return self.level in ("low", "critical", "empty")
174
+
175
+
176
+ @dataclass(frozen=True, slots=True)
177
+ class Service:
178
+ key: str
179
+ name: str
180
+ status: str
181
+ details: Raw
182
+
183
+ @property
184
+ def ready_to_send(self) -> bool:
185
+ """True when a message could go out right now (plan active, SMS left, a phone online)."""
186
+ return bool(self.details.get("ready_to_send", False))
187
+
188
+
189
+ @dataclass(frozen=True, slots=True)
190
+ class Account:
191
+ organisation_id: int
192
+ organisation_name: str
193
+ key_mode: str
194
+ scopes: list[str]
195
+ services: list[Service]
196
+ raw: Raw = field(repr=False, compare=False)
197
+
198
+ @classmethod
199
+ def from_dict(cls, d: Raw) -> Account:
200
+ org, key = d.get("organisation") or {}, d.get("key") or {}
201
+ return cls(_i(org.get("id")), _s(org.get("name")), _s(key.get("mode", "live")), [str(x) for x in key.get("scopes", [])],
202
+ [Service(_s(s["key"]), _s(s["name"]), _s(s["status"]), s.get("details") or {}) for s in d.get("services", [])], d)
203
+
204
+ def service(self, key: str) -> Service | None:
205
+ return next((s for s in self.services if s.key == key), None)
206
+
207
+ @property
208
+ def is_test_key(self) -> bool: return self.key_mode == "test"
209
+
210
+
211
+ @dataclass(frozen=True, slots=True)
212
+ class OtpRequest:
213
+ request_reference: str
214
+ expires_in: int
215
+ status: str
216
+ channel: str
217
+ email_otp_remaining: int | None
218
+ email_otp_resets_at: str | None
219
+ raw: Raw = field(repr=False, compare=False)
220
+
221
+ @classmethod
222
+ def from_dict(cls, d: Raw) -> OtpRequest:
223
+ return cls(_s(d["request_reference"]), _i(d["expires_in"]), _s(d["status"]), _s(d["channel"]), None if d.get("email_otp_remaining") is None else int(d["email_otp_remaining"]), _n(d.get("email_otp_resets_at")), d)
224
+
225
+
226
+ @dataclass(frozen=True, slots=True)
227
+ class OtpVerification:
228
+ """The answer to a code check. A wrong code is a normal answer (verified False), not an error."""
229
+ verified: bool
230
+ status: str
231
+
232
+ @classmethod
233
+ def from_dict(cls, d: Raw) -> OtpVerification:
234
+ return cls(bool(d["verified"]), _s(d["status"]))
235
+
236
+
237
+ @dataclass(frozen=True, slots=True)
238
+ class Statistics:
239
+ overview: dict[str, int]
240
+ quota: Raw
241
+ recent_messages: list[Raw]
242
+ daily: list[Raw]
243
+ status_distribution: list[Raw]
244
+ top_recipients: list[Raw]
245
+ counts: dict[str, int]
246
+ period: Raw
247
+ raw: Raw = field(repr=False, compare=False)
248
+
249
+ @classmethod
250
+ def from_dict(cls, d: Raw) -> Statistics:
251
+ s = d.get("statistics") or {}
252
+ return cls(s.get("overview", {}), s.get("quota", {}), s.get("recent_messages", []), s.get("daily", []), s.get("status_distribution", []), s.get("top_recipients", []), s.get("counts", {}), d.get("period", {}), d)
253
+
254
+
255
+ @dataclass(frozen=True, slots=True)
256
+ class Page(Generic[T]):
257
+ """One page of a list, and where the next one starts (None when there is no more)."""
258
+ items: list[T]
259
+ next_cursor: int | None
260
+
261
+ def __iter__(self): # type: ignore[no-untyped-def]
262
+ return iter(self.items)
263
+
264
+ def __len__(self) -> int: return len(self.items)
265
+ @property
266
+ def has_more(self) -> bool: return self.next_cursor is not None
qmgateway/py.typed ADDED
File without changes
qmgateway/testing.py ADDED
@@ -0,0 +1,47 @@
1
+ """A pretend network for your own tests.
2
+
3
+ fake = FakeTransport().queue_json({"success": True, "data": {}}, 202)
4
+ qm = QMGateway("qm_test_x", Options(transport=fake))
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from typing import Any
10
+
11
+ from ._http import TransportRequest, TransportResponse
12
+ from .errors import QMConnectionError
13
+
14
+
15
+ class FakeTransport:
16
+ def __init__(self) -> None:
17
+ self.requests: list[TransportRequest] = []
18
+ self._answers: list[TransportResponse | QMConnectionError] = []
19
+
20
+ def queue_raw(self, status: int, body: str, headers: dict[str, str] | None = None) -> FakeTransport:
21
+ self._answers.append(TransportResponse(status, {k.lower(): v for k, v in (headers or {}).items()}, body.encode()))
22
+ return self
23
+
24
+ def queue_json(self, data: Any, status: int = 200, headers: dict[str, str] | None = None) -> FakeTransport:
25
+ return self.queue_raw(status, json.dumps(data), headers)
26
+
27
+ def queue_error(self, status: int, code: str, message: str = "Error", *, headers: dict[str, str] | None = None, details: dict[str, Any] | None = None) -> FakeTransport:
28
+ return self.queue_json({"success": False, "error": {"code": code, "message": message, "request_id": "req_fake", "details": details or {}}}, status, headers)
29
+
30
+ def queue_network_error(self, message: str = "Could not connect") -> FakeTransport:
31
+ self._answers.append(QMConnectionError(message))
32
+ return self
33
+
34
+ def __call__(self, request: TransportRequest) -> TransportResponse:
35
+ self.requests.append(request)
36
+ if not self._answers:
37
+ raise AssertionError(f"FakeTransport has no answer queued for {request.method} {request.url}")
38
+ nxt = self._answers.pop(0)
39
+ if isinstance(nxt, QMConnectionError):
40
+ raise nxt
41
+ return nxt
42
+
43
+ @property
44
+ def last(self) -> TransportRequest:
45
+ if not self.requests:
46
+ raise AssertionError("Nothing was sent yet.")
47
+ return self.requests[-1]
qmgateway/webhook.py ADDED
@@ -0,0 +1,65 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import json
6
+ import time
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Mapping
9
+
10
+ from .errors import SignatureError
11
+ from .models import parse_time
12
+ from datetime import datetime
13
+
14
+ WEBHOOK_TOLERANCE = 300
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class WebhookEvent:
19
+ """A verified webhook delivery. Types: sms.incoming, sms.sent, sms.delivered, sms.failed, webhook.test."""
20
+ type: str
21
+ id: str
22
+ attempt: int
23
+ data: dict[str, Any] = field(repr=False)
24
+
25
+ @property
26
+ def message_id(self) -> int | None: return None if self.data.get("message_id") is None else int(self.data["message_id"])
27
+ @property
28
+ def phone_number(self) -> str | None: return None if self.data.get("phone_number") is None else str(self.data["phone_number"])
29
+ @property
30
+ def status(self) -> str | None: return None if self.data.get("status") is None else str(self.data["status"])
31
+ @property
32
+ def updated_at(self) -> datetime | None: return parse_time(self.data.get("updated_at"))
33
+ @property
34
+ def is_test(self) -> bool: return self.type == "webhook.test"
35
+
36
+
37
+ def verify_webhook(body: str | bytes, headers: Mapping[str, str], secret: str, *, tolerance: int = WEBHOOK_TOLERANCE, now: int | None = None) -> WebhookEvent:
38
+ """Check that a webhook really came from QMGateway. Pass the RAW body exactly as received, not re-encoded JSON.
39
+
40
+ Raises SignatureError when it is not genuine. ``now`` is unix seconds (tests pass a fixed one).
41
+ """
42
+ h = {k.lower(): v for k, v in headers.items()}
43
+ signature, timestamp = h.get("x-qmgateway-signature", ""), h.get("x-qmgateway-timestamp", "")
44
+ if not signature or not timestamp:
45
+ raise SignatureError("missing_header")
46
+ if not (timestamp.isascii() and timestamp.isdigit()) or abs((int(time.time()) if now is None else now) - int(timestamp)) > tolerance:
47
+ raise SignatureError("stale_timestamp")
48
+ raw = body if isinstance(body, bytes) else body.encode("utf-8")
49
+ expected = "sha256=" + hmac.new(secret.encode(), timestamp.encode() + b"." + raw, hashlib.sha256).hexdigest()
50
+ if not hmac.compare_digest(expected.encode(), signature.encode()):
51
+ raise SignatureError("bad_signature")
52
+ try:
53
+ data = json.loads(raw)
54
+ except ValueError:
55
+ raise SignatureError("bad_signature") from None
56
+ if not isinstance(data, dict):
57
+ raise SignatureError("bad_signature")
58
+ return WebhookEvent(h.get("x-qmgateway-event", ""), h.get("x-qmgateway-event-id", ""), int(h.get("x-qmgateway-attempt", "1") or 1), data)
59
+
60
+
61
+ def sign_webhook(body: str, secret: str, *, event: str = "sms.delivered", timestamp: int | None = None, event_id: str = "evt_test") -> tuple[str, dict[str, str]]:
62
+ """Make a correctly signed request, for testing your own webhook handler. Returns (body, headers)."""
63
+ t = str(int(time.time()) if timestamp is None else timestamp)
64
+ sig = "sha256=" + hmac.new(secret.encode(), t.encode() + b"." + body.encode(), hashlib.sha256).hexdigest()
65
+ return body, {"X-QMGateway-Timestamp": t, "X-QMGateway-Signature": sig, "X-QMGateway-Event": event, "X-QMGateway-Event-ID": event_id, "X-QMGateway-Attempt": "1"}
@@ -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,16 @@
1
+ qmgateway/__init__.py,sha256=ofYl_I1RDbh3vQNONl2aSIuhDV7l0GwlwZy5olu9v_c,884
2
+ qmgateway/__main__.py,sha256=arq9FhDc5f2AZchKpqlkQwTT-bKvMcj3iAXJg8GRLCc,53
3
+ qmgateway/_cli.py,sha256=rVKWBf1QuZ3ObNIfEMYxFs65uD1u6CxHsKqOyhaYYPQ,4593
4
+ qmgateway/_http.py,sha256=KGBoUtpzdqkvRq-pQhagOWDITbKkwd7NPJgeITaK2Zc,8302
5
+ qmgateway/client.py,sha256=Ex9QXWQlD0eGTsCirI0Q8XowS2rPNC7c_awAqo8IEIE,8058
6
+ qmgateway/errors.py,sha256=S6lT5erRRVYi5d7DpDzY75YWPtZmGccDZnNSgJ7lzTI,1957
7
+ qmgateway/models.py,sha256=0Llot238y8iAr7dXogaNL9EcAYo-cwNFAnG8DxkLUTg,8891
8
+ qmgateway/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ qmgateway/testing.py,sha256=A213fo379Pibv0rRK6z2vxbGpoNdKl0Q6WAIXjvkwb0,1999
10
+ qmgateway/webhook.py,sha256=DPVw83NC74DYDJP0r-0Z3Epk9HZ5Pr5_C0tfkj7T1Oc,3199
11
+ qmgateway-0.1.0.dist-info/licenses/LICENSE,sha256=0P6B5OgxNZb3CmnGhqYLZRbj45k0m08SiCiTYTQgZbc,1066
12
+ qmgateway-0.1.0.dist-info/METADATA,sha256=LlcPefDGM1AlHOiR6DqrceJCNHLjUuSTToYwOsFdms8,5427
13
+ qmgateway-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
14
+ qmgateway-0.1.0.dist-info/entry_points.txt,sha256=P8FAWHZK5mEGvyMxROS4Q_qm957hamSys8dig87GcMU,50
15
+ qmgateway-0.1.0.dist-info/top_level.txt,sha256=NE9T70sQTMnhWGp1CJu_8-cCeLIwP5KRz6rC9TAdH_A,10
16
+ qmgateway-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ qmgateway = qmgateway._cli:main
@@ -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.
@@ -0,0 +1 @@
1
+ qmgateway