Metadata-Version: 2.5
Name: kapso-python
Version: 0.1.0a4
Summary: Unofficial Python SDK for Kapso (WhatsApp Business): webhooks, typed payloads, and async and sync clients for sending.
Project-URL: Homepage, https://github.com/Joselier3/kapso-python
Project-URL: Repository, https://github.com/Joselier3/kapso-python
Project-URL: Issues, https://github.com/Joselier3/kapso-python/issues
Project-URL: Changelog, https://github.com/Joselier3/kapso-python/blob/main/CHANGELOG.md
Author: Elier Fajardo
License-Expression: MIT
License-File: LICENSE
Keywords: chatbot,kapso,sdk,webhooks,whatsapp,whatsapp-business
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: AsyncIO
Classifier: Framework :: Pydantic :: 2
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Communications :: Chat
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx<1,>=0.28.1
Requires-Dist: pydantic<3,>=2.14.4
Description-Content-Type: text/markdown

# kapso-python

[![CI](https://github.com/Joselier3/kapso-python/actions/workflows/ci.yml/badge.svg)](https://github.com/Joselier3/kapso-python/actions/workflows/ci.yml)

A Python SDK for [Kapso](https://kapso.ai) (WhatsApp Business), built from real webhook traffic.

> Unofficial, community-built: not affiliated with or endorsed by Kapso.
> Early and learning-driven (alpha): the API will change.

```bash
uv add kapso-python        # or: pip install kapso-python
```

```python
import kapso

if not kapso.verify(raw_body, headers.get("x-webhook-signature"), secret):
    ...  # reject: 401

for msg in kapso.parse(raw_body, headers.get("x-webhook-event")):
    print(msg.message_id, msg.content.kind, msg.text)

async with kapso.KapsoClient(api_key) as client:
    sent = await client.messages.send_text(phone_number_id, to="15551234567", body="Hola!")
    for msg in kapso.parse(raw_body, headers.get("x-webhook-event")):
        await client.messages.reply_text(msg, "Got it", quote=True)  # same number, same sender
```

## What works today

- **`verify()`**: checks Kapso's `X-Webhook-Signature` (HMAC-SHA256 of the raw body) in constant time, without crashing on malformed headers.
- **`parse()`**: the common case. Turns a verified delivery into the `list[InboundMessage]` a user just sent. Batches are flattened; status events, outbound echoes, imported history and passive messages (handled by another app) are left out.
- **`parse_event()`**: every Kapso WhatsApp event (12, plus `UnknownEvent` for anything new) as a typed object: `MessagesReceived`, `StatusUpdate`, `ConversationEvent`, `ConversationInactive`, `ContactIdentityChanged`, `MarketingPreferenceChanged`, `ThreadOwnershipChanged`, `ThreadStandby`.
- **Typed content**: `msg.content` is one of `Text`, `MediaMessage` (image, video, audio, document, sticker), `Location`, `Contacts`, `InteractiveReply` (button or list), `FlowReply`, `QuickReply`, `Reaction`, or `Unknown`, which keeps the raw message, so a new WhatsApp type never raises. `msg.text` is what to read: the body, a caption, a voice-note transcript, or the title of the option tapped.
- **Dedup keys**: every object an app should act on once has a `dedup_key` (the WAMID for a message, `wamid:status` for a status, ...).
- **`client.media.download()`**: the bytes of inbound media, capped in size, checked against WhatsApp's SHA-256, with a fallback to a fresh download URL when Kapso's copy fails.
- **Sending**: text, image, video, audio and voice notes, documents, stickers, locations, contact cards, reactions, reply buttons, lists, CTA links, location requests, WhatsApp Flows and templates, plus `mark_read` with a typing indicator. Each takes a phone number, a BSUID or `msg.sender`, and checks WhatsApp's limits before sending. `send_raw` sends any other payload as is, unchecked.
- **`client.media.upload()`**: upload a file (bytes, path or open file) and get the media ID to send it with.
- **`KapsoClient` and `KapsoSyncClient`**: the same API, async or sync (for threads and scripts). API errors raise `KapsoError` with `status_code`, `code`, the provider's message and `request_id`, never the API key. The message is Kapso's or Meta's text and can quote what you sent: log `status_code`, `code` and `request_id` instead.

Works with any web framework. All three take the raw body bytes: `verify(raw_body, signature, secret)`, `parse(raw_body, event_name)` and `parse_event(raw_body, headers)`.

## Receiving webhooks

```python
event = kapso.parse_event(raw_body, request.headers)

match event:
    case kapso.MessagesReceived(messages=messages):
        for msg in messages:
            if seen.add_if_new(msg.dedup_key):  # your store: Redis SET NX, a unique DB column, ...
                handle(msg)
    case kapso.StatusUpdate(status="failed", errors=errors):
        log.warning("send failed: %s", [e.code for e in errors])
    case kapso.UnknownEvent():
        pass
```

- **Verify first, then answer 200 fast.** Kapso expects a 200 within 10 seconds and retries otherwise. Do slow work (replies, LLM calls, downloads) after responding, in a background task or queue.
- **Answer 200 even if parsing fails** once the signature is valid. A 500 makes Kapso retry the same body, and a webhook that keeps failing gets paused. Log the error and keep the body.
- **Dedup by `dedup_key`, not by `X-Idempotency-Key`.** The header names a delivery; a message can arrive in more than one delivery (retries, batch fallback).
- **Statuses arrive in any order.** A `sent` can arrive after its `delivered`, and `delivered` is skipped when the user reads right away. Store a status as a rank (sent < delivered < read) and only move it forward.
- **Deliveries of different events aren't ordered against each other.** `conversation.created` can arrive after the message that opened the conversation, so don't make message handling wait for it.
- **`is_new_conversation` means "this inbound message opened the conversation".** A conversation your app opens with an outbound message (a template, a follow-up) fires no `conversation.created`, and the customer's reply has `is_new_conversation=False`. To reset per-conversation state, watch `conversation_id` change.
- **`ConversationInactive` is a `ConversationEvent`**: in a `match`, put its case first.
- **Privacy:** `repr()` of every domain object leaves out text, phone numbers, names, coordinates and media URLs (Kapso's media URLs work without auth). Log IDs, not objects' fields.

## Sending messages

```python
from kapso import Button, KapsoClient, ListRow, ListSection

async with KapsoClient(api_key) as client:
    m = client.messages
    await m.mark_read(pnid, msg.message_id, typing=True)  # blue ticks + "typing…"
    await m.send_text(pnid, msg.sender, "Hola!", reply_to=msg.message_id)
    await m.send_buttons(
        pnid, msg.sender, "Confirm the order?", [Button(id="yes", title="Yes"), Button(id="no", title="No")]
    )
    await m.send_list(
        pnid,
        msg.sender,
        "How should we ship it?",
        button="Options",
        sections=[ListSection(rows=[ListRow(id="express", title="Express", description="1-2 days")])],
    )

    media_id = await client.media.upload(pnid, "quote.pdf")  # MIME type from the name
    await m.send_document(pnid, msg.sender, media_id, filename="quote.pdf", caption="Your quote")
    await m.send_template(pnid, "15551234567", "order_update", "en_US", body=["Ana", "#1234"])
```

- **Who to send to.** `to` is a phone number, a business-scoped user ID (BSUID, e.g. `US.1349…`), or `msg.sender`. A BSUID goes in Meta's `recipient` field, never in `to`; a `Sender` sends both its phone and its BSUID when it has both (Meta uses the phone). Replying with `msg.sender` keeps working for users who hide their number behind a username.
- **What comes back.** Every send returns a `SendResult`: `message_id` (the WAMID that status webhooks refer to) and Meta's `status` when it gives one. `accepted` means Meta took the message, not that it was delivered: watch `StatusUpdate` for `delivered`, `read` or `failed`.
- **The 24-hour window.** Outside 24 hours since the user's last message, only templates go through; anything else raises `KapsoError` with `code=131047`.
- **Limits are checked before sending** by every typed method: text up to 4096 characters, captions and interactive bodies 1024, 3 buttons with 20-character titles, 10 list rows, and so on. A bad message raises `ValueError` without a request, and the error states lengths, not your text. `send_raw` checks nothing: Meta validates the payload.
- **Media.** Pass a media ID from `client.media.upload()` or an `https://` link Meta can download. Uploaded media lasts 30 days.
- **Sync code.** `KapsoSyncClient` has the same methods without `await`: `with KapsoSyncClient(api_key) as client: client.messages.send_text(...)`. It is generated from the async client, so the two never drift.

## Design

- **Small core.** Runtime dependencies are `pydantic` and `httpx` only. Framework integrations will be optional extras.
- **No hidden configuration.** The library never reads environment variables or `.env` files. Your app loads its secrets however it likes and passes them in.
- **Distribution vs import name.** The project is `kapso-python`; you `import kapso`.
- **Organized by API area.** `kapso/webhooks/` (receiving), `kapso/messages/` (sending), more as they're added; domain types in `kapso/types.py`. Import everything public from `kapso` itself: the internal layout may change.

## Example: FastAPI receiver

[`examples/fastapi_receiver.py`](examples/fastapi_receiver.py) verifies and parses every event, skips repeats by `dedup_key`, marks each message read with a typing indicator, downloads inbound media, and replies (quoted) with what the SDK understood ("Recibido: image, 71049 bytes descargados"), after answering the webhook, via a background task.

```bash
uv sync
cp .env.example .env          # fill in WEBHOOK_SECRET and KAPSO_API_KEY
uv run fastapi dev            # http://127.0.0.1:8000
ngrok http 8000               # public URL for Kapso
```

In Kapso, add a WhatsApp webhook on your phone number pointing at `https://<your-ngrok-url>/webhooks/kapso`, subscribed to the events you want (at least `whatsapp.message.received`), with the same secret as `WEBHOOK_SECRET`.

The example saves each verified delivery to `tests/fixtures/` (gitignored) so real payloads can be replayed in tests.

## Development

```bash
uv sync
uv run pytest -q              # tests
uv run ruff check .           # lint
uv run ruff format .          # format
```

Tests run on committed fixtures: Kapso's documented examples (`tests/fixtures/docs`) and real captures sanitized by `scripts/sanitize_fixture.py` (`tests/fixtures/public`). Raw captures contain phone numbers and message text, so they stay gitignored; `tests/test_privacy.py` checks the committed ones. `uv run python scripts/bench_parse.py` measures parsing per event, and `--check` replays every fixture. The sync client in `src/kapso/_sync/` is generated: after changing `client.py`, `messages/resource.py` or `media/resource.py`, run `uv run python scripts/unasync.py`. CI runs lint, checks the generated code is current, runs tests on Python 3.11 to 3.14 and checks that the built wheel imports.

Releases: bump `version` in `pyproject.toml`, update `CHANGELOG.md`, then publish a GitHub release tagged `v<version>`; the release workflow publishes to PyPI.

## License

[MIT](LICENSE): free to use, modify and ship, including commercially.
