Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
# Changelog

## 1.1.0 (2026-11-25)

### Added

- Drops reward claim webhooks. `WebhookHandler` now accepts them (no `Kick-Event-Type` header, `Kick-Event-Timestamp` header) as `DROPS_REWARD_CLAIMED` with a `DropsRewardClaimed` payload. The aiohttp route handles them synchronously, as Kick requires: 200 after your handlers succeed, 500 if one fails, 503 for a copy that arrives while the first is still running.

### Docs

- Moderation: Kick's bare 400 for targets that can't be moderated.
- Offline `custom_tags` updates don't show until the channel is live.
- Drops endpoints return 500 for apps without an organization.

## 1.0.0 (2026-11-25)

A rewrite against the current Kick API. Not compatible with 0.x; see [docs/migrating.md](docs/migrating.md).
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Async Python client for the [Kick.com public API](https://docs.kick.com).
- OAuth 2.1 with PKCE, app tokens and user tokens. Tokens refresh on their own and persist in memory, a JSON file, SQLite or your own store.
- Every endpoint in Kick's API: users, channels, chat, moderation, channel rewards, livestreams, categories, event subscriptions, KICKs, ads and drops.
- Typed responses (pydantic models), cursor pagination, automatic retries on rate limits.
- Webhook receiver with signature checks, replay protection and typed event payloads.
- Webhook receiver with signature checks, replay protection and typed event payloads, including Drops reward claims.
- A websocket chat reader for bots that can't expose a public webhook URL (unofficial, see below).

```bash
Expand Down
2 changes: 2 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ Name and tag filters match on substrings: `names=["just"]` finds "Just Chatting"
| `drops.claims(campaign_id=, user_id=, claim_id=, external_status=, limit=, cursor=)` returns `Page[DropsClaim]` | `GET /public/v1/drops/claims` | App token of an organization app |
| `drops.update_claims({claim_id: status})` | `PATCH /public/v1/drops/claims` | same |

Drops endpoints only work for apps registered to an [organization](https://docs.kick.com/organizations/organization-management). For any other app Kick answers `500 Internal server error`, which kickpython raises as `ServerError`. Claim webhooks are covered in [webhooks.md](webhooks.md#drops-claims).

Ad break errors carry Kick's reason in `exc.data`, for example `CHANNEL_IS_NOT_LIVE` or `MAX_AD_BREAKS_REACHED`.

## OAuth and keys
Expand Down
31 changes: 31 additions & 0 deletions docs/webhooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,37 @@ An event type this version of kickpython doesn't know still reaches your handler

Anonymous gifters arrive with `is_anonymous=True` and every other user field set to `None`.

## Drops claims

If your organization runs [Drops campaigns](https://docs.kick.com/drops/drops-guide), Kick posts each claimed reward to the webhook URL you gave Kick when registering the organization. These requests differ from event webhooks. They have no `Kick-Event-Type` header and send the timestamp as `Kick-Event-Timestamp`, and Kick expects a synchronous answer: 200 only once the reward is delivered.

The same `WebhookHandler` takes them. kickpython labels them `DROPS_REWARD_CLAIMED`:

```python
from kickpython import DROPS_REWARD_CLAIMED, DropsRewardClaimed, WebhookEvent, WebhookHandler

hook = WebhookHandler()

@hook.on(DROPS_REWARD_CLAIMED)
async def fulfil(event: WebhookEvent):
claim: DropsRewardClaimed = event.payload
await give_item(kick_user_id=claim.user_id, reward=claim.external_id or claim.reward_id,
idempotency_key=claim.claim_id)
```

The aiohttp route runs Drops handlers before answering. It returns 200 when they succeed and 500 when one raises, so Kick tries again. A copy that arrives while the first is still running gets 503. Make fulfilment idempotent on `claim_id`: Kick can deliver the same claim twice, and the handler's duplicate memory lives in one process only.

The `broadcaster_user_ids` filter doesn't apply to Drops claims, since they belong to the organization rather than a channel.

To catch up on claims you missed, or to record your fulfilment status at Kick, use the claims API:

```python
page = await kick.drops.claims(campaign_id="01J...", limit=100)
await kick.drops.update_claims({c.claim_id: "processed" for c in page})
```

kickpython verifies Drops signatures the same way as other webhooks, over `"{message id}.{timestamp}.{body}"` with Kick's public key. Kick's Drops guide doesn't spell out the signed string separately, and this path hasn't been tested against real Drops deliveries, because those need an approved organization.

## Verifying by hand

```python
Expand Down
4 changes: 4 additions & 0 deletions src/kickpython/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
WebhookVerificationError,
)
from .events import (
DROPS_REWARD_CLAIMED,
ChannelFollowed,
ChatMessage,
DropsRewardClaimed,
EventUser,
KicksGifted,
LivestreamMetadataUpdated,
Expand Down Expand Up @@ -61,6 +63,7 @@
from .webhooks import WebhookHandler, WebhookKeyUnavailable, parse_event, verify_signature

__all__ = [
"DROPS_REWARD_CLAIMED",
"AdBreak",
"AdBreakStatus",
"AuthorizationRequest",
Expand All @@ -73,6 +76,7 @@
"ChatMessageSent",
"ConflictError",
"DropsClaim",
"DropsRewardClaimed",
"EventSubscription",
"EventType",
"EventUser",
Expand Down
2 changes: 1 addition & 1 deletion src/kickpython/_version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "1.0.0"
__version__ = "1.1.0"
21 changes: 21 additions & 0 deletions src/kickpython/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
from .scopes import EventType

__all__ = [
"DROPS_REWARD_CLAIMED",
"Badge",
"ChannelFollowed",
"ChatMessage",
"DropsRewardClaimed",
"EventPayload",
"EventUser",
"Identity",
Expand Down Expand Up @@ -221,6 +223,24 @@ class KicksGifted(EventPayload):
created_at: OptionalDatetime = None


class DropsRewardClaimed(EventPayload):
"""A viewer claimed a Drops reward (organizations only).

Kick sends this to the organization's webhook URL without a
``Kick-Event-Type`` header; kickpython labels it ``DROPS_REWARD_CLAIMED``.
Fulfil it idempotently: Kick may deliver the same ``claim_id`` again.
"""

claim_id: str
user_id: int
campaign_id: str
reward_id: str
external_id: OptionalStr = None


DROPS_REWARD_CLAIMED = "drops.reward.claimed"
"""kickpython's name for Drops claim webhooks, which carry no event type header."""

_PAYLOADS: dict[str, type[EventPayload]] = {
EventType.CHAT_MESSAGE_SENT.value: ChatMessage,
EventType.CHANNEL_FOLLOWED.value: ChannelFollowed,
Expand All @@ -232,6 +252,7 @@ class KicksGifted(EventPayload):
EventType.LIVESTREAM_METADATA_UPDATED.value: LivestreamMetadataUpdated,
EventType.MODERATION_BANNED.value: ModerationBanned,
EventType.KICKS_GIFTED.value: KicksGifted,
DROPS_REWARD_CLAIMED: DropsRewardClaimed,
}


Expand Down
54 changes: 43 additions & 11 deletions src/kickpython/webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async def on_chat(event: WebhookEvent) -> None:
from cryptography.hazmat.primitives.asymmetric import padding, rsa

from .errors import KickError, WebhookVerificationError
from .events import WebhookEvent, payload_model
from .events import DROPS_REWARD_CLAIMED, WebhookEvent, payload_model
from .scopes import EventType

if TYPE_CHECKING:
Expand All @@ -49,6 +49,7 @@ async def on_chat(event: WebhookEvent) -> None:
from .client import KickClient

__all__ = [
"HEADER_DROPS_TIMESTAMP",
"HEADER_EVENT_TYPE",
"HEADER_EVENT_VERSION",
"HEADER_MESSAGE_ID",
Expand All @@ -67,6 +68,7 @@ async def on_chat(event: WebhookEvent) -> None:
HEADER_SUBSCRIPTION_ID = "Kick-Event-Subscription-Id"
HEADER_SIGNATURE = "Kick-Event-Signature"
HEADER_TIMESTAMP = "Kick-Event-Message-Timestamp"
HEADER_DROPS_TIMESTAMP = "Kick-Event-Timestamp" # Drops claim webhooks use this name
HEADER_EVENT_TYPE = "Kick-Event-Type"
HEADER_EVENT_VERSION = "Kick-Event-Version"
PUBLIC_KEY_URL = "https://api.kick.com/public/v1/public-key"
Expand Down Expand Up @@ -136,19 +138,31 @@ def _parse_timestamp(value: str) -> datetime | None:
return ts if ts.tzinfo else ts.replace(tzinfo=timezone.utc)


def _timestamp_header(headers: Mapping[str, str]) -> str | None:
return _header(headers, HEADER_TIMESTAMP) or _header(headers, HEADER_DROPS_TIMESTAMP)


def _is_drops_claim(data: Mapping[str, object]) -> bool:
return all(k in data for k in ("claim_id", "campaign_id", "reward_id"))


def parse_event(headers: Mapping[str, str], body: bytes | str) -> WebhookEvent:
"""Parse a delivery without verifying it. Use :class:`WebhookHandler` in production."""
raw_body = body.encode() if isinstance(body, str) else body
event_type = _header(headers, HEADER_EVENT_TYPE)
message_id = _header(headers, HEADER_MESSAGE_ID)
if not event_type or not message_id:
raise WebhookVerificationError("missing Kick-Event-Type or Kick-Event-Message-Id header")
if not message_id:
raise WebhookVerificationError("missing Kick-Event-Message-Id header")
try:
data = json.loads(raw_body)
except ValueError as exc:
raise WebhookVerificationError("webhook body is not JSON") from exc
if not isinstance(data, dict):
raise WebhookVerificationError("webhook body is not a JSON object")
event_type = _header(headers, HEADER_EVENT_TYPE)
if not event_type:
if not _is_drops_claim(data):
raise WebhookVerificationError("missing Kick-Event-Type header")
event_type = DROPS_REWARD_CLAIMED
version_raw = _header(headers, HEADER_EVENT_VERSION) or "1"
try:
version = int(version_raw.strip().strip('"'))
Expand All @@ -163,7 +177,7 @@ def parse_event(headers: Mapping[str, str], body: bytes | str) -> WebhookEvent:
log.warning(
"could not parse %s v%s payload; see event.raw", event_type, version, exc_info=True
)
ts_header = _header(headers, HEADER_TIMESTAMP)
ts_header = _timestamp_header(headers)
return WebhookEvent(
type=event_type,
version=version,
Expand Down Expand Up @@ -317,7 +331,7 @@ async def verify(self, headers: Mapping[str, str], body: bytes) -> None:
fetched; answer that with HTTP 503 so Kick retries later.
"""
message_id = _header(headers, HEADER_MESSAGE_ID)
timestamp = _header(headers, HEADER_TIMESTAMP)
timestamp = _timestamp_header(headers)
signature = _header(headers, HEADER_SIGNATURE)
if not message_id or not timestamp or not signature:
raise WebhookVerificationError("missing Kick-Event-* signature headers")
Expand All @@ -339,8 +353,8 @@ async def verify(self, headers: Mapping[str, str], body: bytes) -> None:
raise WebhookVerificationError("invalid Kick-Event-Signature")

def _check_broadcaster(self, event: WebhookEvent) -> None:
if self.broadcaster_user_ids is None:
return
if self.broadcaster_user_ids is None or event.type == DROPS_REWARD_CLAIMED:
return # Drops claims belong to the organization, not to a channel
broadcaster = event.raw.get("broadcaster")
uid = broadcaster.get("user_id") if isinstance(broadcaster, dict) else None
if uid is None or int(uid) not in self.broadcaster_user_ids:
Expand Down Expand Up @@ -388,6 +402,10 @@ async def handle(self, headers: Mapping[str, str], body: bytes) -> WebhookEvent
event = await self.accept(headers, body)
if event is None:
return None
await self._dispatch_once(event)
return event

async def _dispatch_once(self, event: WebhookEvent) -> None:
# Reserve the ID before awaiting handlers, so a concurrent retry of the
# same delivery is dropped. Released if a handler raises.
self._inflight.add(event.message_id)
Expand All @@ -396,7 +414,6 @@ async def handle(self, headers: Mapping[str, str], body: bytes) -> WebhookEvent
self._remember(event.message_id)
finally:
self._inflight.discard(event.message_id)
return event

async def dispatch(self, event: WebhookEvent) -> None:
for func in [*self._handlers.get(event.type, []), *self._catch_all]:
Expand All @@ -407,7 +424,13 @@ async def dispatch(self, event: WebhookEvent) -> None:
# aiohttp integration --------------------------------------------------

async def aiohttp_handler(self, request: web.Request) -> web.Response:
"""An aiohttp request handler. Answers quickly; handler errors are logged."""
"""An aiohttp request handler.

Event webhooks get 200 as soon as they verify, and handlers run in the
background (errors are logged). Drops claims are synchronous, as Kick
requires: handlers run first, and the answer is 200 only if they
succeed, otherwise 500.
"""
from aiohttp import web

body = await request.read()
Expand All @@ -419,7 +442,16 @@ async def aiohttp_handler(self, request: web.Request) -> web.Response:
except WebhookKeyUnavailable as exc:
log.warning("could not verify webhook: %s", exc)
return web.Response(status=503, text="try again")
if event is not None:
if event is None and _header(request.headers, HEADER_MESSAGE_ID) in self._inflight:
# The first copy is still being handled; don't confirm what may yet fail.
return web.Response(status=503, text="still processing")
if event is not None and event.type == DROPS_REWARD_CLAIMED:
try:
await self._dispatch_once(event)
except Exception:
log.exception("drops claim handler failed for %s", event.message_id)
return web.Response(status=500, text="claim not processed")
elif event is not None:
self._remember(event.message_id)
task = asyncio.create_task(self._safe_dispatch(event))
self._tasks.add(task)
Expand Down
72 changes: 72 additions & 0 deletions tests/test_webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,3 +300,75 @@ async def broken() -> rsa.RSAPublicKey:
with pytest.raises(WebhookKeyUnavailable):
await hook.handle(headers, body)
assert calls[0] == 1


CLAIM = {
"claim_id": "01CLAIM",
"user_id": 42,
"campaign_id": "01CAMP",
"reward_id": "01REW",
"external_id": "sword-1",
}


def drops_signed(
payload: dict[str, Any], message_id: str = "01DROP"
) -> tuple[dict[str, str], bytes]:
headers, body = signed("unused", payload, message_id=message_id)
# Drops claim webhooks: no type/version/subscription headers, and a different timestamp name.
return {
"Kick-Event-Signature": headers["Kick-Event-Signature"],
"Kick-Event-Message-ID": headers["Kick-Event-Message-Id"],
"Kick-Event-Timestamp": headers["Kick-Event-Message-Timestamp"],
}, body


async def test_drops_claim_webhook() -> None:
from kickpython import DROPS_REWARD_CLAIMED, DropsRewardClaimed

hook = WebhookHandler(PEM, broadcaster_user_ids=[123]) # allowlist must not block drops
got: list[WebhookEvent] = []

@hook.on(DROPS_REWARD_CLAIMED)
def on_claim(event: WebhookEvent) -> None:
got.append(event)

headers, body = drops_signed(CLAIM)
event = await hook.handle(headers, body)
assert event is not None and event.type == DROPS_REWARD_CLAIMED
claim = event.payload
assert isinstance(claim, DropsRewardClaimed)
assert (claim.claim_id, claim.user_id, claim.external_id) == ("01CLAIM", 42, "sword-1")
assert event.timestamp is not None and got == [event]


async def test_untyped_non_drops_body_is_rejected() -> None:
hook = WebhookHandler(PEM)
headers, body = drops_signed({"hello": "world"})
with pytest.raises(WebhookVerificationError, match="Kick-Event-Type"):
await hook.handle(headers, body)


async def test_aiohttp_drops_claim_is_synchronous() -> None:
hook = WebhookHandler(PEM)
calls: list[str] = []

@hook.on("drops.reward.claimed")
async def fulfil(event: WebhookEvent) -> None:
calls.append(event.message_id)
if len(calls) == 1:
raise RuntimeError("game server down")

client = TestClient(TestServer(hook.aiohttp_app("/hook")))
await client.start_server()
try:
headers, body = drops_signed(CLAIM)
first = await client.post("/hook", data=body, headers=headers)
assert first.status == 500 # Kick will retry
retry = await client.post("/hook", data=body, headers=headers)
assert retry.status == 200
again = await client.post("/hook", data=body, headers=headers)
assert again.status == 200 # idempotent: already fulfilled, not run again
assert len(calls) == 2
finally:
await client.close()