kapso-python 0.1.0a1__tar.gz
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_python-0.1.0a1/.env.example +8 -0
- kapso_python-0.1.0a1/.github/dependabot.yml +10 -0
- kapso_python-0.1.0a1/.github/workflows/ci.yml +47 -0
- kapso_python-0.1.0a1/.github/workflows/release.yml +48 -0
- kapso_python-0.1.0a1/.gitignore +14 -0
- kapso_python-0.1.0a1/.python-version +1 -0
- kapso_python-0.1.0a1/CHANGELOG.md +22 -0
- kapso_python-0.1.0a1/LICENSE +21 -0
- kapso_python-0.1.0a1/PKG-INFO +105 -0
- kapso_python-0.1.0a1/README.md +74 -0
- kapso_python-0.1.0a1/examples/fastapi_receiver.py +106 -0
- kapso_python-0.1.0a1/pyproject.toml +72 -0
- kapso_python-0.1.0a1/src/kapso/__init__.py +13 -0
- kapso_python-0.1.0a1/src/kapso/client.py +84 -0
- kapso_python-0.1.0a1/src/kapso/errors.py +19 -0
- kapso_python-0.1.0a1/src/kapso/messages/__init__.py +4 -0
- kapso_python-0.1.0a1/src/kapso/messages/models.py +23 -0
- kapso_python-0.1.0a1/src/kapso/messages/resource.py +30 -0
- kapso_python-0.1.0a1/src/kapso/py.typed +0 -0
- kapso_python-0.1.0a1/src/kapso/types.py +41 -0
- kapso_python-0.1.0a1/src/kapso/webhooks/__init__.py +7 -0
- kapso_python-0.1.0a1/src/kapso/webhooks/parse.py +90 -0
- kapso_python-0.1.0a1/src/kapso/webhooks/payloads.py +181 -0
- kapso_python-0.1.0a1/src/kapso/webhooks/signature.py +16 -0
- kapso_python-0.1.0a1/tests/test_client.py +149 -0
- kapso_python-0.1.0a1/tests/test_parse.py +123 -0
- kapso_python-0.1.0a1/tests/test_webhooks.py +93 -0
- kapso_python-0.1.0a1/uv.lock +1888 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Config for the example app and the tests. The library itself never reads this file.
|
|
2
|
+
# Copy to .env and fill in. .env is gitignored.
|
|
3
|
+
|
|
4
|
+
# The secret you set on the Kapso WhatsApp webhook (used to verify X-Webhook-Signature).
|
|
5
|
+
WEBHOOK_SECRET=
|
|
6
|
+
|
|
7
|
+
# Kapso project API key (Kapso dashboard -> API keys). Needed for outbound calls.
|
|
8
|
+
KAPSO_API_KEY=
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
concurrency:
|
|
12
|
+
group: ci-${{ github.ref }}
|
|
13
|
+
cancel-in-progress: true
|
|
14
|
+
|
|
15
|
+
jobs:
|
|
16
|
+
lint:
|
|
17
|
+
runs-on: ubuntu-latest
|
|
18
|
+
steps:
|
|
19
|
+
- uses: actions/checkout@v7
|
|
20
|
+
- uses: astral-sh/setup-uv@v7
|
|
21
|
+
- run: uv sync --locked
|
|
22
|
+
- run: uv run ruff check .
|
|
23
|
+
- run: uv run ruff format --check .
|
|
24
|
+
|
|
25
|
+
test:
|
|
26
|
+
runs-on: ubuntu-latest
|
|
27
|
+
strategy:
|
|
28
|
+
fail-fast: false
|
|
29
|
+
matrix:
|
|
30
|
+
python-version: ["3.11", "3.12", "3.13", "3.14"]
|
|
31
|
+
steps:
|
|
32
|
+
- uses: actions/checkout@v7
|
|
33
|
+
- uses: astral-sh/setup-uv@v7
|
|
34
|
+
with:
|
|
35
|
+
python-version: ${{ matrix.python-version }}
|
|
36
|
+
- run: uv sync --locked
|
|
37
|
+
# Tests that need private webhook captures or WEBHOOK_SECRET skip here by design.
|
|
38
|
+
- run: uv run pytest -q -rs
|
|
39
|
+
|
|
40
|
+
build:
|
|
41
|
+
runs-on: ubuntu-latest
|
|
42
|
+
steps:
|
|
43
|
+
- uses: actions/checkout@v7
|
|
44
|
+
- uses: astral-sh/setup-uv@v7
|
|
45
|
+
- run: uv build
|
|
46
|
+
# The wheel must import on its own, without the repo's src/ on the path.
|
|
47
|
+
- run: uv run --isolated --no-project --with dist/*.whl python -c "import kapso; print(kapso.__all__)"
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
name: Release
|
|
2
|
+
|
|
3
|
+
# Publishes to PyPI when a GitHub release is published (e.g. tag v0.1.0a1).
|
|
4
|
+
# Uses PyPI trusted publishing (OIDC): no API token is stored anywhere.
|
|
5
|
+
# One-time setup on pypi.org: add a pending trusted publisher for
|
|
6
|
+
# owner Joselier3, repo kapso-python, workflow release.yml, environment pypi.
|
|
7
|
+
|
|
8
|
+
on:
|
|
9
|
+
release:
|
|
10
|
+
types: [published]
|
|
11
|
+
|
|
12
|
+
permissions:
|
|
13
|
+
contents: read
|
|
14
|
+
|
|
15
|
+
jobs:
|
|
16
|
+
build:
|
|
17
|
+
runs-on: ubuntu-latest
|
|
18
|
+
steps:
|
|
19
|
+
- uses: actions/checkout@v7
|
|
20
|
+
- uses: astral-sh/setup-uv@v7
|
|
21
|
+
- run: uv sync --locked
|
|
22
|
+
- run: uv run ruff check .
|
|
23
|
+
- run: uv run pytest -q
|
|
24
|
+
- name: Check the tag matches the package version
|
|
25
|
+
run: |
|
|
26
|
+
version=$(uv version --short)
|
|
27
|
+
if [ "v$version" != "${{ github.event.release.tag_name }}" ]; then
|
|
28
|
+
echo "Tag ${{ github.event.release.tag_name }} does not match version $version in pyproject.toml"
|
|
29
|
+
exit 1
|
|
30
|
+
fi
|
|
31
|
+
- run: uv build
|
|
32
|
+
- uses: actions/upload-artifact@v7
|
|
33
|
+
with:
|
|
34
|
+
name: dist
|
|
35
|
+
path: dist/
|
|
36
|
+
|
|
37
|
+
publish:
|
|
38
|
+
needs: build
|
|
39
|
+
runs-on: ubuntu-latest
|
|
40
|
+
environment: pypi
|
|
41
|
+
permissions:
|
|
42
|
+
id-token: write # required for trusted publishing
|
|
43
|
+
steps:
|
|
44
|
+
- uses: actions/download-artifact@v8
|
|
45
|
+
with:
|
|
46
|
+
name: dist
|
|
47
|
+
path: dist/
|
|
48
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.11
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here.
|
|
4
|
+
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
|
|
5
|
+
[Semantic Versioning](https://semver.org/). Before 1.0, minor versions may include breaking changes.
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.1.0a1] - 2026-11-30
|
|
10
|
+
|
|
11
|
+
First alpha.
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
- `verify()`: constant-time check of Kapso's `X-Webhook-Signature` (HMAC-SHA256 of the raw body),
|
|
15
|
+
safe on missing or malformed headers.
|
|
16
|
+
- Pydantic models for `whatsapp.message.*` webhook payloads, single and batched (buffering on),
|
|
17
|
+
including image, document, audio and video media.
|
|
18
|
+
- `parse()`: turns a verified delivery into a flat `list[InboundMessage]`, ignoring status events,
|
|
19
|
+
outbound messages and imported history.
|
|
20
|
+
- `KapsoClient` (async, httpx) with `client.messages.send_text(...)`, returning the new message's WAMID.
|
|
21
|
+
- `KapsoError` with `status_code`, `code` and Kapso's message for every API error shape.
|
|
22
|
+
- Example FastAPI receiver that verifies, parses and replies from a background task.
|
|
@@ -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.
|
|
@@ -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
|
+
[](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,74 @@
|
|
|
1
|
+
# kapso-python
|
|
2
|
+
|
|
3
|
+
[](https://github.com/Joselier3/kapso-python/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
A Python SDK for [Kapso](https://kapso.ai) (WhatsApp Business), built from real webhook traffic.
|
|
6
|
+
|
|
7
|
+
> Unofficial, community-built: not affiliated with or endorsed by Kapso.
|
|
8
|
+
> Early and learning-driven (alpha): the API will change.
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
uv add "kapso-python @ git+https://github.com/Joselier3/kapso-python" # until the first PyPI release
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
import kapso
|
|
16
|
+
|
|
17
|
+
if not kapso.verify(raw_body, headers.get("x-webhook-signature"), secret):
|
|
18
|
+
... # reject: 401
|
|
19
|
+
|
|
20
|
+
for msg in kapso.parse(raw_body, headers.get("x-webhook-event")):
|
|
21
|
+
print(msg.message_id, msg.type, msg.text)
|
|
22
|
+
|
|
23
|
+
async with kapso.KapsoClient(api_key) as client:
|
|
24
|
+
wamid = await client.messages.send_text(phone_number_id, to="15551234567", body="Hola!")
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## What works today
|
|
28
|
+
|
|
29
|
+
- **`verify()`**: checks Kapso's `X-Webhook-Signature` (HMAC-SHA256 of the raw body) in constant time, without crashing on malformed headers.
|
|
30
|
+
- **Typed payloads**: Pydantic models for `whatsapp.message.*` webhooks, single and batched (buffering on), including media.
|
|
31
|
+
- **`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`).
|
|
32
|
+
|
|
33
|
+
- **`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.
|
|
34
|
+
|
|
35
|
+
Works with any web framework: `verify` and `parse` take the raw body bytes and header values.
|
|
36
|
+
|
|
37
|
+
## Design
|
|
38
|
+
|
|
39
|
+
- **Small core.** Runtime dependencies are `pydantic` and `httpx` only. Framework integrations will be optional extras.
|
|
40
|
+
- **No hidden configuration.** The library never reads environment variables or `.env` files. Your app loads its secrets however it likes and passes them in.
|
|
41
|
+
- **Distribution vs import name.** The project is `kapso-python`; you `import kapso`.
|
|
42
|
+
- **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.
|
|
43
|
+
|
|
44
|
+
## Example: FastAPI receiver
|
|
45
|
+
|
|
46
|
+
[`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).
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
uv sync
|
|
50
|
+
cp .env.example .env # fill in WEBHOOK_SECRET and KAPSO_API_KEY
|
|
51
|
+
uv run fastapi dev # http://127.0.0.1:8000
|
|
52
|
+
ngrok http 8000 # public URL for Kapso
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
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`.
|
|
56
|
+
|
|
57
|
+
The example saves each verified delivery to `tests/fixtures/` (gitignored) so real payloads can be replayed in tests.
|
|
58
|
+
|
|
59
|
+
## Development
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
uv sync
|
|
63
|
+
uv run pytest -q # tests
|
|
64
|
+
uv run ruff check . # lint
|
|
65
|
+
uv run ruff format . # format
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
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.
|
|
69
|
+
|
|
70
|
+
Releases: bump `version` in `pyproject.toml`, update `CHANGELOG.md`, then publish a GitHub release tagged `v<version>`; the release workflow publishes to PyPI.
|
|
71
|
+
|
|
72
|
+
## License
|
|
73
|
+
|
|
74
|
+
[MIT](LICENSE): free to use, modify and ship, including commercially.
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Example app: receive Kapso WhatsApp webhooks with FastAPI and reply to each message.
|
|
2
|
+
|
|
3
|
+
This is an application, not part of the library: it reads its own config from .env,
|
|
4
|
+
saves each verified delivery to tests/fixtures/ (gitignored) for replay in tests,
|
|
5
|
+
and logs identifiers only.
|
|
6
|
+
|
|
7
|
+
uv run fastapi dev examples/fastapi_receiver.py
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
from contextlib import asynccontextmanager
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from dotenv import load_dotenv
|
|
18
|
+
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request, status
|
|
19
|
+
|
|
20
|
+
from kapso import InboundMessage, KapsoClient, KapsoError, parse, verify
|
|
21
|
+
|
|
22
|
+
load_dotenv()
|
|
23
|
+
|
|
24
|
+
# Uvicorn only configures its own loggers; this gives ours a handler and a format.
|
|
25
|
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
|
26
|
+
# Log identifiers only (IDs, types, counts): never message text, phone numbers, names or media URLs.
|
|
27
|
+
log = logging.getLogger("fastapi_receiver")
|
|
28
|
+
|
|
29
|
+
FIXTURES = Path(__file__).resolve().parents[1] / "tests" / "fixtures"
|
|
30
|
+
|
|
31
|
+
# Fail closed: refuse to start without config instead of misbehaving later.
|
|
32
|
+
KAPSO_WEBHOOK_SECRET = os.getenv("WEBHOOK_SECRET")
|
|
33
|
+
if not KAPSO_WEBHOOK_SECRET:
|
|
34
|
+
raise RuntimeError("WEBHOOK_SECRET is not set. Add it to .env (the secret configured on the Kapso webhook).")
|
|
35
|
+
|
|
36
|
+
KAPSO_API_KEY = os.getenv("KAPSO_API_KEY")
|
|
37
|
+
if not KAPSO_API_KEY:
|
|
38
|
+
raise RuntimeError("KAPSO_API_KEY is not set. Add it to .env (the Kapso project API key).")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@asynccontextmanager
|
|
42
|
+
async def lifespan(app: FastAPI):
|
|
43
|
+
# One client (one connection pool) for the whole app, closed on shutdown/reload.
|
|
44
|
+
async with KapsoClient(KAPSO_API_KEY) as client:
|
|
45
|
+
app.state.kapso = client
|
|
46
|
+
yield
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
app = FastAPI(lifespan=lifespan)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
async def safe_send(client: KapsoClient, msg: InboundMessage, text: str) -> None:
|
|
53
|
+
"""Reply to `msg`. Runs after the 200 has gone out, so nobody would see an exception:
|
|
54
|
+
log failures here instead (identifiers only)."""
|
|
55
|
+
try:
|
|
56
|
+
wamid = await client.messages.send_text(msg.phone_number_id, msg.sender_phone, text)
|
|
57
|
+
log.info(" replied to=%s reply=%s", msg.message_id, wamid)
|
|
58
|
+
except KapsoError as e:
|
|
59
|
+
log.error(" reply failed to=%s status=%s code=%s: %s", msg.message_id, e.status_code, e.code, e.message)
|
|
60
|
+
except Exception:
|
|
61
|
+
log.exception(" reply failed to=%s: unexpected error", msg.message_id)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@app.get("/health")
|
|
65
|
+
def health_check():
|
|
66
|
+
return {"ok": True}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@app.post("/webhooks/kapso")
|
|
70
|
+
async def reply(req: Request, background: BackgroundTasks):
|
|
71
|
+
raw_bytes = await req.body()
|
|
72
|
+
|
|
73
|
+
signature_header = req.headers.get("x-webhook-signature")
|
|
74
|
+
event = req.headers.get("x-webhook-event")
|
|
75
|
+
delivery_id = req.headers.get("x-idempotency-key") # same value on Kapso's retries
|
|
76
|
+
|
|
77
|
+
# Guard clause: reject anything not signed by Kapso before touching it.
|
|
78
|
+
if not verify(raw_bytes, signature_header, KAPSO_WEBHOOK_SECRET):
|
|
79
|
+
log.warning("rejected delivery=%s event=%s: invalid signature (%d bytes)", delivery_id, event, len(raw_bytes))
|
|
80
|
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid signature")
|
|
81
|
+
|
|
82
|
+
messages = parse(raw_bytes, event)
|
|
83
|
+
log.info("delivery=%s event=%s messages=%d", delivery_id, event, len(messages))
|
|
84
|
+
|
|
85
|
+
client: KapsoClient = req.app.state.kapso
|
|
86
|
+
for msg in messages:
|
|
87
|
+
log.info(
|
|
88
|
+
" message id=%s conversation=%s type=%s media=%s",
|
|
89
|
+
msg.message_id,
|
|
90
|
+
msg.conversation_id,
|
|
91
|
+
msg.type,
|
|
92
|
+
msg.media.mime_type if msg.media else None,
|
|
93
|
+
)
|
|
94
|
+
if msg.sender_phone is None: # BSUID-only sender: send_text needs a phone number for now
|
|
95
|
+
log.warning(" skipped id=%s: no sender phone", msg.message_id)
|
|
96
|
+
continue
|
|
97
|
+
# Runs after the response: Kapso gets its 200 right away and doesn't retry.
|
|
98
|
+
# Still no dedup: if Kapso does retry a delivery, this replies twice (exercise 4).
|
|
99
|
+
background.add_task(safe_send, client, msg, "Hola, mundo!")
|
|
100
|
+
|
|
101
|
+
FIXTURES.mkdir(parents=True, exist_ok=True)
|
|
102
|
+
name = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
|
|
103
|
+
(FIXTURES / f"{name}.body").write_bytes(raw_bytes)
|
|
104
|
+
(FIXTURES / f"{name}.headers.json").write_text(json.dumps(dict(req.headers), indent=2))
|
|
105
|
+
|
|
106
|
+
return {"ok": True}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "kapso-python"
|
|
3
|
+
version = "0.1.0a1"
|
|
4
|
+
description = "Unofficial Python SDK for Kapso (WhatsApp Business): webhooks, typed payloads and an async API client."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [{ name = "Elier Fajardo" }]
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
keywords = ["kapso", "whatsapp", "whatsapp-business", "webhooks", "sdk", "chatbot"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 3 - Alpha",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
17
|
+
"Programming Language :: Python :: 3.11",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Programming Language :: Python :: 3.14",
|
|
21
|
+
"Framework :: AsyncIO",
|
|
22
|
+
"Framework :: Pydantic :: 2",
|
|
23
|
+
"Topic :: Communications :: Chat",
|
|
24
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
dependencies = [
|
|
28
|
+
"httpx>=0.28.1",
|
|
29
|
+
"pydantic>=2.14.4",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://github.com/Joselier3/kapso-python"
|
|
34
|
+
Repository = "https://github.com/Joselier3/kapso-python"
|
|
35
|
+
Issues = "https://github.com/Joselier3/kapso-python/issues"
|
|
36
|
+
Changelog = "https://github.com/Joselier3/kapso-python/blob/main/CHANGELOG.md"
|
|
37
|
+
|
|
38
|
+
[dependency-groups]
|
|
39
|
+
dev = [
|
|
40
|
+
"fastapi[standard]>=0.165.0",
|
|
41
|
+
"pytest>=9.2.0",
|
|
42
|
+
"pytest-asyncio>=1.5.0",
|
|
43
|
+
"python-dotenv>=1.2.4",
|
|
44
|
+
"ruff>=0.17.6",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
[build-system]
|
|
48
|
+
requires = ["hatchling"]
|
|
49
|
+
build-backend = "hatchling.build"
|
|
50
|
+
|
|
51
|
+
[tool.hatch.build.targets.wheel]
|
|
52
|
+
# distribution is "kapso-python", import name is "kapso"
|
|
53
|
+
packages = ["src/kapso"]
|
|
54
|
+
|
|
55
|
+
[tool.fastapi]
|
|
56
|
+
entrypoint = "examples.fastapi_receiver:app"
|
|
57
|
+
|
|
58
|
+
[tool.pytest.ini_options]
|
|
59
|
+
testpaths = ["tests"]
|
|
60
|
+
asyncio_mode = "auto"
|
|
61
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
62
|
+
|
|
63
|
+
[tool.ruff]
|
|
64
|
+
line-length = 120
|
|
65
|
+
target-version = "py311"
|
|
66
|
+
|
|
67
|
+
[tool.ruff.lint]
|
|
68
|
+
# pycodestyle errors/warnings, pyflakes, isort, pyupgrade, bugbear, simplify
|
|
69
|
+
select = ["E", "W", "F", "I", "UP", "B", "SIM"]
|
|
70
|
+
|
|
71
|
+
[tool.ruff.lint.isort]
|
|
72
|
+
known-first-party = ["kapso"]
|
|
@@ -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"]
|
|
@@ -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)
|
|
@@ -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})"
|