Metadata-Version: 2.5
Name: usenadia
Version: 0.1.1
Summary: Python SDK for the UseNadia public API — schedule posts, manage channels, run the Instagram comment/story → DM machinery
Project-URL: Homepage, https://usenadia.com
License: MIT
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: attrs>=22.2
Requires-Dist: httpx<1,>=0.23
Requires-Dist: python-dateutil>=2.8
Description-Content-Type: text/markdown

# usenadia

Python SDK for the **UseNadia** public API (`/public/v1`) — schedule posts,
manage channels, and drive the Instagram comment/story → DM machinery.

```bash
pip install usenadia
```

Requires Python 3.11+. Your API key is in the app, **Settings → Developers**.

## Quick start

The block below is not just an example: the smoke test
(`tests/test_smoke.py`) runs it, as written, against the real API before
every release. It drafts a post on your first Instagram channel, far in the
future, reads it back, then deletes it.

<!-- smoke:start -->
```python
import os

from usenadia import Nadia, NadiaError

nadia = Nadia(api_key=os.environ["NADIA_API_KEY"])

nadia.is_connected()  # raises NadiaError(401) on a bad key

channels = nadia.integrations()
instagram = next(c for c in channels if c["identifier"] == "instagram-standalone")

created = nadia.post({
    "type": "draft",  # "schedule" to publish at `date`, "now" to publish now
    "date": "2030-06-01T09:00:00.000Z",
    "shortLink": False,
    "tags": [],
    "posts": [{
        "integration": {"id": instagram["id"]},
        "value": [{"content": "Drafted from the Python SDK", "image": []}],
        "settings": {"post_type": "post"},
    }],
})
post_id = created[0]["postId"]

drafts = nadia.post_list(
    startDate="2030-06-01T00:00:00.000Z",
    endDate="2030-06-02T00:00:00.000Z",
)["posts"]
assert any(p["id"] == post_id and p["state"] == "DRAFT" for p in drafts)

nadia.delete_post(post_id)

try:
    nadia.post_list()  # startDate and endDate are required
except NadiaError as err:
    print(err.status, err)  # 400 startDate must be a valid ISO 8601 date string; ...
```
<!-- smoke:end -->

Each channel has its own required `settings` (TikTok: privacy, duet, stitch…;
Instagram: `post_type`). Ask the API for them:
`nadia.raw.get(f"/public/v1/integration-settings/{channel_id}").json()`.

## The content board

Every card of the board in the app is reachable: create one from anywhere
(a voice note, a Notion page, a DM), move it along, read its numbers once
it is published.

```python
card = nadia.create_content(
    "Three mistakes when moving to Malta",
    hook="Nobody told me about the third one.",
)

nadia.move_content(card["id"], "SCRIPT")
nadia.update_content(card["id"], script="…")

# Scheduled with nadia.post({..., "posts": [{"group": "g-42", ...}]}):
nadia.link_content_post(card["id"], "g-42")  # → PUBLISHED when it goes live

numbers = nadia.contents_performance()  # keyed by card id
```

Columns, in order: `IDEA`, `SCRIPT`, `VALIDATED`, `TO_SHOOT`, `TO_EDIT`,
`TO_SCHEDULE`, `PUBLISHED`.

## How it is built

Two layers, and the split is deliberate.

- **`usenadia/generated/`** — the transport. Generated from
  `openapi.public.json` by
  [`openapi-python-client`](https://github.com/openapi-generators/openapi-python-client)
  (httpx + attrs), covers every operation, never edited by hand, not
  committed.
- **`usenadia/__init__.py`** — this SDK's own surface: the `Nadia` class,
  sane defaults, typed errors, retries. Small, hand-written, reviewed.

Anything the facade does not wrap is reachable two ways:

- `nadia.typed` — the generated client, every operation with its models:

  ```python
  from usenadia.generated.api.public_api import list_webhook_events

  events = list_webhook_events.sync(client=nadia.typed)
  print([e.name for e in events.events])
  ```

- `nadia.raw` — the configured `httpx.Client` (base URL and key already set):
  `nadia.raw.get("/public/v1/integration-settings/<id>").json()`.

## Webhooks

UseNadia signs every webhook it sends: `X-Nadia-Signature` is `sha256=` +
the hex HMAC-SHA256 of `<X-Nadia-Timestamp>.<raw body>`, keyed with the
webhook's secret (returned once, when you create the webhook). Verify against
the **raw** body: parsing then re-serialising the JSON breaks the signature.

```python
from usenadia import parse_webhook, WebhookVerificationError

# Flask
@app.post("/nadia")
def nadia_webhook():
    try:
        delivery = parse_webhook(SECRET, request.headers, request.get_data())
    except WebhookVerificationError:
        return "", 401
    if delivery["event"] == "post.published":
        print(delivery["data"]["releaseURL"])
    return "", 204

# FastAPI
@app.post("/nadia")
async def nadia_webhook(request: Request):
    try:
        delivery = parse_webhook(SECRET, request.headers, await request.body())
    except WebhookVerificationError:
        raise HTTPException(status_code=401)
    ...
```

`parse_webhook` rejects a timestamp more than 5 minutes away
(`tolerance=300`, `None` to turn it off) and returns the envelope
`{"id", "event", "occurredAt", "organizationId", "data"}`. For the check
alone: `verify_webhook_signature(secret, signature, timestamp, body,
tolerance=None)` → `bool`.

## Errors

Every response with a status ≥ 400 raises a `NadiaError` carrying `status`,
`body` and the API's message (`str(err)`). `err.is_transient` is true for 429 and 5xx — those
are retried automatically (twice by default, `Nadia(key, retries=0)` to turn
it off).

## Regenerating

```bash
pnpm run sdk:generate   # from the repo root — regenerates both SDKs
```

## Tests

```bash
uv run --python 3.11 --with httpx --with pytest pytest tests/ -q
```

Offline by default. With `NADIA_API_KEY` set, `tests/test_smoke.py` also runs
against the real API (it only writes a 2030 draft, then deletes it). Releases
run it from the built wheel and refuse to publish if it fails — tag
`python-v<version>`, see `.github/workflows/publish-sdk-python.yml`.

Plan: `docs/roadmap/done/19-sdk-public-api.md`.
