Metadata-Version: 2.5
Name: msgine
Version: 1.0.0
Summary: Python client for the MsGine messaging API
Project-URL: Documentation, https://docs.msgine.net
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Description-Content-Type: text/markdown

# msgine

Python client for the MsGine messaging API: SMS, WhatsApp, email, push, workflows and webhooks.

Documentation: https://docs.msgine.net

## Install

```
pip install msgine
```

Requires Python 3.10 or newer. The only dependency is `httpx`.

## Quick start

```python
from msgine import MsGine

with MsGine("msg_<kid>_<secret>") as client:
    message = client.sms.send(to="+256700000001", message="Your code is 4821")
    print(message["id"], message["status"])
```

Async:

```python
import asyncio
from msgine import AsyncMsGine

async def main() -> None:
    async with AsyncMsGine("msg_<kid>_<secret>") as client:
        page = await client.sms.list(page=1, limit=20)
        print(page.total, len(page.items))

asyncio.run(main())
```

Both clients expose the same resources and methods. Parameters are keyword-only and snake_case
(`scheduled_for`, `idempotency_key`, `from_`); they are sent under their API names. Nested data such as
`payload`, `definition` or `android` is sent as given. Responses are plain dicts with the API's camelCase
keys. List calls return `Page(items, total, page, pages)`.

## Configuration

```python
MsGine(
    api_key,
    signing_secret=None,
    base_url="https://api.msgine.net/api/v1",
    timeout=30.0,
    max_retries=2,
    http_client=None,
)
```

`http_client` takes an `httpx.Client` (`httpx.AsyncClient` for `AsyncMsGine`) to share a connection pool or
set proxies. A client you pass in is not closed by `close()`.

## Sending

```python
client.sms.send(to=["+256700000001", "+256700000002"], message="Hello", scheduled_for="2026-12-25T09:00:00Z")

client.whatsapp.send(to="+256700000001", template_id="order_update", template_language="en",
                     template_params=["A-1042"])

client.email.send(from_="hello@example.com", to="user@example.com", subject="Receipt", html="<p>Thanks</p>")

client.push.send(title="Order shipped", body="On its way", external_user_ids=["user-42"])

client.events.send(name="order.created", payload={"orderId": "A-1042"}, phone="+256700000001")
```

Email is transactional only. Recipients may be a string or a list. Every send carries an idempotency key:
yours (`idempotency_key=`) or a generated one that is reused across retries.

Other resources: `messages`, `webhooks`, `workflows` (`runs`, `launches`, `hooks`, `secrets`,
`messaging_policy`), `opt_outs`, `contact_fields`, `analytics`, `push.devices`, `push.config`.

## Webhooks

Verify the raw request body, not re-serialised JSON.

```python
from fastapi import FastAPI, HTTPException, Request
from msgine import WebhookVerificationError, verify_webhook

app = FastAPI()

@app.post("/msgine")
async def receive(request: Request) -> dict[str, bool]:
    try:
        event = verify_webhook(
            await request.body(),
            request.headers.get("x-msgine-signature"),
            "whsec_...",
        )
    except WebhookVerificationError:
        raise HTTPException(status_code=400)
    print(event["event"], event["data"])
    return {"ok": True}
```

Signatures older than 300 seconds are refused; change it with `tolerance=`. Several `v1` signatures are
accepted, so a rotated secret can overlap.

## Errors and retries

API errors raise `MsGineError` with `status`, `code`, `message`, `details`, `retry_after` and `body`.
Network failures and timeouts raise `MsGineConnectionError` (`status` 0, `code` `connection_error` or
`timeout`).

```python
from msgine import MsGineError

try:
    client.sms.send(to="x", message="Hi")
except MsGineError as error:
    print(error.status, error.code, error.details)
```

Up to `max_retries` retries (default 2). A 429 is always retried. Network errors, 408 and 5xx are retried
only for requests that are safe to repeat: GET, PUT and DELETE, and sends, which carry an idempotency key.
The wait follows `Retry-After` (1 to 60 seconds) or backs off exponentially from 1 second.

## Sandbox keys

A key created with the sandbox environment validates and records requests but sends nothing and charges
nothing. Use one in tests and CI.

## Request signing

Pass `signing_secret` to sign every request with `x-timestamp` and `x-signature` headers (HMAC-SHA256 of
method, path and query, timestamp and body hash). A fresh signature is computed for each attempt.

```python
client = MsGine("msg_<kid>_<secret>", signing_secret="sk_...")
```
