kickpython 0.1.4__py3-none-any.whl → 1.0.0__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.
kickpython/client.py ADDED
@@ -0,0 +1,936 @@
1
+ """The Kick API client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import builtins
7
+ import urllib.parse
8
+ import uuid
9
+ from collections.abc import Iterable, Mapping, Sequence
10
+ from typing import TYPE_CHECKING, Any, Literal, TypeVar
11
+
12
+ import aiohttp
13
+ from pydantic import BaseModel, TypeAdapter
14
+
15
+ from ._http import DEFAULT_API_BASE, DEFAULT_OAUTH_BASE, AuthMode, Params, Transport
16
+ from .errors import KickAPIError, MissingTokenError, OAuthError
17
+ from .models import (
18
+ AdBreak,
19
+ AdBreakStatus,
20
+ Category,
21
+ Channel,
22
+ ChatMessageSent,
23
+ DropsClaim,
24
+ EventSubscription,
25
+ FailedRedemption,
26
+ KicksLeaderboard,
27
+ Livestream,
28
+ LivestreamsStats,
29
+ Page,
30
+ RedemptionStatus,
31
+ Reward,
32
+ RewardRedemptions,
33
+ SubscriptionResult,
34
+ TokenInfo,
35
+ User,
36
+ )
37
+ from .oauth import AuthorizationRequest, build_authorization_url
38
+ from .scopes import EventType, Scope
39
+ from .tokens import Token, TokenStore
40
+
41
+ if TYPE_CHECKING:
42
+ from types import TracebackType
43
+
44
+ __all__ = ["KickClient"]
45
+
46
+ M = TypeVar("M", bound=BaseModel)
47
+ T = TypeVar("T")
48
+
49
+ MAX_CHAT_BYTES = 2048
50
+
51
+
52
+ def _data(body: Any) -> Any:
53
+ return body.get("data") if isinstance(body, dict) else body
54
+
55
+
56
+ def _parse(model: type[M], value: Any) -> M:
57
+ return model.model_validate(value)
58
+
59
+
60
+ def _parse_list(model: type[M], value: Any) -> list[M]:
61
+ return TypeAdapter(list[model]).validate_python(value or []) # type: ignore[valid-type]
62
+
63
+
64
+ def _chunks(values: Sequence[T], size: int) -> Iterable[Sequence[T]]:
65
+ for i in range(0, len(values), size):
66
+ yield values[i : i + size]
67
+
68
+
69
+ def _ids(values: Iterable[int | str] | int | str | None) -> list[int] | None:
70
+ if values is None:
71
+ return None
72
+ if isinstance(values, (int, str)):
73
+ values = [values]
74
+ return [int(v) for v in values]
75
+
76
+
77
+ def _strs(values: Iterable[str] | str | None) -> list[str] | None:
78
+ if values is None:
79
+ return None
80
+ if isinstance(values, str):
81
+ return [values]
82
+ return [str(v) for v in values]
83
+
84
+
85
+ class KickClient:
86
+ """Async client for the official Kick API (https://docs.kick.com).
87
+
88
+ Use it as an async context manager, or call :meth:`close` when done::
89
+
90
+ async with KickClient(client_id, client_secret) as kick:
91
+ channel = await kick.channels.get_by_slug("berkaydigital")
92
+
93
+ Without a bound user, requests use an app access token (client
94
+ credentials), fetched and renewed for you. Endpoints that act on a user's
95
+ behalf need that user's token: authorize them once with
96
+ :meth:`authorization_url` and :meth:`exchange_code`, then use
97
+ :meth:`as_user`::
98
+
99
+ me = kick.as_user(user_id)
100
+ await me.chat.send("hello chat")
101
+
102
+ Args:
103
+ client_id: Your app's client ID from https://kick.com/settings/developer.
104
+ client_secret: Your app's client secret.
105
+ access_token: Use this fixed token for every request instead of
106
+ managing tokens. Handy for scripts; it is never refreshed.
107
+ token_store: Where user tokens are saved. Defaults to memory. Use
108
+ :class:`~kickpython.SQLiteTokenStore` or
109
+ :class:`~kickpython.JSONFileTokenStore` to survive restarts.
110
+ session: An existing ``aiohttp.ClientSession`` to reuse. The client
111
+ won't close a session it didn't create.
112
+ user_agent: User-Agent header for API requests.
113
+ timeout: Total timeout per HTTP request, in seconds.
114
+ max_retries: Retries for rate limits (429) and failed GET requests.
115
+ """
116
+
117
+ def __init__(
118
+ self,
119
+ client_id: str | None = None,
120
+ client_secret: str | None = None,
121
+ *,
122
+ access_token: str | None = None,
123
+ token_store: TokenStore | None = None,
124
+ session: aiohttp.ClientSession | None = None,
125
+ user_agent: str | None = None,
126
+ api_base: str = DEFAULT_API_BASE,
127
+ oauth_base: str = DEFAULT_OAUTH_BASE,
128
+ timeout: float = 30.0,
129
+ max_retries: int = 3,
130
+ ) -> None:
131
+ self._http = Transport(
132
+ client_id=client_id,
133
+ client_secret=client_secret,
134
+ access_token=access_token,
135
+ token_store=token_store,
136
+ session=session,
137
+ user_agent=user_agent,
138
+ api_base=api_base,
139
+ oauth_base=oauth_base,
140
+ timeout=timeout,
141
+ max_retries=max_retries,
142
+ )
143
+ self._user_id: int | None = None
144
+ self._root = True
145
+ self._init_resources()
146
+
147
+ def _init_resources(self) -> None:
148
+ self.users = UsersAPI(self)
149
+ self.channels = ChannelsAPI(self)
150
+ self.chat = ChatAPI(self)
151
+ self.moderation = ModerationAPI(self)
152
+ self.rewards = RewardsAPI(self)
153
+ self.livestreams = LivestreamsAPI(self)
154
+ self.categories = CategoriesAPI(self)
155
+ self.events = EventsAPI(self)
156
+ self.kicks = KicksAPI(self)
157
+ self.ads = AdsAPI(self)
158
+ self.drops = DropsAPI(self)
159
+
160
+ # Lifecycle --------------------------------------------------------------
161
+
162
+ async def __aenter__(self) -> KickClient:
163
+ return self
164
+
165
+ async def __aexit__(
166
+ self,
167
+ exc_type: type[BaseException] | None,
168
+ exc: BaseException | None,
169
+ tb: TracebackType | None,
170
+ ) -> None:
171
+ await self.close()
172
+
173
+ async def close(self) -> None:
174
+ """Close the HTTP session (only if the client created it)."""
175
+ if self._root:
176
+ await self._http.close()
177
+
178
+ def __repr__(self) -> str:
179
+ bound = f" user_id={self._user_id}" if self._user_id is not None else ""
180
+ return f"<KickClient{bound}>"
181
+
182
+ # Users ------------------------------------------------------------------
183
+
184
+ @property
185
+ def user_id(self) -> int | None:
186
+ """The user this view acts as, or ``None`` for the app itself."""
187
+ return self._user_id
188
+
189
+ @property
190
+ def token_store(self) -> TokenStore:
191
+ return self._http.store
192
+
193
+ def as_user(self, user_id: int | str) -> KickClient:
194
+ """A view of this client that acts as ``user_id``, using their stored token.
195
+
196
+ The view shares the session, token store and refresh locks with this
197
+ client. It is cheap; create one per request if you like.
198
+ """
199
+ view = object.__new__(KickClient)
200
+ view._http = self._http
201
+ view._user_id = int(user_id)
202
+ view._root = False
203
+ view._init_resources()
204
+ return view
205
+
206
+ def _require_user_id(self, value: int | str | None, what: str = "broadcaster_user_id") -> int:
207
+ if value is not None:
208
+ return int(value)
209
+ if self._user_id is not None:
210
+ return self._user_id
211
+ raise ValueError(f"pass {what}, or call this on client.as_user(user_id)")
212
+
213
+ async def _request(
214
+ self,
215
+ method: str,
216
+ path: str,
217
+ *,
218
+ auth: AuthMode = "any",
219
+ params: Params = None,
220
+ json: Any = None,
221
+ ) -> Any:
222
+ return await self._http.request(
223
+ method, path, auth=auth, user_id=self._user_id, params=params, json=json
224
+ )
225
+
226
+ # OAuth ------------------------------------------------------------------
227
+
228
+ def authorization_url(
229
+ self,
230
+ redirect_uri: str,
231
+ scopes: Iterable[Scope | str],
232
+ *,
233
+ state: str | None = None,
234
+ ) -> AuthorizationRequest:
235
+ """Start the authorization code flow (with PKCE).
236
+
237
+ Redirect the user to ``request.url`` and keep ``request.state`` and
238
+ ``request.code_verifier`` (in their session, for example) until Kick
239
+ redirects back to ``redirect_uri`` with ``?code=...&state=...``.
240
+ """
241
+ if not self._http.client_id:
242
+ raise MissingTokenError("client_id is required to build an authorization URL")
243
+ return build_authorization_url(
244
+ client_id=self._http.client_id,
245
+ redirect_uri=redirect_uri,
246
+ scopes=scopes,
247
+ state=state,
248
+ oauth_base=self._http.oauth_base,
249
+ )
250
+
251
+ async def exchange_code(
252
+ self, code: str, *, code_verifier: str, redirect_uri: str, store: bool = True
253
+ ) -> Token:
254
+ """Exchange the ``code`` from the OAuth callback for a user token.
255
+
256
+ The returned token has ``user_id`` filled in, and is saved in the
257
+ token store unless ``store=False``. Finding the user ID needs the
258
+ ``user:read`` or ``channel:read`` scope. Without either, a
259
+ :class:`MissingTokenError` is raised with the unsaved token on
260
+ ``exc.token`` (with ``store=False`` the token is returned with
261
+ ``user_id=None`` instead).
262
+ """
263
+ client_id, secret = self._http.require_credentials()
264
+ data = await self._http.oauth_post(
265
+ "/oauth/token",
266
+ form={
267
+ "grant_type": "authorization_code",
268
+ "client_id": client_id,
269
+ "client_secret": secret,
270
+ "redirect_uri": redirect_uri,
271
+ "code_verifier": code_verifier,
272
+ "code": code,
273
+ },
274
+ )
275
+ token = Token.from_oauth_response(data)
276
+ try:
277
+ token = token.with_user(await self._lookup_user_id(token))
278
+ except MissingTokenError as exc:
279
+ if not store:
280
+ return token
281
+ exc.token = token # type: ignore[attr-defined]
282
+ raise
283
+ if store:
284
+ await self._http.store.set(token)
285
+ return token
286
+
287
+ async def add_user_token(self, token: Token) -> Token:
288
+ """Save a token you obtained elsewhere. Looks up ``user_id`` if missing."""
289
+ if token.user_id is None:
290
+ token = token.with_user(await self._lookup_user_id(token))
291
+ await self._http.store.set(token)
292
+ return token
293
+
294
+ async def _lookup_user_id(self, token: Token) -> int:
295
+ temp = KickClient(
296
+ access_token=token.access_token,
297
+ session=self._http.session,
298
+ api_base=self._http.api_base,
299
+ user_agent=self._http.user_agent,
300
+ )
301
+ unknown = not token.scopes
302
+ if unknown or token.has_scopes(Scope.USER_READ):
303
+ try:
304
+ return (await temp.users.me()).user_id
305
+ except (KickAPIError, MissingTokenError):
306
+ if not unknown:
307
+ raise
308
+ if unknown or token.has_scopes(Scope.CHANNEL_READ):
309
+ try:
310
+ return (await temp.channels.me()).broadcaster_user_id
311
+ except (KickAPIError, MissingTokenError):
312
+ if not unknown:
313
+ raise
314
+ raise MissingTokenError(
315
+ "can't tell which user this token belongs to: request the user:read scope"
316
+ )
317
+
318
+ async def refresh_user_token(self, user_id: int | str | None = None) -> Token:
319
+ """Refresh a user's token now and save the new one."""
320
+ uid = self._require_user_id(user_id, "user_id")
321
+ return await self._http.user_token(uid, force=True)
322
+
323
+ async def refresh_all_user_tokens(
324
+ self, *, concurrency: int = 5
325
+ ) -> dict[int, Token | Exception]:
326
+ """Refresh every stored user token.
327
+
328
+ Kick refresh tokens expire after a period of inactivity (the window
329
+ slides on every refresh), so long-idle bots can call this on a timer.
330
+ Failures are returned, not raised.
331
+ """
332
+ ids = await self._http.store.user_ids()
333
+ limit = asyncio.Semaphore(concurrency)
334
+
335
+ async def one(uid: int) -> Token:
336
+ async with limit:
337
+ return await self._http.user_token(uid, force=True)
338
+
339
+ results = await asyncio.gather(*(one(uid) for uid in ids), return_exceptions=True)
340
+ out: dict[int, Token | Exception] = {}
341
+ for uid, res in zip(ids, results, strict=True):
342
+ if isinstance(res, BaseException) and not isinstance(res, Exception):
343
+ raise res
344
+ out[uid] = res
345
+ return out
346
+
347
+ async def get_user_token(self, user_id: int | str | None = None) -> Token:
348
+ """A valid token for the user, refreshed first if it is about to expire."""
349
+ return await self._http.user_token(self._require_user_id(user_id, "user_id"))
350
+
351
+ async def get_app_token(self, *, force_new: bool = False) -> Token:
352
+ """The cached app access token (client credentials), fetched if needed."""
353
+ return await self._http.app_token(force=force_new)
354
+
355
+ async def revoke_token(
356
+ self, token: str, *, hint: Literal["access_token", "refresh_token"] | None = None
357
+ ) -> None:
358
+ """Revoke an access or refresh token."""
359
+ await self._http.oauth_post(
360
+ "/oauth/revoke", params={"token": token, "token_type_hint": hint}, form={}
361
+ )
362
+
363
+ async def revoke_user(self, user_id: int | str | None = None) -> None:
364
+ """Revoke a user's tokens at Kick, then remove them from the store.
365
+
366
+ Waits for any refresh in flight first, so the pair that gets revoked
367
+ is the current one. If Kick refuses either revocation the error is
368
+ raised and the token stays stored, so you can retry.
369
+ """
370
+ uid = self._require_user_id(user_id, "user_id")
371
+ async with self._http.exclusive_user(uid):
372
+ token = await self._http.store.get(uid)
373
+ if token is not None:
374
+ if token.refresh_token:
375
+ await self.revoke_token(token.refresh_token, hint="refresh_token")
376
+ await self.revoke_token(token.access_token, hint="access_token")
377
+ await self._http.store.delete(uid)
378
+
379
+ async def introspect(self, access_token: str | None = None) -> TokenInfo:
380
+ """Check a token. Defaults to the token this client would use.
381
+
382
+ Revoked, expired or unknown tokens give ``active=False``.
383
+ """
384
+ if access_token is None:
385
+ access_token, _ = await self._http._bearer("any", self._user_id)
386
+ try:
387
+ body = await self._http.oauth_post("/oauth/token/introspect", bearer=access_token)
388
+ except OAuthError as exc:
389
+ if exc.status == 401: # Kick answers 401 for revoked or unknown tokens
390
+ return TokenInfo(active=False)
391
+ raise
392
+ return _parse(TokenInfo, _data(body))
393
+
394
+ async def public_key(self) -> str:
395
+ """Kick's current public key (PEM) for verifying webhook signatures."""
396
+ body = await self._request("GET", "/public/v1/public-key", auth="none")
397
+ return str(_data(body)["public_key"])
398
+
399
+
400
+ class _Resource:
401
+ def __init__(self, client: KickClient) -> None:
402
+ self._client = client
403
+
404
+ async def _req(self, method: str, path: str, **kw: Any) -> Any:
405
+ return await self._client._request(method, path, **kw)
406
+
407
+
408
+ class UsersAPI(_Resource):
409
+ async def get(self, ids: Iterable[int | str] | int | None = None) -> list[User]:
410
+ """Users by ID. With no IDs, the authorized user (needs a user token)."""
411
+ if ids is None:
412
+ return [await self.me()]
413
+ id_list = _ids(ids) or []
414
+ out: list[User] = []
415
+ for chunk in _chunks(id_list, 50):
416
+ body = await self._req("GET", "/public/v1/users", params={"id": list(chunk)})
417
+ out += _parse_list(User, _data(body))
418
+ return out
419
+
420
+ async def me(self) -> User:
421
+ """The user this client acts as."""
422
+ body = await self._req("GET", "/public/v1/users", auth="user")
423
+ users = _parse_list(User, _data(body))
424
+ if not users:
425
+ raise MissingTokenError("Kick returned no user for this token")
426
+ return users[0]
427
+
428
+
429
+ class ChannelsAPI(_Resource):
430
+ async def get(
431
+ self,
432
+ *,
433
+ user_ids: Iterable[int | str] | int | None = None,
434
+ slugs: Iterable[str] | str | None = None,
435
+ ) -> list[Channel]:
436
+ """Channels by broadcaster user ID or by slug (not both).
437
+
438
+ With neither, returns the authorized user's channel. Requests over the
439
+ API's 50 item limit are split for you.
440
+ """
441
+ if user_ids is not None and slugs is not None:
442
+ raise ValueError("pass user_ids or slugs, not both")
443
+ if user_ids is None and slugs is None:
444
+ return [await self.me()]
445
+ values: list[Any]
446
+ if user_ids is not None:
447
+ key, values = "broadcaster_user_id", _ids(user_ids) or []
448
+ else:
449
+ key, values = "slug", _strs(slugs) or []
450
+ out: list[Channel] = []
451
+ for chunk in _chunks(values, 50):
452
+ body = await self._req("GET", "/public/v1/channels", params={key: list(chunk)})
453
+ out += _parse_list(Channel, _data(body))
454
+ return out
455
+
456
+ async def get_by_slug(self, slug: str) -> Channel | None:
457
+ found = await self.get(slugs=[slug])
458
+ return found[0] if found else None
459
+
460
+ async def get_by_user_id(self, user_id: int | str) -> Channel | None:
461
+ found = await self.get(user_ids=[user_id])
462
+ return found[0] if found else None
463
+
464
+ async def me(self) -> Channel:
465
+ """The channel of the user this client acts as."""
466
+ body = await self._req("GET", "/public/v1/channels", auth="user")
467
+ channels = _parse_list(Channel, _data(body))
468
+ if not channels:
469
+ raise MissingTokenError("Kick returned no channel for this token")
470
+ return channels[0]
471
+
472
+ async def update(
473
+ self,
474
+ *,
475
+ stream_title: str | None = None,
476
+ category_id: int | None = None,
477
+ custom_tags: Sequence[str] | None = None,
478
+ ) -> None:
479
+ """Update the livestream title, category and/or tags. Needs ``channel:write``."""
480
+ body: dict[str, Any] = {}
481
+ if stream_title is not None:
482
+ body["stream_title"] = stream_title
483
+ if category_id is not None:
484
+ body["category_id"] = int(category_id)
485
+ if custom_tags is not None:
486
+ if len(custom_tags) > 10:
487
+ raise ValueError("Kick allows at most 10 custom tags")
488
+ body["custom_tags"] = list(custom_tags)
489
+ if not body:
490
+ raise ValueError("set at least one of stream_title, category_id, custom_tags")
491
+ await self._req("PATCH", "/public/v1/channels", auth="user", json=body)
492
+
493
+
494
+ class ChatAPI(_Resource):
495
+ async def send(
496
+ self,
497
+ content: str,
498
+ *,
499
+ sender: Literal["bot", "user"] = "bot",
500
+ broadcaster_user_id: int | str | None = None,
501
+ reply_to: str | None = None,
502
+ ) -> ChatMessageSent:
503
+ """Send a chat message. Needs ``chat:write``.
504
+
505
+ ``sender="bot"`` (default) posts as your app's bot account into the
506
+ chat of the user whose token is used; ``broadcaster_user_id`` is
507
+ ignored. ``sender="user"`` posts as that user into
508
+ ``broadcaster_user_id``'s chat (defaults to their own chat).
509
+ ``reply_to`` is the ID of a message to reply to.
510
+
511
+ Kick limits messages to 500 characters and 2048 UTF-8 bytes.
512
+ """
513
+ if not content or not content.strip():
514
+ raise ValueError("content can't be empty")
515
+ if len(content.encode("utf-8")) > MAX_CHAT_BYTES:
516
+ raise ValueError(f"content is over Kick's {MAX_CHAT_BYTES} byte limit")
517
+ body: dict[str, Any] = {"content": content, "type": sender}
518
+ if sender == "user":
519
+ body["broadcaster_user_id"] = self._client._require_user_id(broadcaster_user_id)
520
+ if reply_to:
521
+ body["reply_to_message_id"] = str(reply_to)
522
+ data = _data(await self._req("POST", "/public/v1/chat", auth="user", json=body))
523
+ return _parse(ChatMessageSent, data)
524
+
525
+ async def reply(self, message_id: str, content: str, **kwargs: Any) -> ChatMessageSent:
526
+ """Shortcut for ``send(content, reply_to=message_id)``."""
527
+ return await self.send(content, reply_to=message_id, **kwargs)
528
+
529
+ async def delete(self, message_id: str) -> None:
530
+ """Delete a chat message. Needs ``moderation:chat_message:manage``."""
531
+ await self._req("DELETE", f"/public/v1/chat/{_seg(message_id)}", auth="user")
532
+
533
+
534
+ class ModerationAPI(_Resource):
535
+ async def ban(
536
+ self,
537
+ user_id: int | str,
538
+ *,
539
+ broadcaster_user_id: int | str | None = None,
540
+ reason: str | None = None,
541
+ ) -> None:
542
+ """Permanently ban a user from a chat. Needs ``moderation:ban``."""
543
+ await self._ban(user_id, broadcaster_user_id, None, reason)
544
+
545
+ async def timeout(
546
+ self,
547
+ user_id: int | str,
548
+ minutes: int,
549
+ *,
550
+ broadcaster_user_id: int | str | None = None,
551
+ reason: str | None = None,
552
+ ) -> None:
553
+ """Time a user out for 1 to 10080 minutes (7 days). Needs ``moderation:ban``."""
554
+ if not 1 <= int(minutes) <= 10080:
555
+ raise ValueError("timeout must be between 1 and 10080 minutes")
556
+ await self._ban(user_id, broadcaster_user_id, int(minutes), reason)
557
+
558
+ async def _ban(
559
+ self,
560
+ user_id: int | str,
561
+ broadcaster: int | str | None,
562
+ minutes: int | None,
563
+ reason: str | None,
564
+ ) -> None:
565
+ body: dict[str, Any] = {
566
+ "broadcaster_user_id": self._client._require_user_id(broadcaster),
567
+ "user_id": int(user_id),
568
+ }
569
+ if minutes is not None:
570
+ body["duration"] = minutes
571
+ if reason:
572
+ if len(reason) > 100:
573
+ raise ValueError("reason can be at most 100 characters")
574
+ body["reason"] = reason
575
+ await self._req("POST", "/public/v1/moderation/bans", auth="user", json=body)
576
+
577
+ async def unban(
578
+ self, user_id: int | str, *, broadcaster_user_id: int | str | None = None
579
+ ) -> None:
580
+ """Lift a ban or timeout. Needs ``moderation:ban``."""
581
+ body = {
582
+ "broadcaster_user_id": self._client._require_user_id(broadcaster_user_id),
583
+ "user_id": int(user_id),
584
+ }
585
+ await self._req("DELETE", "/public/v1/moderation/bans", auth="user", json=body)
586
+
587
+
588
+ class RewardsAPI(_Resource):
589
+ """Channel point rewards. Read needs ``channel:rewards:read``, the rest ``:write``."""
590
+
591
+ async def list(self) -> list[Reward]:
592
+ body = await self._req("GET", "/public/v1/channels/rewards", auth="user")
593
+ return _parse_list(Reward, _data(body))
594
+
595
+ async def create(
596
+ self,
597
+ title: str,
598
+ cost: int,
599
+ *,
600
+ description: str | None = None,
601
+ background_color: str | None = None,
602
+ is_enabled: bool | None = None,
603
+ is_user_input_required: bool | None = None,
604
+ should_redemptions_skip_request_queue: bool | None = None,
605
+ ) -> Reward:
606
+ body = _drop_none(
607
+ title=title,
608
+ cost=int(cost),
609
+ description=description,
610
+ background_color=background_color,
611
+ is_enabled=is_enabled,
612
+ is_user_input_required=is_user_input_required,
613
+ should_redemptions_skip_request_queue=should_redemptions_skip_request_queue,
614
+ )
615
+ data = _data(await self._req("POST", "/public/v1/channels/rewards", auth="user", json=body))
616
+ return _parse(Reward, data)
617
+
618
+ async def update(
619
+ self,
620
+ reward_id: str,
621
+ *,
622
+ title: str | None = None,
623
+ cost: int | None = None,
624
+ description: str | None = None,
625
+ background_color: str | None = None,
626
+ is_enabled: bool | None = None,
627
+ is_paused: bool | None = None,
628
+ is_user_input_required: bool | None = None,
629
+ should_redemptions_skip_request_queue: bool | None = None,
630
+ ) -> Reward:
631
+ """Update a reward. Only the app that created a reward can change it."""
632
+ body = _drop_none(
633
+ title=title,
634
+ cost=cost,
635
+ description=description,
636
+ background_color=background_color,
637
+ is_enabled=is_enabled,
638
+ is_paused=is_paused,
639
+ is_user_input_required=is_user_input_required,
640
+ should_redemptions_skip_request_queue=should_redemptions_skip_request_queue,
641
+ )
642
+ if not body:
643
+ raise ValueError("set at least one field to update")
644
+ data = _data(
645
+ await self._req(
646
+ "PATCH", f"/public/v1/channels/rewards/{_seg(reward_id)}", auth="user", json=body
647
+ )
648
+ )
649
+ return _parse(Reward, data)
650
+
651
+ async def delete(self, reward_id: str) -> None:
652
+ """Delete a reward. Only the app that created a reward can delete it."""
653
+ await self._req("DELETE", f"/public/v1/channels/rewards/{_seg(reward_id)}", auth="user")
654
+
655
+ async def redemptions(
656
+ self,
657
+ *,
658
+ reward_id: str | None = None,
659
+ status: RedemptionStatus | None = None,
660
+ ids: Iterable[str] | None = None,
661
+ cursor: str | None = None,
662
+ ) -> Page[RewardRedemptions]:
663
+ """Redemptions grouped by reward. Kick defaults ``status`` to ``pending``."""
664
+ id_list = _strs(ids)
665
+ if id_list and (reward_id or status):
666
+ raise ValueError("filtering by ids can't be combined with reward_id or status")
667
+ params = {"reward_id": reward_id, "status": status, "id": id_list, "cursor": cursor}
668
+ body = await self._req(
669
+ "GET", "/public/v1/channels/rewards/redemptions", auth="user", params=params
670
+ )
671
+
672
+ async def fetch(next_cursor: str) -> Page[RewardRedemptions]:
673
+ return await self.redemptions(
674
+ reward_id=reward_id, status=status, ids=id_list, cursor=next_cursor
675
+ )
676
+
677
+ return _page(RewardRedemptions, body, fetch)
678
+
679
+ async def accept(self, ids: Iterable[str] | str) -> builtins.list[FailedRedemption]:
680
+ """Accept pending redemptions (25 per call). Returns the ones that failed."""
681
+ return await self._resolve("accept", ids)
682
+
683
+ async def reject(self, ids: Iterable[str] | str) -> builtins.list[FailedRedemption]:
684
+ """Reject pending redemptions (25 per call). Returns the ones that failed."""
685
+ return await self._resolve("reject", ids)
686
+
687
+ async def _resolve(
688
+ self, action: str, ids: Iterable[str] | str
689
+ ) -> builtins.list[FailedRedemption]:
690
+ unique = list(dict.fromkeys(_strs(ids) or []))
691
+ failed: builtins.list[FailedRedemption] = []
692
+ for chunk in _chunks(unique, 25):
693
+ body = await self._req(
694
+ "POST",
695
+ f"/public/v1/channels/rewards/redemptions/{action}",
696
+ auth="user",
697
+ json={"ids": list(chunk)},
698
+ )
699
+ failed += _parse_list(FailedRedemption, _data(body))
700
+ return failed
701
+
702
+
703
+ class LivestreamsAPI(_Resource):
704
+ async def list(
705
+ self,
706
+ *,
707
+ category_ids: Iterable[int] | int | None = None,
708
+ language_codes: Iterable[str] | str | None = None,
709
+ limit: int | None = None,
710
+ cursor: str | None = None,
711
+ ) -> Page[Livestream]:
712
+ """Live streams, oldest first, with cursor pagination (up to 1000 per page)."""
713
+ cats, langs = _ids(category_ids), _strs(language_codes)
714
+ params = {"category_id": cats, "language_code": langs, "limit": limit, "cursor": cursor}
715
+ body = await self._req("GET", "/public/v2/livestreams", params=params)
716
+
717
+ async def fetch(next_cursor: str) -> Page[Livestream]:
718
+ return await self.list(
719
+ category_ids=cats, language_codes=langs, limit=limit, cursor=next_cursor
720
+ )
721
+
722
+ return _page(Livestream, body, fetch)
723
+
724
+ async def for_users(self, user_ids: Iterable[int | str] | int) -> builtins.list[Livestream]:
725
+ """Current livestreams of these broadcasters (offline ones are left out)."""
726
+ out: builtins.list[Livestream] = []
727
+ for chunk in _chunks(_ids(user_ids) or [], 100):
728
+ body = await self._req(
729
+ "GET", "/public/v1/users/livestreams", params={"user_id": list(chunk)}
730
+ )
731
+ out += _parse_list(Livestream, _data(body))
732
+ return out
733
+
734
+ async def stats(self) -> LivestreamsStats:
735
+ return _parse(
736
+ LivestreamsStats, _data(await self._req("GET", "/public/v1/livestreams/stats"))
737
+ )
738
+
739
+
740
+ class CategoriesAPI(_Resource):
741
+ async def list(
742
+ self,
743
+ *,
744
+ names: Iterable[str] | str | None = None,
745
+ tags: Iterable[str] | str | None = None,
746
+ ids: Iterable[int] | int | None = None,
747
+ limit: int | None = None,
748
+ cursor: str | None = None,
749
+ ) -> Page[Category]:
750
+ """Search categories by name or tag, or fetch them by ID. Paginated."""
751
+ name_list, tag_list, id_list = _strs(names), _strs(tags), _ids(ids)
752
+ params = {
753
+ # The spec says comma separated, but the API only accepts repeated keys.
754
+ "name": name_list,
755
+ "tag": tag_list,
756
+ "id": id_list,
757
+ "limit": limit,
758
+ "cursor": cursor,
759
+ }
760
+ body = await self._req("GET", "/public/v2/categories", params=params)
761
+
762
+ async def fetch(next_cursor: str) -> Page[Category]:
763
+ return await self.list(
764
+ names=name_list, tags=tag_list, ids=id_list, limit=limit, cursor=next_cursor
765
+ )
766
+
767
+ return _page(Category, body, fetch)
768
+
769
+ async def search(self, name: str, *, limit: int | None = None) -> Page[Category]:
770
+ return await self.list(names=[name], limit=limit)
771
+
772
+ async def get(self, category_id: int) -> Category | None:
773
+ page = await self.list(ids=[category_id])
774
+ return page.items[0] if page.items else None
775
+
776
+
777
+ EventSpec = EventType | str | tuple[EventType | str, int]
778
+
779
+
780
+ class EventsAPI(_Resource):
781
+ """Webhook event subscriptions. See :mod:`kickpython.webhooks` to receive them."""
782
+
783
+ async def list(
784
+ self, *, broadcaster_user_id: int | str | None = None
785
+ ) -> builtins.list[EventSubscription]:
786
+ params = {"broadcaster_user_id": broadcaster_user_id}
787
+ body = await self._req("GET", "/public/v1/events/subscriptions", params=params)
788
+ return _parse_list(EventSubscription, _data(body))
789
+
790
+ async def subscribe(
791
+ self,
792
+ events: Iterable[EventSpec] | EventSpec,
793
+ *,
794
+ broadcaster_user_id: int | str | None = None,
795
+ ) -> builtins.list[SubscriptionResult]:
796
+ """Subscribe to webhook events.
797
+
798
+ Items are event names, optionally as ``(name, version)`` tuples
799
+ (default version 1). With an app token, ``broadcaster_user_id`` is
800
+ required; with a user token Kick uses the token's user. Check
801
+ ``result.ok`` on each entry: Kick reports per-event errors in the body.
802
+ """
803
+ if isinstance(events, (str, EventType)) or _is_event_spec_tuple(events):
804
+ events = [events] # type: ignore[list-item]
805
+ payload: builtins.list[dict[str, Any]] = []
806
+ for ev in events:
807
+ name, version = ev if isinstance(ev, tuple) else (ev, 1)
808
+ payload.append({"name": str(name), "version": int(version)})
809
+ body: dict[str, Any] = {"events": payload, "method": "webhook"}
810
+ if broadcaster_user_id is not None:
811
+ body["broadcaster_user_id"] = int(broadcaster_user_id)
812
+ elif self._client.user_id is None and not self._client._http.static_token:
813
+ raise ValueError("broadcaster_user_id is required when subscribing with an app token")
814
+ data = _data(await self._req("POST", "/public/v1/events/subscriptions", json=body))
815
+ return _parse_list(SubscriptionResult, data)
816
+
817
+ async def unsubscribe(self, subscription_ids: Iterable[str] | str) -> None:
818
+ ids = _strs(subscription_ids) or []
819
+ for chunk in _chunks(ids, 50):
820
+ await self._req("DELETE", "/public/v1/events/subscriptions", params={"id": list(chunk)})
821
+
822
+ async def unsubscribe_all(self, *, broadcaster_user_id: int | str | None = None) -> int:
823
+ """Remove every subscription visible to this token. Returns how many."""
824
+ subs = await self.list(broadcaster_user_id=broadcaster_user_id)
825
+ if subs:
826
+ await self.unsubscribe([s.id for s in subs])
827
+ return len(subs)
828
+
829
+
830
+ class KicksAPI(_Resource):
831
+ async def leaderboard(self, *, top: int = 10) -> KicksLeaderboard:
832
+ """KICKs gifting leaderboard (lifetime, month, week). Needs ``kicks:read``."""
833
+ if not 1 <= top <= 100:
834
+ raise ValueError("top must be between 1 and 100")
835
+ body = await self._req(
836
+ "GET", "/public/v1/kicks/leaderboard", auth="user", params={"top": top}
837
+ )
838
+ return _parse(KicksLeaderboard, _data(body))
839
+
840
+
841
+ class AdsAPI(_Resource):
842
+ async def start_break(self, duration_seconds: int, *, id: str | None = None) -> AdBreak:
843
+ """Start an ad break of 7 to 90 seconds. Needs ``ads:write``.
844
+
845
+ ``id`` is an idempotency key (UUID); one is generated if omitted.
846
+ Errors carry a reason in ``exc.data``, such as ``CHANNEL_IS_NOT_LIVE``.
847
+ """
848
+ if not 7 <= duration_seconds <= 90:
849
+ raise ValueError("ad breaks must be 7 to 90 seconds long")
850
+ body = {"break_duration_seconds": int(duration_seconds), "id": id or str(uuid.uuid4())}
851
+ data = _data(await self._req("POST", "/public/v1/ads/ad-break", auth="user", json=body))
852
+ return _parse(AdBreak, data)
853
+
854
+ async def status(self) -> AdBreakStatus:
855
+ """Ad settings and recent ad breaks. Needs ``ads:read`` or ``ads:write``."""
856
+ body = await self._req("GET", "/public/v1/ads/ad-break-status", auth="user")
857
+ return _parse(AdBreakStatus, _data(body))
858
+
859
+ async def enroll(self) -> None:
860
+ """Enroll the channel in ads. Needs ``ads:write``."""
861
+ await self._req("POST", "/public/v1/ads/enroll", auth="user")
862
+
863
+
864
+ class DropsAPI(_Resource):
865
+ """Drops reward claims. Only for apps owned by an organization; uses the app token."""
866
+
867
+ async def claims(
868
+ self,
869
+ *,
870
+ campaign_id: str | None = None,
871
+ user_id: int | None = None,
872
+ claim_id: str | None = None,
873
+ external_status: str | None = None,
874
+ limit: int | None = None,
875
+ cursor: str | None = None,
876
+ ) -> Page[DropsClaim]:
877
+ params = {
878
+ "campaign_id": campaign_id,
879
+ "user_id": user_id,
880
+ "claim_id": claim_id,
881
+ "external_status": external_status,
882
+ "limit": limit,
883
+ "cursor": cursor,
884
+ }
885
+ body = await self._req("GET", "/public/v1/drops/claims", auth="app", params=params)
886
+ data = _data(body) or {}
887
+ items = _parse_list(DropsClaim, data.get("claims"))
888
+
889
+ async def fetch(next_cursor: str) -> Page[DropsClaim]:
890
+ return await self.claims(
891
+ campaign_id=campaign_id,
892
+ user_id=user_id,
893
+ claim_id=claim_id,
894
+ external_status=external_status,
895
+ limit=limit,
896
+ cursor=next_cursor,
897
+ )
898
+
899
+ return Page(items=items, next_cursor=data.get("cursor") or None, _fetch=fetch)
900
+
901
+ async def update_claims(self, statuses: Mapping[str, str]) -> None:
902
+ """Set ``external_status`` per claim ID, e.g. ``{claim_id: "processed"}``."""
903
+ items = [{"claim_id": k, "external_status": v} for k, v in statuses.items()]
904
+ for chunk in _chunks(items, 100):
905
+ await self._req(
906
+ "PATCH", "/public/v1/drops/claims", auth="app", json={"claims": list(chunk)}
907
+ )
908
+
909
+
910
+ def _is_event_spec_tuple(value: Any) -> bool:
911
+ return (
912
+ isinstance(value, tuple)
913
+ and len(value) == 2
914
+ and isinstance(value[0], (str, EventType))
915
+ and isinstance(value[1], int)
916
+ and not isinstance(value[1], bool)
917
+ )
918
+
919
+
920
+ def _seg(value: str) -> str:
921
+ """Quote an ID for use as one URL path segment."""
922
+ text = str(value)
923
+ if text in ("", ".", ".."):
924
+ raise ValueError(f"invalid ID {text!r}")
925
+ return urllib.parse.quote(text, safe="")
926
+
927
+
928
+ def _drop_none(**fields: Any) -> dict[str, Any]:
929
+ return {k: v for k, v in fields.items() if v is not None}
930
+
931
+
932
+ def _page(model: type[M], body: Any, fetch: Any) -> Page[M]:
933
+ items = _parse_list(model, _data(body))
934
+ pagination = body.get("pagination") if isinstance(body, dict) else None
935
+ cursor = pagination.get("next_cursor") if isinstance(pagination, dict) else None
936
+ return Page(items=items, next_cursor=cursor or None, _fetch=fetch)