kapso-python 0.1.0a1__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.
kapso/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """Python SDK for Kapso (WhatsApp Business).
2
+
3
+ The library never reads environment variables or .env files: secrets and keys are
4
+ passed in explicitly by the application that uses it.
5
+ """
6
+
7
+ from kapso.client import KapsoClient
8
+ from kapso.errors import KapsoError
9
+ from kapso.types import InboundMessage, Media
10
+ from kapso.webhooks.parse import parse
11
+ from kapso.webhooks.signature import verify
12
+
13
+ __all__ = ["InboundMessage", "KapsoClient", "KapsoError", "Media", "parse", "verify"]
kapso/client.py ADDED
@@ -0,0 +1,84 @@
1
+ from typing import Any
2
+
3
+ import httpx
4
+
5
+ from kapso.errors import KapsoError
6
+ from kapso.messages.resource import Messages
7
+
8
+ META_API_VERSION = "v24.0"
9
+
10
+
11
+ def _error_from_response(res: httpx.Response) -> KapsoError:
12
+ """Build a KapsoError from any failed response. Never raises while parsing.
13
+
14
+ Kapso returns errors in more than one shape:
15
+ Meta-style (400, 401, 404, 422): {"error": {"message": "...", "code": 131047, ...}}
16
+ Kapso-style (402, 409): {"error": "...", "code": "insufficient_credits"}
17
+ Not JSON at all (e.g. a proxy's HTML 502 page)
18
+ """
19
+ try:
20
+ body = res.json()
21
+ except ValueError: # includes json.JSONDecodeError
22
+ body = None
23
+
24
+ message: str | None = None
25
+ code: int | str | None = None
26
+
27
+ if isinstance(body, dict):
28
+ error = body.get("error")
29
+ if isinstance(error, dict):
30
+ message = error.get("message")
31
+ code = error.get("code")
32
+ elif isinstance(error, str):
33
+ message = error
34
+ code = body.get("code")
35
+
36
+ if not message:
37
+ message = res.text.strip()[:500] or f"HTTP {res.status_code}"
38
+
39
+ return KapsoError(res.status_code, message, code)
40
+
41
+
42
+ class KapsoClient:
43
+ """Async client for the Kapso API.
44
+
45
+ Holds what every call shares (API key, base URL, one HTTP connection pool) and exposes
46
+ the API by area: `kapso.messages.send_text(...)`.
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ api_key: str,
52
+ *,
53
+ base_url: str = "https://api.kapso.ai",
54
+ http_client: httpx.AsyncClient | None = None,
55
+ ):
56
+ self._base_url = base_url.rstrip("/")
57
+ self._headers = {"X-API-Key": api_key}
58
+ self._own_http = http_client is None
59
+ self._http = http_client or httpx.AsyncClient(timeout=10.0)
60
+
61
+ self.messages = Messages(self)
62
+
63
+ async def __aenter__(self) -> "KapsoClient":
64
+ return self
65
+
66
+ async def __aexit__(self, *exc) -> None:
67
+ await self.aclose()
68
+
69
+ async def aclose(self) -> None:
70
+ # Only close what we created; an injected client belongs to the caller.
71
+ if self._own_http:
72
+ await self._http.aclose()
73
+
74
+ async def _request(self, method: str, path: str, *, json: Any = None) -> Any:
75
+ """Send one request to `base_url + path`. Return the parsed JSON body,
76
+ or raise KapsoError for any non-2xx response."""
77
+ res = await self._http.request(method, f"{self._base_url}{path}", json=json, headers=self._headers)
78
+ if not res.is_success:
79
+ raise _error_from_response(res)
80
+ return res.json()
81
+
82
+ async def _meta_request(self, method: str, path: str, *, json: Any = None) -> Any:
83
+ """Meta proxy (`/meta/whatsapp/{version}/...`): messages, media, templates."""
84
+ return await self._request(method, f"/meta/whatsapp/{META_API_VERSION}{path}", json=json)
kapso/errors.py ADDED
@@ -0,0 +1,19 @@
1
+ """Exceptions raised by the Kapso client."""
2
+
3
+
4
+ class KapsoError(Exception):
5
+ """The Kapso API returned an error response.
6
+
7
+ `status_code` is the HTTP status. `code` is the provider's error code when there is one:
8
+ Meta's numeric codes (e.g. 131047, 24-hour window closed) or Kapso's own strings
9
+ (e.g. "insufficient_credits"). The message never includes request headers or the API key.
10
+ """
11
+
12
+ def __init__(self, status_code: int, message: str, code: int | str | None = None):
13
+ super().__init__(message) # str(err) returns the message
14
+ self.status_code = status_code
15
+ self.message = message
16
+ self.code = code
17
+
18
+ def __repr__(self) -> str:
19
+ return f"KapsoError(status_code={self.status_code}, code={self.code!r}, message={self.message!r})"
@@ -0,0 +1,4 @@
1
+ """Sending WhatsApp messages (Meta proxy: `/{phone_number_id}/messages`).
2
+
3
+ Used through the client: `kapso.messages.send_text(...)`. Kept empty to avoid circular imports.
4
+ """
@@ -0,0 +1,23 @@
1
+ """Wire models for the messages endpoint's responses, exactly as Kapso returns them.
2
+
3
+ POST /meta/whatsapp/{version}/{phone_number_id}/messages
4
+ """
5
+
6
+ from pydantic import BaseModel
7
+
8
+
9
+ class SentContact(BaseModel):
10
+ input: str # the `to` (or `recipient`) we sent
11
+ wa_id: str | None = None # normalized phone number; absent when sending to a BSUID
12
+ user_id: str | None = None # BSUID, when sending to one
13
+
14
+
15
+ class SentMessage(BaseModel):
16
+ id: str # the new message's WAMID
17
+ message_status: str | None = None
18
+
19
+
20
+ class SendMessageResponse(BaseModel):
21
+ messaging_product: str
22
+ contacts: list[SentContact] = []
23
+ messages: list[SentMessage]
@@ -0,0 +1,30 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+
5
+ from kapso.messages.models import SendMessageResponse
6
+
7
+ if TYPE_CHECKING: # only for type hints: importing it at runtime would be circular
8
+ from kapso.client import KapsoClient
9
+
10
+
11
+ class Messages:
12
+ """`kapso.messages`: send WhatsApp messages. One public method per message type."""
13
+
14
+ def __init__(self, client: KapsoClient):
15
+ self._client = client
16
+
17
+ async def send_text(self, phone_number_id: str, to: str, body: str) -> str:
18
+ """Send a WhatsApp text. Returns the new message's WAMID."""
19
+ payload = {
20
+ "messaging_product": "whatsapp",
21
+ "to": to,
22
+ "type": "text",
23
+ "text": {"body": body},
24
+ }
25
+ return await self._send(phone_number_id, payload)
26
+
27
+ async def _send(self, phone_number_id: str, payload: dict[str, Any]) -> str:
28
+ """POST a message payload; return its WAMID or raise KapsoError."""
29
+ data = await self._client._meta_request("POST", f"/{phone_number_id}/messages", json=payload)
30
+ return SendMessageResponse.model_validate(data).messages[0].id
kapso/py.typed ADDED
File without changes
kapso/types.py ADDED
@@ -0,0 +1,41 @@
1
+ """Domain types: what the app works with, independent of Kapso's wire format.
2
+
3
+ `parse()` builds these from webhook payloads. Integrations (e.g. LangGraph) consume them.
4
+ """
5
+
6
+ from datetime import datetime
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field
9
+
10
+ from kapso.webhooks.payloads import MessageEvent
11
+
12
+
13
+ class Media(BaseModel):
14
+ """A reference to a file, not the file. Download it only when the agent needs it."""
15
+
16
+ model_config = ConfigDict(frozen=True)
17
+
18
+ url: str = Field(repr=False) # Kapso's copy; works without auth, so keep it out of logs
19
+ mime_type: str | None = None
20
+ filename: str | None = None
21
+ size: int | None = None # bytes
22
+ media_id: str | None = None # Meta's ID: fallback if Kapso's copy fails
23
+ sha256: str | None = None # to check the download
24
+
25
+
26
+ class InboundMessage(BaseModel):
27
+ """One message a user sent to the business number, flattened from Kapso's payload."""
28
+
29
+ model_config = ConfigDict(frozen=True)
30
+
31
+ message_id: str # WAMID: stable across retries, use it to dedupe
32
+ timestamp: datetime
33
+ type: str # "text", "image", "document", "audio", ...
34
+ conversation_id: str # Kapso's conversation; a new one opens after a closed one
35
+ phone_number_id: str # the business number that received it
36
+ sender_phone: str | None # can be missing (BSUID)
37
+ sender_user_id: str | None # business-scoped user ID
38
+ contact_name: str | None
39
+ text: str | None # what the user typed: the text body, or the caption on media
40
+ media: Media | None
41
+ raw: MessageEvent = Field(repr=False) # escape hatch to every field Kapso sent
@@ -0,0 +1,7 @@
1
+ """Receiving Kapso webhooks: signature check (`signature`), wire models (`payloads`) and
2
+ turning a delivery into `InboundMessage`s (`parse`).
3
+
4
+ Import the public functions from `kapso` (`kapso.verify`, `kapso.parse`). This file stays
5
+ empty on purpose: re-exporting here would import `parse` (and so `kapso.types`) whenever
6
+ `payloads` is imported, which is a circular import.
7
+ """
@@ -0,0 +1,90 @@
1
+ """Turn a verified Kapso webhook delivery into the inbound messages the app should act on.
2
+
3
+ parse(raw_body, event)
4
+ 1. event check -> anything but `whatsapp.message.received` is ignored: []
5
+ 2. validate -> Kapso's wire shape: MessageReceivedBatch | MessageEvent
6
+ 3. normalize -> always a list[MessageEvent], whatever the shape
7
+ 4. filter -> keep only messages a user just sent
8
+ 5. to_inbound -> flatten each one into an InboundMessage
9
+ """
10
+
11
+ from kapso.types import InboundMessage, Media
12
+ from kapso.webhooks.payloads import (
13
+ MessageEvent,
14
+ MessagePayload,
15
+ MessageReceivedBatch,
16
+ payload_adapter,
17
+ )
18
+
19
+ RECEIVED = "whatsapp.message.received"
20
+
21
+
22
+ def normalize(payload: MessagePayload) -> list[MessageEvent]:
23
+ """Batch -> its items; single -> a list of one. Downstream never sees batching."""
24
+ if isinstance(payload, MessageReceivedBatch):
25
+ return payload.data
26
+ return [payload]
27
+
28
+
29
+ def is_actionable(event: MessageEvent) -> bool:
30
+ """Only messages a user just sent. Outbound echoes and imported history
31
+ (`history_sync`: old chats copied in when a number connects) must not trigger a reply."""
32
+ kapso = event.message.kapso
33
+ return kapso.direction == "inbound" and kapso.origin != "history_sync"
34
+
35
+
36
+ def to_media(event: MessageEvent) -> Media | None:
37
+ kapso = event.message.kapso
38
+ stored = kapso.media_data # Kapso's copy: same shape for every media type
39
+ meta = event.message.media # Meta's object under image/document/...: has the ID
40
+ url = (stored.url if stored else None) or kapso.media_url or (meta.link if meta else None)
41
+ if url is None:
42
+ return None
43
+ return Media(
44
+ url=url,
45
+ mime_type=(stored.content_type if stored else None) or (meta.mime_type if meta else None),
46
+ filename=(stored.filename if stored else None) or (meta.filename if meta else None),
47
+ size=stored.byte_size if stored else None,
48
+ media_id=meta.id if meta else None,
49
+ sha256=meta.sha256 if meta else None,
50
+ )
51
+
52
+
53
+ def to_text(event: MessageEvent) -> str | None:
54
+ """The text body, or the caption on media. Empty captions ("") become None."""
55
+ message = event.message
56
+ if message.text is not None:
57
+ return message.text.body
58
+ type_data = message.kapso.message_type_data
59
+ caption = (type_data.caption if type_data else None) or (message.media.caption if message.media else None)
60
+ return caption or None
61
+
62
+
63
+ def to_inbound(event: MessageEvent) -> InboundMessage:
64
+ message, conversation = event.message, event.conversation
65
+ return InboundMessage(
66
+ message_id=message.id,
67
+ timestamp=message.timestamp,
68
+ type=message.type,
69
+ conversation_id=conversation.id,
70
+ phone_number_id=event.phone_number_id,
71
+ sender_phone=message.from_,
72
+ sender_user_id=message.from_user_id or conversation.business_scoped_user_id,
73
+ contact_name=conversation.contact_name,
74
+ text=to_text(event),
75
+ media=to_media(event),
76
+ raw=event,
77
+ )
78
+
79
+
80
+ def parse(raw_body: bytes, event: str | None) -> list[InboundMessage]:
81
+ """`raw_body` must already have passed `verify()`. `event` is the `x-webhook-event`
82
+ header: a single delivery doesn't carry its event type in the body.
83
+
84
+ Returns [] for deliveries to ignore. The route should still answer 200 for those,
85
+ or Kapso retries them.
86
+ """
87
+ if event != RECEIVED:
88
+ return []
89
+ payload = payload_adapter.validate_json(raw_body)
90
+ return [to_inbound(e) for e in normalize(payload) if is_actionable(e)]
@@ -0,0 +1,181 @@
1
+ """Wire models: Kapso's `whatsapp.message.*` webhook payloads, exactly as sent.
2
+
3
+ Every message event (received, sent, delivered, read, failed) has the same single-delivery
4
+ body: `MessageEvent`. Only `whatsapp.message.received` can also arrive batched (buffering on).
5
+ The event name itself is only in the `x-webhook-event` header (and in a batch's `type`).
6
+
7
+ Only the webhook code imports these. The rest of the app works with `kapso.InboundMessage`
8
+ (kapso/types.py), which `parse()` builds.
9
+ Unknown keys are ignored (Pydantic's default), so new Kapso fields don't break validation.
10
+ """
11
+
12
+ from datetime import datetime
13
+ from typing import Annotated, Any, Literal
14
+
15
+ from pydantic import BaseModel, ConfigDict, Discriminator, Field, Tag, TypeAdapter
16
+
17
+ # --- message --------------------------------------------------------------------------
18
+
19
+
20
+ class TextContent(BaseModel):
21
+ body: str
22
+
23
+
24
+ class MediaContent(BaseModel):
25
+ """Meta's media object, under a key named after the type (`image`, `document`, ...)."""
26
+
27
+ id: str # Meta media ID: fetch a fresh URL via GET /meta/whatsapp/v24.0/{id}
28
+ mime_type: str | None = None
29
+ sha256: str | None = None # base64 checksum of the file
30
+ url: str | None = None # Meta's copy (lookaside.fbsbx.com): needs Meta's token, 401 otherwise
31
+ link: str | None = None # Kapso's copy: same as kapso.media_url
32
+ filename: str | None = None # documents only
33
+ caption: str | None = None
34
+
35
+
36
+ class MediaData(BaseModel):
37
+ """Kapso's stored copy of the file. Same shape for every media type."""
38
+
39
+ url: str # works without auth: treat it like a password, never log it
40
+ content_type: str | None = None
41
+ filename: str | None = None
42
+ byte_size: int | None = None
43
+
44
+
45
+ class MessageTypeData(BaseModel):
46
+ caption: str | None = None # "" when the user typed nothing
47
+ has_media: bool | None = None
48
+
49
+
50
+ class Pricing(BaseModel):
51
+ type: str # e.g. "free_customer_service"
52
+ billable: bool
53
+ category: str | None = None # e.g. "service", "marketing", "utility"
54
+ subtype: str | None = None
55
+ pricing_model: str | None = None
56
+
57
+
58
+ class MessageStatus(BaseModel):
59
+ """One step in an outbound message's delivery history (sent -> delivered -> read)."""
60
+
61
+ id: str # same WAMID as the message
62
+ status: str # "sent" | "delivered" | "read" | "failed"
63
+ timestamp: datetime
64
+ recipient_id: str | None = None
65
+ recipient_user_id: str | None = None
66
+ pricing: Pricing | None = None
67
+
68
+
69
+ class MessageKapso(BaseModel):
70
+ direction: Literal["inbound", "outbound"]
71
+ origin: str # "cloud_api" | "business_app" | "history_sync"
72
+ status: str # latest status: "delivered", "sent", "read", ...
73
+ has_media: bool
74
+ content: str | None = None
75
+ processing_status: str | None = None
76
+ statuses: list[MessageStatus] = [] # outbound only; absent on inbound and on "sent"
77
+ # media messages only
78
+ media_url: str | None = None # Kapso's copy; same as media_data.url
79
+ media_data: MediaData | None = None
80
+ message_type_data: MessageTypeData | None = None
81
+
82
+
83
+ class Message(BaseModel):
84
+ model_config = ConfigDict(populate_by_name=True)
85
+
86
+ id: str # the WAMID: the dedup key
87
+ type: str # "text", "image", ... (open set: WhatsApp keeps adding types)
88
+ timestamp: datetime # sent as unix seconds in a string; Pydantic converts it
89
+ # inbound messages have `from`, outbound ones have `to`
90
+ from_: str | None = Field(default=None, alias="from") # can be missing (BSUID)
91
+ from_user_id: str | None = None
92
+ to: str | None = None
93
+ to_user_id: str | None = None
94
+ username: str | None = None
95
+ text: TextContent | None = None # only when type == "text"
96
+ # the media object sits under a key named after `type`
97
+ image: MediaContent | None = None
98
+ document: MediaContent | None = None
99
+ audio: MediaContent | None = None
100
+ video: MediaContent | None = None
101
+ sticker: MediaContent | None = None
102
+ context: dict[str, Any] | None = None # set when replying to a specific message
103
+ kapso: MessageKapso
104
+
105
+ @property
106
+ def media(self) -> MediaContent | None:
107
+ """The media object for this message's type, if it has one."""
108
+ value = getattr(self, self.type, None)
109
+ return value if isinstance(value, MediaContent) else None
110
+
111
+
112
+ # --- conversation ---------------------------------------------------------------------
113
+
114
+
115
+ class ConversationKapso(BaseModel):
116
+ messages_count: int
117
+ last_message_id: str | None = None
118
+ last_inbound_at: datetime | None = None
119
+ last_outbound_at: datetime | None = None
120
+
121
+
122
+ class Conversation(BaseModel):
123
+ id: str
124
+ status: str
125
+ phone_number_id: str
126
+ phone_number: str | None = None
127
+ contact_name: str | None = None
128
+ business_scoped_user_id: str | None = None
129
+ created_at: datetime
130
+ updated_at: datetime
131
+ last_active_at: datetime | None = None
132
+ kapso: ConversationKapso
133
+
134
+
135
+ # --- payload shapes -------------------------------------------------------------------
136
+
137
+
138
+ class MessageEvent(BaseModel):
139
+ """Single delivery of any `whatsapp.message.*` event. Also the shape of each batch item."""
140
+
141
+ message: Message
142
+ conversation: Conversation
143
+ phone_number_id: str
144
+ is_new_conversation: bool
145
+
146
+
147
+ class BatchInfo(BaseModel):
148
+ size: int
149
+ window_ms: int
150
+ first_sequence: int # sequences are per conversation: use them to spot gaps
151
+ last_sequence: int
152
+ conversation_id: str
153
+
154
+
155
+ class MessageReceivedBatch(BaseModel):
156
+ """Batched delivery (buffering on). Sent even when the batch holds one message."""
157
+
158
+ type: Literal["whatsapp.message.received"]
159
+ batch: Literal[True]
160
+ data: list[MessageEvent]
161
+ batch_info: BatchInfo
162
+
163
+
164
+ # --- picking the right shape ----------------------------------------------------------
165
+
166
+
167
+ def _shape(payload: Any) -> str:
168
+ """Tell the two shapes apart. The single shape has no field to discriminate on,
169
+ so a plain `Field(discriminator=...)` can't work; a callable can."""
170
+ if isinstance(payload, dict):
171
+ return "batch" if payload.get("batch") is True else "single"
172
+ return "batch" if isinstance(payload, MessageReceivedBatch) else "single"
173
+
174
+
175
+ MessagePayload = Annotated[
176
+ Annotated[MessageReceivedBatch, Tag("batch")] | Annotated[MessageEvent, Tag("single")],
177
+ Discriminator(_shape),
178
+ ]
179
+
180
+ # `payload_adapter.validate_json(raw_bytes)` returns a MessageReceivedBatch or a MessageEvent.
181
+ payload_adapter: TypeAdapter[MessagePayload] = TypeAdapter(MessagePayload)
@@ -0,0 +1,16 @@
1
+ import hashlib
2
+ import hmac
3
+
4
+
5
+ def verify(raw_bytes: bytes, signature_header: str | None, secret: str) -> bool:
6
+ if signature_header is None:
7
+ return False
8
+
9
+ secret_bytes = bytes(secret, "utf-8")
10
+ expected = hmac.new(secret_bytes, raw_bytes, hashlib.sha256).hexdigest()
11
+
12
+ # Convert to bytes so compare_digest doesn't fail for non-ascii chars
13
+ b_signature_header = bytes(signature_header, "utf-8")
14
+ b_expected = bytes(expected, "utf-8")
15
+
16
+ return hmac.compare_digest(b_signature_header, b_expected)
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.5
2
+ Name: kapso-python
3
+ Version: 0.1.0a1
4
+ Summary: Unofficial Python SDK for Kapso (WhatsApp Business): webhooks, typed payloads and an async API client.
5
+ Project-URL: Homepage, https://github.com/Joselier3/kapso-python
6
+ Project-URL: Repository, https://github.com/Joselier3/kapso-python
7
+ Project-URL: Issues, https://github.com/Joselier3/kapso-python/issues
8
+ Project-URL: Changelog, https://github.com/Joselier3/kapso-python/blob/main/CHANGELOG.md
9
+ Author: Elier Fajardo
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: chatbot,kapso,sdk,webhooks,whatsapp,whatsapp-business
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Framework :: Pydantic :: 2
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: Communications :: Chat
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.11
28
+ Requires-Dist: httpx>=0.28.1
29
+ Requires-Dist: pydantic>=2.14.4
30
+ Description-Content-Type: text/markdown
31
+
32
+ # kapso-python
33
+
34
+ [![CI](https://github.com/Joselier3/kapso-python/actions/workflows/ci.yml/badge.svg)](https://github.com/Joselier3/kapso-python/actions/workflows/ci.yml)
35
+
36
+ A Python SDK for [Kapso](https://kapso.ai) (WhatsApp Business), built from real webhook traffic.
37
+
38
+ > Unofficial, community-built: not affiliated with or endorsed by Kapso.
39
+ > Early and learning-driven (alpha): the API will change.
40
+
41
+ ```bash
42
+ uv add "kapso-python @ git+https://github.com/Joselier3/kapso-python" # until the first PyPI release
43
+ ```
44
+
45
+ ```python
46
+ import kapso
47
+
48
+ if not kapso.verify(raw_body, headers.get("x-webhook-signature"), secret):
49
+ ... # reject: 401
50
+
51
+ for msg in kapso.parse(raw_body, headers.get("x-webhook-event")):
52
+ print(msg.message_id, msg.type, msg.text)
53
+
54
+ async with kapso.KapsoClient(api_key) as client:
55
+ wamid = await client.messages.send_text(phone_number_id, to="15551234567", body="Hola!")
56
+ ```
57
+
58
+ ## What works today
59
+
60
+ - **`verify()`**: checks Kapso's `X-Webhook-Signature` (HMAC-SHA256 of the raw body) in constant time, without crashing on malformed headers.
61
+ - **Typed payloads**: Pydantic models for `whatsapp.message.*` webhooks, single and batched (buffering on), including media.
62
+ - **`parse()`**: turns a verified delivery into a flat `list[InboundMessage]`. Batches are flattened, status events and outbound or imported-history messages are ignored, and media comes back as a reference (URL hidden from `repr`).
63
+
64
+ - **`KapsoClient`**: async client (httpx). `client.messages.send_text(...)` returns the new message's WAMID; API errors raise `KapsoError` with `status_code`, `code` and Kapso's message, never the API key.
65
+
66
+ Works with any web framework: `verify` and `parse` take the raw body bytes and header values.
67
+
68
+ ## Design
69
+
70
+ - **Small core.** Runtime dependencies are `pydantic` and `httpx` only. Framework integrations will be optional extras.
71
+ - **No hidden configuration.** The library never reads environment variables or `.env` files. Your app loads its secrets however it likes and passes them in.
72
+ - **Distribution vs import name.** The project is `kapso-python`; you `import kapso`.
73
+ - **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.
74
+
75
+ ## Example: FastAPI receiver
76
+
77
+ [`examples/fastapi_receiver.py`](examples/fastapi_receiver.py) is a minimal app that verifies, parses and logs deliveries, and replies "Hola, mundo!" to each inbound message (after answering the webhook, via a background task).
78
+
79
+ ```bash
80
+ uv sync
81
+ cp .env.example .env # fill in WEBHOOK_SECRET and KAPSO_API_KEY
82
+ uv run fastapi dev # http://127.0.0.1:8000
83
+ ngrok http 8000 # public URL for Kapso
84
+ ```
85
+
86
+ In Kapso, add a WhatsApp webhook on your phone number pointing at `https://<your-ngrok-url>/webhooks/kapso`, subscribed to `whatsapp.message.received`, with the same secret as `WEBHOOK_SECRET`.
87
+
88
+ The example saves each verified delivery to `tests/fixtures/` (gitignored) so real payloads can be replayed in tests.
89
+
90
+ ## Development
91
+
92
+ ```bash
93
+ uv sync
94
+ uv run pytest -q # tests
95
+ uv run ruff check . # lint
96
+ uv run ruff format . # format
97
+ ```
98
+
99
+ Tests that need real captured payloads skip when those files are missing. Captures contain phone numbers and message text, so they are never committed. CI runs lint and tests on Python 3.11 to 3.14 and checks that the built wheel imports.
100
+
101
+ Releases: bump `version` in `pyproject.toml`, update `CHANGELOG.md`, then publish a GitHub release tagged `v<version>`; the release workflow publishes to PyPI.
102
+
103
+ ## License
104
+
105
+ [MIT](LICENSE): free to use, modify and ship, including commercially.
@@ -0,0 +1,16 @@
1
+ kapso/__init__.py,sha256=JBatRiuwH0Mp6rVCQO6YWth1PsYghI_PkkSx0BzIxkM,476
2
+ kapso/client.py,sha256=yD4RFfGAMphCXizrQPU239K2hPcY1Be76cmq-LlaeiU,2849
3
+ kapso/errors.py,sha256=Gcdy3Nt3DV9ASE2ZKhYmCjN93GrjBQZwYdp7fDEjbFQ,794
4
+ kapso/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ kapso/types.py,sha256=sDrb6a9Gei1P_5faPmTAAHCCNUEekJs-glbAnvuAE1Y,1599
6
+ kapso/messages/__init__.py,sha256=RxdW9vnqf3Ipv5fW0PHDt24eae0WYHyLmWBaMQOWGOE,175
7
+ kapso/messages/models.py,sha256=yalFdzxquSa8N-4WZ0oqs858tNBCGAMj8aFyizfMP50,657
8
+ kapso/messages/resource.py,sha256=GHbf4b5v_hrioo5IkO-ctAUmqdOwHP62NFdSQYGQv-E,1137
9
+ kapso/webhooks/__init__.py,sha256=v4Ef47qHKTYew-T5qb-q5KWD9L1ruypGu6mM4LAPhcg,378
10
+ kapso/webhooks/parse.py,sha256=Ze-WiQIFwB8MWJTX8dTyfCYWaS0LD7zbvWIDG18si04,3536
11
+ kapso/webhooks/payloads.py,sha256=WXeHdY5b4yPCO47vAxzKIvRi1QwLlzG7HLQrkVB5Q-c,6423
12
+ kapso/webhooks/signature.py,sha256=m9AvWpUBQ-Rafo-RBHoRLpysegrfg9qwJxj67OFC4FY,523
13
+ kapso_python-0.1.0a1.dist-info/METADATA,sha256=K12-2676AUrWMTYSI6i53w1Rj3KSkF50qsrX8KEALUg,5111
14
+ kapso_python-0.1.0a1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
15
+ kapso_python-0.1.0a1.dist-info/licenses/LICENSE,sha256=DtdC21WTJrp-abEBJGD8FJpAaK3AcV6g4AT_aobWm_A,1070
16
+ kapso_python-0.1.0a1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Elier Fajardo
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.