Metadata-Version: 2.4
Name: ody-sdk
Version: 0.7.0
Summary: Official Python SDK for the Ody REST API (contacts, conversations, messaging, calls, numbers, AI agent, webhooks) with webhook verification and event parsing.
License: MIT
Project-URL: Homepage, https://ody.co
Project-URL: Documentation, https://dev.ody.co/sdks/python
Project-URL: API reference, https://dev.ody.co/api/overview
Project-URL: Source, https://github.com/CosmicHero2/ody-platform/tree/main/sdks/python
Keywords: ody,sms,mms,voice,ai-agent,contacts,webhooks,api,sdk
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Communications :: Telephony
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# ody-sdk

Official Python SDK for the [Ody REST API](https://dev.ody.co/api/overview) — contacts, conversations, SMS/MMS sending, calls and the AI agent, phone numbers, and outbound webhooks. Docs: [dev.ody.co/sdks/python](https://dev.ody.co/sdks/python).

- **Standard library only** — no dependencies (`urllib.request`, `hmac`, `hashlib`).
- Python ≥ 3.9, type hints throughout.
- Auto-pagination generators, typed errors, idempotent sends, Standard-Webhooks verification and webhook event parsing built in.

## Install

```bash
pip install ody-sdk
```

Published on [PyPI](https://pypi.org/project/ody-sdk/) since 0.6.0 (2026-11-04). To work from a checkout instead (for example to test an unreleased change):

```bash
pip install /path/to/ody-platform/sdks/python
# or for development:
pip install -e sdks/python
```

## Quickstart

```python
from ody import Ody, OdyError

# Keys come from Settings → Developer API. ody_test_... keys behave identically
# but message sends are simulated (no real SMS).
client = Ody("ody_live_...")
# Override the origin if you call the Cloud Run URL directly:
# client = Ody(key, base_url="https://ody-api-rtvqk5tg2a-uc.a.run.app")

# Contacts
page = client.contacts.list(q="acme", limit=50)   # {"contacts": [...], "nextCursor": ...}
contact = client.contacts.create(
    first_name="Ada",
    last_name="Lovelace",
    phone="+15125550123",
    tags=["vip"],
)

# Auto-pagination: iterate every contact, following nextCursor for you.
for c in client.contacts.list_all():
    print(c["id"], c["firstName"])

# Conversations
open_page = client.conversations.list(status="open")
thread = client.conversations.get(open_page["conversations"][0]["id"])
client.conversations.set_status(thread["conversation"]["id"], "done")

# Send an SMS (idempotent — safe to retry with the same key for 24h)
sent = client.messages.send(
    to="+15125550123",
    body="Your order shipped!",
    idempotency_key="order-1042-shipped",
)
print(sent["conversationId"], sent.get("simulated", False))

# Search, calls, numbers
hits = client.messages.search("refund", limit=10)
calls = client.calls.list(limit=100)
numbers = client.numbers.list()
```

## Error handling

Every non-2xx response raises `OdyError` carrying the structured body plus HTTP status:

```python
try:
    client.contacts.get("00000000-0000-0000-0000-000000000000")
except OdyError as err:
    print(err.code)        # "not_found", "resource_exhausted", ...
    print(err.status)      # 404, 429, ...
    print(err.request_id)  # quote this to support
    if err.status == 429:
        print(f"retry in {err.retry_after}s")  # from Retry-After
```

Rate limit: 600 requests/minute per key; every response carries `RateLimit-*` headers and a 429 adds `Retry-After` (surfaced as `err.retry_after`).

## Webhooks

Register endpoints and verify deliveries per [Standard Webhooks](https://www.standardwebhooks.com). The signing secret (`whsec_...`) is returned **only** by `create` and `rotate` — store it immediately.

```python
catalog = client.webhooks.event_types()
hook = client.webhooks.create(
    url="https://example.com/ody-webhook",
    events=["*"],
    label="prod",
)
print(hook["secret"])  # whsec_... — shown once!

client.webhooks.test(hook["id"])                  # signed {"type": "ping"} delivery
deliveries = client.webhooks.deliveries(hook["id"])  # debugging view
```

### Verifying deliveries

`verify_webhook_signature` checks the `v1,<base64 HMAC-SHA256>` signature over `<webhook-id>.<webhook-timestamp>.<raw body>` in constant time and rejects timestamps older than 5 minutes (replay guard). **Pass the raw body bytes** — re-serializing parsed JSON breaks the signature.

```python
import json
import os

from flask import Flask, request
from ody import verify_webhook_signature

app = Flask(__name__)

@app.post("/ody-webhook")
def ody_webhook():
    ok = verify_webhook_signature(
        os.environ["ODY_WEBHOOK_SECRET"],
        request.headers,       # any case-insensitive mapping works
        request.get_data(),    # RAW bytes, not request.json
    )
    if not ok:
        return "", 401

    event = json.loads(request.get_data())
    print("verified event:", event["type"])
    return "", 200
```

### One step: `parse_webhook_event`

Verify and parse together. Returns the envelope dict (`id`, `apiVersion`, `createdAt`, `type`, `data`); raises `WebhookVerificationError` on a bad or stale signature or a malformed body.

```python
from ody import parse_webhook_event, WebhookVerificationError, WEBHOOK_EVENT_TYPES, is_known_webhook_event_type

@app.post("/ody-webhook")
def ody_webhook():
    try:
        event = parse_webhook_event(os.environ["ODY_WEBHOOK_SECRET"], request.headers, request.get_data())
    except WebhookVerificationError:
        return "", 401
    if event["type"] == "call.ringing":
        screen_pop(event["data"]["from"], event["data"]["callerName"])
    elif event["type"] in ("contact.updated", "contact.deleted"):
        sync_contact(event["data"]["contactId"])
    elif not is_known_webhook_event_type(event["type"]):
        app.logger.info("new Ody event type %s", event["type"])
    return "", 200
```

`WEBHOOK_EVENT_TYPES` is the server catalog as a tuple (kept in step by `tests/events/sdkCatalogParity.test.ts` in the platform repo). Every event and its `data` fields: [dev.ody.co/webhooks/events](https://dev.ody.co/webhooks/events).

## API surface

| Group | Methods |
| --- | --- |
| `client.contacts` | `list`, `list_all` (generator), `create`, `get`, `update`, `delete` |
| `client.conversations` | `list`, `list_all`, `get`, `set_status` |
| `client.messages` | `send` (supports `idempotency_key`), `search` |
| `client.calls` | `list`, `place` (outbound AI call, scope `calls:place`) |
| `client.numbers` | `list`, `search_available`, `buy` (supports `idempotency_key`), `connect_agent`, `disconnect_agent` |
| `client.messaging` | `status`, `register` (10DLC brand + campaign), `refresh` |
| `client.agent` | `get`, `update`, `publish` |
| `client.knowledge` | `get`, `search`, `list_articles`, `get_article`, `create_article`, `update_article`, `delete_article`, `import_website`, `refresh_article`, `create_folder`, `update_folder`, `delete_folder` |
| `client.webhooks` | `list`, `create`, `get`, `update`, `delete`, `rotate`, `test`, `deliveries`, `event_types` |

### Agent Phone

Provision a working AI phone line end to end — everything an agent buys or
configures through the API appears in the customer's account exactly as if
they did it in the app (same billing, same gates, same timeline), and a human
can take over at any moment:

```python
candidate = client.numbers.search_available(starts_with="512")[0]
client.numbers.buy(candidate["phone_number"], idempotency_key="onboard-1")

client.messaging.register(business={
    "displayName": "Acme Plumbing", "email": "ops@acme.com", "vertical": "PROFESSIONAL",
    "companyName": "Acme Plumbing LLC", "ein": "12-3456789",
    "street": "600 Congress Ave", "city": "Austin", "state": "TX", "postalCode": "78701",
})

client.agent.update(name="Front Desk", greeting="Thanks for calling Acme!")
client.agent.publish()
client.numbers.connect_agent(candidate["phone_number"])

placed = client.calls.place(to="+15125550123")
```

Use an ``ody_test_...`` key to dry-run the whole flow: purchases, filings, and
calls are simulated — nothing is bought, filed, or dialed.

### Knowledge hub

Everything the AI agents (and the inbox's AI suggested replies) answer from
lives in the workspace's Knowledge hub — Markdown articles in nested folders.
Articles are live the moment they are saved; published agents are updated
automatically. Scopes ``knowledge:read`` / ``knowledge:write``.

```python
tree = client.knowledge.get()                      # folders, articles, consumers
sales = client.knowledge.create_folder("Sales line")

client.knowledge.import_website("https://acme.com", folder_id=sales["id"])
client.knowledge.create_article(
    title="Pricing",
    content="## Hourly rate\n$120/h, first hour minimum…",
    folder_id=sales["id"],
    audience="selected",
    consumers=["texting"] + [c["key"] for c in tree["consumers"] if c["name"] == "Sales desk"],
)

hits = client.knowledge.search("how much per hour", consumer="texting")
```

## Development

```bash
python3 -m py_compile ody/__init__.py ody/client.py ody/webhooks.py  # syntax check
python3 -m build                                                      # build sdist + wheel
```
