kickpython 0.1.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/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """
2
+ KickPython - Python wrapper for Kick.com API
3
+ """
4
+
5
+ from .api import KickAPI
6
+
7
+ __version__ = "0.1.0"
8
+ __author__ = "berkay.digital"
9
+ __all__ = ["KickAPI"]
kickpython/api.py ADDED
@@ -0,0 +1,844 @@
1
+ import aiohttp
2
+ import asyncio
3
+ import websockets
4
+ import json
5
+ import logging
6
+ import sqlite3
7
+ import os
8
+ import base64
9
+ import hashlib
10
+ import secrets
11
+ import time
12
+ import urllib.parse
13
+ from typing import Optional, Dict, List, Any, Callable, Tuple
14
+ from curl_cffi import requests
15
+
16
+ logging.basicConfig(level=logging.INFO)
17
+ logger = logging.getLogger(__name__)
18
+
19
+ class KickAPI:
20
+ def __init__(self, client_id=None, client_secret=None, redirect_uri=None,
21
+ base_url="https://api.kick.com/public/v1",
22
+ oauth_base_url="https://id.kick.com",
23
+ db_path="kick_tokens.db",
24
+ proxy=None, proxy_auth=None, **kwargs):
25
+ self.base_url = base_url
26
+ self.oauth_base_url = oauth_base_url
27
+ self.client_id = client_id
28
+ self.client_secret = client_secret
29
+ self.redirect_uri = redirect_uri
30
+ self.db_path = db_path
31
+ self.proxy = proxy
32
+ self.proxy_auth = proxy_auth
33
+ self.extra_kwargs = kwargs
34
+ self.ws = None
35
+ self.message_handlers = []
36
+ self.session = None
37
+ self.refresh_task = None
38
+ self._refresh_interval = 3600 # Refresh tokens every hour
39
+ self._should_refresh = False
40
+
41
+ # Initialize database if needed
42
+ self._init_db()
43
+
44
+ def _init_db(self):
45
+ """Initialize SQLite database for token storage"""
46
+ conn = sqlite3.connect(self.db_path)
47
+ cursor = conn.cursor()
48
+ cursor.execute('''
49
+ CREATE TABLE IF NOT EXISTS tokens (
50
+ channel_id TEXT PRIMARY KEY,
51
+ access_token TEXT NOT NULL,
52
+ refresh_token TEXT NOT NULL,
53
+ expires_at INTEGER NOT NULL,
54
+ scope TEXT
55
+ )
56
+ ''')
57
+
58
+ # Add a table to store chatroom IDs if it doesn't exist
59
+ cursor.execute('''
60
+ CREATE TABLE IF NOT EXISTS kick_users (
61
+ kick_id INTEGER PRIMARY KEY,
62
+ user_id INTEGER,
63
+ slug TEXT,
64
+ is_banned INTEGER,
65
+ playback_url TEXT,
66
+ vod_enabled INTEGER,
67
+ subscription_enabled INTEGER,
68
+ followers_count INTEGER,
69
+ verified INTEGER,
70
+ can_host INTEGER,
71
+ username TEXT UNIQUE,
72
+ bio TEXT,
73
+ profile_pic TEXT,
74
+ chatroom_id INTEGER NOT NULL
75
+ )
76
+ ''')
77
+
78
+ conn.commit()
79
+ conn.close()
80
+
81
+ def _get_headers_with_token(self, token, content_type=None):
82
+ headers = {
83
+ "Accept": "application/json",
84
+ "User-Agent": "KickPython/1.0",
85
+ "Authorization": f"Bearer {token}"
86
+ }
87
+
88
+ if content_type:
89
+ headers["Content-Type"] = content_type
90
+
91
+ return headers
92
+
93
+ def _get_headers(self, content_type=None, channel_id=None):
94
+ """Get headers with authentication token if available"""
95
+ headers = {
96
+ "Accept": "application/json",
97
+ "User-Agent": "KickPython/1.0"
98
+ }
99
+
100
+ # Try to get token for specific channel if provided
101
+ if channel_id:
102
+ token = self._get_token_for_channel(channel_id)
103
+ if token:
104
+ headers["Authorization"] = f"Bearer {token}"
105
+
106
+ if content_type:
107
+ headers["Content-Type"] = content_type
108
+
109
+ return headers
110
+
111
+ def _get_token_for_channel(self, channel_id):
112
+ """Get valid access token for a specific channel"""
113
+ conn = sqlite3.connect(self.db_path)
114
+ cursor = conn.cursor()
115
+ cursor.execute(
116
+ "SELECT access_token, refresh_token, expires_at FROM tokens WHERE channel_id = ?",
117
+ (channel_id,)
118
+ )
119
+ result = cursor.fetchone()
120
+ conn.close()
121
+
122
+ if not result:
123
+ return None
124
+
125
+ access_token, refresh_token, expires_at = result
126
+
127
+ # Check if token has expired or will expire soon (within 5 minutes)
128
+ current_time = int(time.time())
129
+ if expires_at - current_time < 300: # Less than 5 minutes remaining
130
+ # Refresh the token
131
+ new_tokens = asyncio.run(self.refresh_token(channel_id, refresh_token))
132
+ if new_tokens:
133
+ access_token = new_tokens["access_token"]
134
+
135
+ return access_token
136
+
137
+ def _generate_code_verifier(self):
138
+ """Generate a random code verifier for PKCE"""
139
+ code_verifier = secrets.token_urlsafe(64)
140
+ # Trim to a valid length (between 43-128 chars)
141
+ if len(code_verifier) > 128:
142
+ code_verifier = code_verifier[:128]
143
+ return code_verifier
144
+
145
+ def _generate_code_challenge(self, code_verifier):
146
+ """Generate code challenge from verifier using S256 method"""
147
+ code_challenge = hashlib.sha256(code_verifier.encode('utf-8')).digest()
148
+ return base64.urlsafe_b64encode(code_challenge).decode('utf-8').rstrip('=')
149
+
150
+ def _store_token(self, channel_id, access_token, refresh_token, expires_in, scope):
151
+ """Store token in the database"""
152
+ expires_at = int(time.time()) + int(expires_in)
153
+
154
+ conn = sqlite3.connect(self.db_path)
155
+ cursor = conn.cursor()
156
+ cursor.execute(
157
+ """
158
+ INSERT OR REPLACE INTO tokens
159
+ (channel_id, access_token, refresh_token, expires_at, scope)
160
+ VALUES (?, ?, ?, ?, ?)
161
+ """,
162
+ (channel_id, access_token, refresh_token, expires_at, scope)
163
+ )
164
+ conn.commit()
165
+ conn.close()
166
+
167
+ async def _init_session(self):
168
+ if not self.session:
169
+ self.session = aiohttp.ClientSession()
170
+
171
+ async def close(self):
172
+ await self.stop_token_refresh()
173
+ if self.session:
174
+ await self.session.close()
175
+ self.session = None
176
+ if self.ws:
177
+ await self.ws.close()
178
+ self.ws = None
179
+
180
+ def get_auth_url(self, scopes, state=None):
181
+ """
182
+ Generate authorization URL for OAuth flow
183
+
184
+ Args:
185
+ scopes (list): List of permission scopes to request
186
+ state (str, optional): Random state string for CSRF protection
187
+
188
+ Returns:
189
+ dict: Dictionary containing auth_url and code_verifier
190
+ """
191
+ if not self.client_id or not self.redirect_uri:
192
+ raise ValueError("client_id and redirect_uri must be provided to generate auth URL")
193
+
194
+ # Generate PKCE code verifier and challenge
195
+ code_verifier = self._generate_code_verifier()
196
+ code_challenge = self._generate_code_challenge(code_verifier)
197
+
198
+ # Generate random state if not provided
199
+ if state is None:
200
+ state = secrets.token_urlsafe(16)
201
+
202
+ # Construct scope string
203
+ scope_str = " ".join(scopes)
204
+
205
+ # Construct auth URL
206
+ params = {
207
+ "response_type": "code",
208
+ "client_id": self.client_id,
209
+ "redirect_uri": self.redirect_uri,
210
+ "scope": scope_str,
211
+ "code_challenge": code_challenge,
212
+ "code_challenge_method": "S256",
213
+ "state": state
214
+ }
215
+
216
+ auth_url = f"{self.oauth_base_url}/oauth/authorize?{urllib.parse.urlencode(params)}"
217
+
218
+ return {
219
+ "auth_url": auth_url,
220
+ "code_verifier": code_verifier,
221
+ "state": state
222
+ }
223
+
224
+ async def exchange_code(self, code, code_verifier, channel_id=None):
225
+ """
226
+ Exchange authorization code for tokens
227
+
228
+ Args:
229
+ code (str): Authorization code from redirect
230
+ code_verifier (str): PKCE code verifier used during authorization
231
+ channel_id (str): Channel ID for storing the tokens
232
+
233
+ Returns:
234
+ dict: Token response containing access and refresh tokens
235
+ """
236
+ if not self.client_id or not self.client_secret or not self.redirect_uri:
237
+ raise ValueError("client_id, client_secret, and redirect_uri must be provided")
238
+
239
+ await self._init_session()
240
+
241
+ data = {
242
+ "grant_type": "authorization_code",
243
+ "client_id": self.client_id,
244
+ "client_secret": self.client_secret,
245
+ "redirect_uri": self.redirect_uri,
246
+ "code_verifier": code_verifier,
247
+ "code": code
248
+ }
249
+
250
+ headers = {"Content-Type": "application/x-www-form-urlencoded"}
251
+
252
+ async with self.session.post(
253
+ f"{self.oauth_base_url}/oauth/token",
254
+ headers=headers,
255
+ data=data
256
+ ) as response:
257
+ if response.status != 200:
258
+ error_text = await response.text()
259
+ logger.error(f"Failed to exchange code: {error_text}")
260
+ return None
261
+
262
+ token_data = await response.json()
263
+
264
+ # Get channel_id if not provided
265
+ if not channel_id:
266
+ channel_id = await self.get_broadcaster_id(token_data["access_token"])
267
+ if not channel_id:
268
+ logger.error("Could not determine broadcaster ID from token")
269
+ return None
270
+
271
+ # Store token in database
272
+ self._store_token(
273
+ channel_id,
274
+ token_data["access_token"],
275
+ token_data["refresh_token"],
276
+ token_data["expires_in"],
277
+ token_data["scope"]
278
+ )
279
+
280
+ return token_data
281
+
282
+ async def refresh_token(self, channel_id, refresh_token=None):
283
+ """
284
+ Refresh an access token
285
+
286
+ Args:
287
+ channel_id (str): Channel ID whose token to refresh
288
+ refresh_token (str, optional): Refresh token to use. If not provided, will be fetched from DB
289
+
290
+ Returns:
291
+ dict: New token data or None if failed
292
+ """
293
+ if not self.client_id or not self.client_secret:
294
+ raise ValueError("client_id and client_secret must be provided to refresh tokens")
295
+
296
+ await self._init_session()
297
+
298
+ # Get refresh token from DB if not provided
299
+ if not refresh_token:
300
+ conn = sqlite3.connect(self.db_path)
301
+ cursor = conn.cursor()
302
+ cursor.execute("SELECT refresh_token FROM tokens WHERE channel_id = ?", (channel_id,))
303
+ result = cursor.fetchone()
304
+ conn.close()
305
+
306
+ if not result:
307
+ logger.error(f"No refresh token found for channel {channel_id}")
308
+ return None
309
+
310
+ refresh_token = result[0]
311
+
312
+ data = {
313
+ "grant_type": "refresh_token",
314
+ "client_id": self.client_id,
315
+ "client_secret": self.client_secret,
316
+ "refresh_token": refresh_token
317
+ }
318
+
319
+ headers = {"Content-Type": "application/x-www-form-urlencoded"}
320
+
321
+ async with self.session.post(
322
+ f"{self.oauth_base_url}/oauth/token",
323
+ headers=headers,
324
+ data=data
325
+ ) as response:
326
+ if response.status != 200:
327
+ error_text = await response.text()
328
+ logger.error(f"Failed to refresh token: {error_text}")
329
+ return None
330
+
331
+ token_data = await response.json()
332
+
333
+ # Store updated tokens
334
+ self._store_token(
335
+ channel_id,
336
+ token_data["access_token"],
337
+ token_data["refresh_token"],
338
+ token_data["expires_in"],
339
+ token_data["scope"]
340
+ )
341
+
342
+ return token_data
343
+
344
+ async def revoke_token(self, channel_id, token_type="access_token"):
345
+ """
346
+ Revoke a token
347
+
348
+ Args:
349
+ channel_id (str): Channel ID whose token to revoke
350
+ token_type (str): Type of token to revoke ('access_token' or 'refresh_token')
351
+
352
+ Returns:
353
+ bool: True if successful, False otherwise
354
+ """
355
+ conn = sqlite3.connect(self.db_path)
356
+ cursor = conn.cursor()
357
+ cursor.execute(f"SELECT {token_type} FROM tokens WHERE channel_id = ?", (channel_id,))
358
+ result = cursor.fetchone()
359
+ conn.close()
360
+
361
+ if not result:
362
+ logger.error(f"No {token_type} found for channel {channel_id}")
363
+ return False
364
+
365
+ token = result[0]
366
+
367
+ await self._init_session()
368
+
369
+ params = {
370
+ "token": token,
371
+ "token_hint_type": token_type
372
+ }
373
+
374
+ headers = {"Content-Type": "application/x-www-form-urlencoded"}
375
+
376
+ async with self.session.post(
377
+ f"{self.oauth_base_url}/oauth/revoke",
378
+ headers=headers,
379
+ params=params
380
+ ) as response:
381
+ if response.status != 200:
382
+ error_text = await response.text()
383
+ logger.error(f"Failed to revoke token: {error_text}")
384
+ return False
385
+
386
+ # Remove token from database
387
+ conn = sqlite3.connect(self.db_path)
388
+ cursor = conn.cursor()
389
+ cursor.execute("DELETE FROM tokens WHERE channel_id = ?", (channel_id,))
390
+ conn.commit()
391
+ conn.close()
392
+
393
+ return True
394
+
395
+ async def get_categories(self, query=None, **kwargs):
396
+ await self._init_session()
397
+ params = {}
398
+ if query:
399
+ params["q"] = query
400
+
401
+ async with self.session.get(
402
+ f"{self.base_url}/categories",
403
+ headers=self._get_headers(),
404
+ params=params,
405
+ **kwargs
406
+ ) as response:
407
+ return await response.json()
408
+
409
+ async def get_category(self, category_id, **kwargs):
410
+ await self._init_session()
411
+ async with self.session.get(
412
+ f"{self.base_url}/categories/{category_id}",
413
+ headers=self._get_headers(),
414
+ **kwargs
415
+ ) as response:
416
+ return await response.json()
417
+
418
+ async def post_chat(self, channel_id, content):
419
+ await self._init_session()
420
+
421
+ url = f"{self.base_url}/chat"
422
+ data = {
423
+ "content": content,
424
+ "type": "bot"
425
+ }
426
+ print(data)
427
+ print(url)
428
+ print(self._get_headers(content_type="application/json", channel_id=channel_id))
429
+
430
+ if not content:
431
+ raise ValueError("Content cannot be empty")
432
+ if not channel_id:
433
+ raise ValueError("Channel ID cannot be empty")
434
+ async with self.session.post(
435
+ url,
436
+ headers=self._get_headers(content_type="application/json", channel_id=channel_id),
437
+ json=data
438
+ ) as response:
439
+ if response.status != 200:
440
+ error_text = await response.text()
441
+ raise Exception(f"Failed to send message: {error_text}")
442
+ return await response.json()
443
+
444
+ def add_message_handler(self, handler: Callable):
445
+ self.message_handlers.append(handler)
446
+
447
+ async def _handle_ws_message(self, message: str):
448
+ try:
449
+ data = json.loads(message)
450
+ event = data.get('event')
451
+
452
+ if "ChatMessageEvent" in event:
453
+ chat_message = json.loads(data.get('data', '{}'))
454
+ channel = data.get('channel', '').split('.')
455
+ chat_id = channel[1] if len(channel) > 1 else None
456
+
457
+ if chat_id:
458
+ message_info = {
459
+ 'sender_username': chat_message.get('sender', {}).get('username'),
460
+ 'content': chat_message.get('content'),
461
+ 'badges': [badge.get('text') for badge in chat_message.get('sender', {}).get('identity', {}).get('badges', [])],
462
+ 'created_at': chat_message.get('created_at'),
463
+ 'chat_id': chat_id
464
+ }
465
+
466
+ for handler in self.message_handlers:
467
+ await handler(message_info)
468
+
469
+ except Exception as e:
470
+ logger.error(f"Error processing message: {e}")
471
+
472
+ async def get_chatroom_id(self, username):
473
+ """
474
+ Get the chatroom ID for a Kick.com username
475
+
476
+ Args:
477
+ username (str): Kick.com username to get chatroom ID for
478
+
479
+ Returns:
480
+ tuple: (chatroom_id, user_data) or (None, None) if not found
481
+ """
482
+ # First, try to get the user from the database
483
+ conn = sqlite3.connect(self.db_path)
484
+ cursor = conn.cursor()
485
+ cursor.execute("SELECT chatroom_id FROM kick_users WHERE username = ?", (username.lower(),))
486
+ result = cursor.fetchone()
487
+ conn.close()
488
+
489
+ if result:
490
+ return result[0], None
491
+
492
+ url_base = "https://kick.com/api/v2/channels/"
493
+ proxies = None
494
+
495
+ if self.proxy and self.proxy_auth:
496
+ proxies = {
497
+ "http": f"http://{self.proxy_auth}@{self.proxy}",
498
+ "https": f"http://{self.proxy_auth}@{self.proxy}"
499
+ }
500
+
501
+ max_retries = 4
502
+ username_variations = [
503
+ username,
504
+ username.replace('_', '-'),
505
+ username.replace('-', '_'),
506
+ username.replace('_', '-').replace('-', '_')
507
+ ]
508
+
509
+ for attempt in range(max_retries):
510
+ current_username = username_variations[attempt % len(username_variations)]
511
+ url = url_base + current_username
512
+
513
+ try:
514
+ response_kwargs = {"impersonate": "chrome"}
515
+ if proxies:
516
+ response_kwargs["proxies"] = proxies
517
+
518
+ response = requests.get(url, **response_kwargs)
519
+
520
+ if response.status_code == 200:
521
+ try:
522
+ data = json.loads(response.text)
523
+ chatroom_id = data['chatroom']['id']
524
+
525
+ # Save the data to the database
526
+ conn = sqlite3.connect(self.db_path)
527
+ cursor = conn.cursor()
528
+ cursor.execute(
529
+ """
530
+ INSERT OR REPLACE INTO kick_users
531
+ (kick_id, user_id, slug, is_banned, playback_url, vod_enabled,
532
+ subscription_enabled, followers_count, verified, can_host,
533
+ username, bio, profile_pic, chatroom_id)
534
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
535
+ """,
536
+ (
537
+ data['id'],
538
+ data['user_id'],
539
+ data['slug'],
540
+ 1 if data['is_banned'] else 0,
541
+ data['playback_url'],
542
+ 1 if data['vod_enabled'] else 0,
543
+ 1 if data['subscription_enabled'] else 0,
544
+ data['followers_count'],
545
+ 1 if data['verified'] else 0,
546
+ 1 if data['can_host'] else 0,
547
+ data['user']['username'].lower(),
548
+ data['user']['bio'],
549
+ data['user']['profile_pic'],
550
+ chatroom_id
551
+ )
552
+ )
553
+ conn.commit()
554
+ conn.close()
555
+
556
+ logger.info(f"Found and saved chatroom ID: {chatroom_id} for user: {current_username}")
557
+ return chatroom_id, data
558
+
559
+ except (json.JSONDecodeError, KeyError) as e:
560
+ logger.warning(f"Error processing JSON for {current_username}: {str(e)}")
561
+ else:
562
+ logger.warning(f"Failed to load page for {current_username}, status code: {response.status_code} on attempt {attempt + 1}")
563
+
564
+ if attempt < max_retries - 1:
565
+ await asyncio.sleep(1)
566
+
567
+ except Exception as e:
568
+ logger.error(f"An error occurred while fetching chatroom ID for {current_username} on attempt {attempt + 1}: {e}")
569
+
570
+ if attempt < max_retries - 1:
571
+ await asyncio.sleep(1)
572
+
573
+ logger.error(f"Failed to retrieve chatroom ID for {username} after {max_retries} attempts")
574
+ return None, None
575
+
576
+ async def connect_to_chatroom(self, username_or_chatroom_id: str):
577
+ """
578
+ Connect to a chatroom by username or chatroom ID
579
+
580
+ Args:
581
+ username_or_chatroom_id (str): Username or chatroom ID to connect to
582
+ """
583
+ # Check if input is numeric (chatroom ID) or a username
584
+ chatroom_id = None
585
+ if username_or_chatroom_id.isdigit():
586
+ chatroom_id = username_or_chatroom_id
587
+ else:
588
+ # Fetch chatroom ID for the username
589
+ chatroom_id, _ = await self.get_chatroom_id(username_or_chatroom_id)
590
+
591
+ if not chatroom_id:
592
+ raise ValueError(f"Could not find chatroom ID for {username_or_chatroom_id}")
593
+
594
+ APP_KEY = "32cbd69e4b950bf97679"
595
+ CLUSTER = "us2"
596
+
597
+ ws_url = f"wss://ws-{CLUSTER}.pusher.com/app/{APP_KEY}?protocol=7&client=js&version=8.4.0-rc2&flash=false"
598
+
599
+ async with websockets.connect(ws_url) as websocket:
600
+ self.ws = websocket
601
+
602
+ # Subscribe to the chatroom
603
+ subscribe_message = {
604
+ "event": "pusher:subscribe",
605
+ "data": {"auth": "", "channel": f"chatrooms.{chatroom_id}.v2"}
606
+ }
607
+ await websocket.send(json.dumps(subscribe_message))
608
+
609
+ logger.info(f"Connected to chatroom {chatroom_id}")
610
+
611
+ try:
612
+ while True:
613
+ message = await websocket.recv()
614
+ await self._handle_ws_message(message)
615
+ except websockets.exceptions.ConnectionClosed:
616
+ logger.warning("WebSocket connection closed")
617
+ except Exception as e:
618
+ logger.error(f"WebSocket error: {e}")
619
+ finally:
620
+ self.ws = None
621
+
622
+ def get_channel_id_from_chatroom(self, chatroom_id):
623
+ """
624
+ Get the channel ID from a chatroom ID
625
+
626
+ Args:
627
+ chatroom_id (str): Chatroom ID to get the channel ID for
628
+
629
+ Returns:
630
+ str: Channel ID or None if not found
631
+ """
632
+ try:
633
+ conn = sqlite3.connect(self.db_path)
634
+ cursor = conn.cursor()
635
+ cursor.execute("SELECT user_id FROM kick_users WHERE chatroom_id = ?", (chatroom_id,))
636
+ result = cursor.fetchone()
637
+ conn.close()
638
+
639
+ if result:
640
+ return str(result[0])
641
+ return None
642
+ except Exception as e:
643
+ logger.error(f"Database error: {e}")
644
+ return None
645
+
646
+ def check_token_exists(self, channel_id):
647
+ """
648
+ Check if a token exists for a given channel ID
649
+
650
+ Args:
651
+ channel_id (str): Channel ID to check for token existence
652
+
653
+ Returns:
654
+ bool: True if token exists, False otherwise
655
+ """
656
+ try:
657
+ conn = sqlite3.connect(self.db_path)
658
+ cursor = conn.cursor()
659
+ cursor.execute("SELECT access_token FROM tokens WHERE channel_id = ?", (channel_id,))
660
+ result = cursor.fetchone()
661
+ conn.close()
662
+
663
+ return result is not None
664
+ except Exception as e:
665
+ logger.error(f"Database error: {e}")
666
+ return False
667
+
668
+ async def fetch_channel_username(self, channel_id):
669
+ """
670
+ Fetch the username for a given channel ID
671
+
672
+ Args:
673
+ channel_id (str): Channel ID to fetch the username for
674
+
675
+ Returns:
676
+ str: Username or a default string if not found
677
+ """
678
+ try:
679
+ logger.info(f"Fetching username for channel ID: {channel_id}")
680
+ response = await self.get_channels(channel_id=channel_id)
681
+
682
+ if not response or not response.get('data'):
683
+ logger.warning(f"No channel data returned for channel_id: {channel_id}")
684
+ return f"channel_{channel_id}"
685
+
686
+ channel_data = response['data'][0]
687
+ return channel_data.get('slug', f"channel_{channel_id}")
688
+ except Exception as e:
689
+ logger.error(f"Error fetching channel username: {e}")
690
+ return f"channel_{channel_id}"
691
+
692
+ async def start_chat_listener(self, username_or_chatroom_id: str):
693
+ while True:
694
+ try:
695
+ await self.connect_to_chatroom(username_or_chatroom_id)
696
+ except Exception as e:
697
+ logger.error(f"Connection error: {e}")
698
+ await asyncio.sleep(5) # Wait before reconnecting
699
+
700
+ def run_chat_listener(self, username_or_chatroom_id: str):
701
+ loop = asyncio.get_event_loop()
702
+ loop.run_until_complete(self.start_chat_listener(username_or_chatroom_id))
703
+
704
+ # Keep other methods as async
705
+ async def update_channel(self, channel_id, category_id, stream_title, **kwargs):
706
+ await self._init_session()
707
+ data = {
708
+ "category_id": category_id,
709
+ "stream_title": stream_title
710
+ }
711
+
712
+ async with self.session.patch(
713
+ f"{self.base_url}/channels",
714
+ headers=self._get_headers(content_type="application/json", channel_id=channel_id),
715
+ json=data,
716
+ **kwargs
717
+ ) as response:
718
+ return await response.json()
719
+
720
+ async def get_users(self, channel_id=None, **kwargs):
721
+ await self._init_session()
722
+ async with self.session.get(
723
+ f"{self.base_url}/users",
724
+ headers=self._get_headers(channel_id=channel_id),
725
+ **kwargs
726
+ ) as response:
727
+ return await response.json()
728
+
729
+ async def get_channels(self, channel_id=None, **kwargs):
730
+ await self._init_session()
731
+ async with self.session.get(
732
+ f"{self.base_url}/channels",
733
+ headers=self._get_headers(channel_id=channel_id),
734
+ **kwargs
735
+ ) as response:
736
+ return await response.json()
737
+
738
+ async def start_token_refresh(self):
739
+ self._should_refresh = True
740
+ if self.refresh_task is None:
741
+ self.refresh_task = asyncio.create_task(self._token_refresh_loop())
742
+
743
+ async def stop_token_refresh(self):
744
+ self._should_refresh = False
745
+ if self.refresh_task:
746
+ self.refresh_task.cancel()
747
+ try:
748
+ await self.refresh_task
749
+ except asyncio.CancelledError:
750
+ pass
751
+ self.refresh_task = None
752
+
753
+ async def _token_refresh_loop(self):
754
+ while self._should_refresh:
755
+ try:
756
+ conn = sqlite3.connect(self.db_path)
757
+ cursor = conn.cursor()
758
+ cursor.execute("SELECT channel_id FROM tokens")
759
+ channels = cursor.fetchall()
760
+ conn.close()
761
+
762
+ for (channel_id,) in channels:
763
+ try:
764
+ await self.refresh_token(channel_id)
765
+ except Exception as e:
766
+ logger.error(f"Failed to refresh token for channel {channel_id}: {e}")
767
+
768
+ except Exception as e:
769
+ logger.error(f"Error in token refresh loop: {e}")
770
+
771
+ await asyncio.sleep(self._refresh_interval)
772
+
773
+ async def get_broadcaster_id(self, access_token):
774
+ await self._init_session()
775
+
776
+ headers = self._get_headers_with_token(access_token)
777
+
778
+ async with self.session.get(
779
+ f"{self.base_url}/channels",
780
+ headers=headers
781
+ ) as response:
782
+ if response.status != 200:
783
+ error_text = await response.text()
784
+ logger.error(f"Failed to get broadcaster ID: {error_text}")
785
+ return None
786
+
787
+ data = await response.json()
788
+ if 'data' in data and len(data['data']) > 0:
789
+ return data['data'][0]['broadcaster_user_id']
790
+
791
+ return None
792
+
793
+ async def get_all_chatroom_ids(self):
794
+ conn = sqlite3.connect(self.db_path)
795
+ cursor = conn.cursor()
796
+
797
+ cursor.execute("SELECT username, chatroom_id FROM kick_users")
798
+ user_results = cursor.fetchall()
799
+
800
+ cursor.execute("SELECT channel_id FROM tokens")
801
+ token_results = cursor.fetchall()
802
+
803
+ conn.close()
804
+
805
+ channels = []
806
+ for (channel_id,) in token_results:
807
+ found = False
808
+
809
+ conn = sqlite3.connect(self.db_path)
810
+ cursor = conn.cursor()
811
+ cursor.execute("SELECT chatroom_id FROM kick_users WHERE user_id = ?", (channel_id,))
812
+ chat_result = cursor.fetchone()
813
+ conn.close()
814
+
815
+ if chat_result:
816
+ found = True
817
+ logger.info(f"Found existing chatroom ID {chat_result[0]} for channel ID {channel_id}")
818
+
819
+ if not found:
820
+ try:
821
+ username = await self.fetch_channel_username(channel_id)
822
+ chatroom_id, _ = await self.get_chatroom_id(username)
823
+
824
+ if chatroom_id:
825
+ logger.info(f"Found chatroom ID {chatroom_id} for channel {channel_id} with username {username}")
826
+ except Exception as e:
827
+ logger.error(f"Error getting chatroom ID for channel {channel_id}: {e}")
828
+
829
+ conn = sqlite3.connect(self.db_path)
830
+ cursor = conn.cursor()
831
+
832
+ cursor.execute("SELECT username, chatroom_id FROM kick_users")
833
+ updated_user_results = cursor.fetchall()
834
+
835
+ conn.close()
836
+
837
+ for username, chatroom_id in updated_user_results:
838
+ channels.append({
839
+ 'username': username,
840
+ 'chatroom_id': str(chatroom_id)
841
+ })
842
+
843
+ logger.info(f"Found {len(channels)} channels to monitor")
844
+ return channels
kickpython/py.typed ADDED
File without changes
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 berkay.digital
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,196 @@
1
+ Metadata-Version: 2.2
2
+ Name: kickpython
3
+ Version: 0.1.0
4
+ Summary: Python wrapper for Kick.com API
5
+ Home-page: https://github.com/berkay-digital/kickpython
6
+ Author: berkay.digital
7
+ Author-email: "berkay.digital" <contact@berkay.digital>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/berkay-digital/kickpython
10
+ Project-URL: Documentation, https://github.com/berkay-digital/kickpython/tree/main/docs
11
+ Project-URL: Repository, https://github.com/berkay-digital/kickpython.git
12
+ Project-URL: Issues, https://github.com/berkay-digital/kickpython/issues
13
+ Requires-Python: >=3.6
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: author
17
+ Dynamic: home-page
18
+ Dynamic: requires-python
19
+
20
+ # KickPython - Python API Wrapper
21
+
22
+ A Python wrapper for the Kick.com API that provides easy access to Kick.com's public API endpoints and WebSocket chat functionality.
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ pip install kickpython
28
+ ```
29
+
30
+ ## Features
31
+
32
+ - OAuth 2.1 authentication with PKCE support
33
+ - Automatic token storage and refresh
34
+ - Channel management
35
+ - Chat message sending and receiving
36
+ - WebSocket-based chat listener
37
+ - Support for channel category management
38
+ - Proxy support
39
+
40
+ ## Usage
41
+
42
+ ### Basic Initialization
43
+
44
+ ```python
45
+ from kickpython import KickAPI
46
+
47
+ # For OAuth 2.1 authentication (recommended)
48
+ api = KickAPI(
49
+ client_id="your_client_id",
50
+ client_secret="your_client_secret",
51
+ redirect_uri="your_redirect_uri",
52
+ db_path="kick_tokens.db" # Optional, defaults to kick_tokens.db
53
+ )
54
+
55
+ # With proxy support
56
+ api = KickAPI(
57
+ client_id="your_client_id",
58
+ client_secret="your_client_secret",
59
+ redirect_uri="your_redirect_uri",
60
+ proxy="proxy.example.com:8080",
61
+ proxy_auth="username:password"
62
+ )
63
+ ```
64
+
65
+ ### OAuth Authentication
66
+
67
+ ```python
68
+ # Generate authorization URL with PKCE
69
+ auth_data = api.get_auth_url([
70
+ "user:read",
71
+ "channel:read",
72
+ "channel:write",
73
+ "chat:write",
74
+ "events:subscribe"
75
+ ])
76
+
77
+ # The auth URL for user authorization
78
+ auth_url = auth_data["auth_url"]
79
+ code_verifier = auth_data["code_verifier"]
80
+ state = auth_data["state"]
81
+
82
+ # After user authorization, exchange the code for tokens
83
+ token_data = await api.exchange_code(code, code_verifier)
84
+
85
+ # Tokens are automatically stored and managed
86
+ await api.start_token_refresh() # Start automatic token refresh
87
+ ```
88
+
89
+ ### Chat Functionality
90
+
91
+ #### Sending Messages
92
+
93
+ ```python
94
+ # Send a chat message
95
+ await api.post_chat(
96
+ channel_id="123",
97
+ content="Hello from the bot!"
98
+ )
99
+ ```
100
+
101
+ #### Listening to Chat Messages
102
+
103
+ ```python
104
+ # Define a message handler
105
+ async def message_handler(message):
106
+ username = message['sender_username']
107
+ content = message['content']
108
+ badges = message['badges']
109
+ chat_id = message['chat_id']
110
+ print(f"{username}: {content}")
111
+
112
+ # Add the message handler
113
+ api.add_message_handler(message_handler)
114
+
115
+ # Connect to a channel's chat
116
+ await api.connect_to_chatroom("channel_username")
117
+ # Or connect using chatroom ID
118
+ await api.connect_to_chatroom("123456")
119
+ ```
120
+
121
+ ### Channel Management
122
+
123
+ ```python
124
+ # Get channel information
125
+ channels = await api.get_channels()
126
+
127
+ # Update channel information
128
+ await api.update_channel(
129
+ channel_id="123",
130
+ category_id="456",
131
+ stream_title="New Stream Title"
132
+ )
133
+ ```
134
+
135
+ ### Category Management
136
+
137
+ ```python
138
+ # Get list of categories
139
+ categories = await api.get_categories()
140
+
141
+ # Search for specific categories
142
+ results = await api.get_categories(query="games")
143
+
144
+ # Get specific category
145
+ category = await api.get_category(category_id="123")
146
+ ```
147
+
148
+ ## Complete Examples
149
+
150
+ ### OAuth Web Server
151
+
152
+ See [examples/oauth.py](kickpython/examples/oauth.py) for a complete Flask-based OAuth implementation that includes:
153
+ - OAuth authorization flow with PKCE
154
+ - Token management interface
155
+ - Token refresh and revocation
156
+ - Example API usage
157
+
158
+ ### Chat Bot
159
+
160
+ See [examples/listen_all_channels.py](kickpython/examples/listen_all_channels.py) for a chat bot example that:
161
+ - Connects to multiple channels
162
+ - Handles chat messages
163
+ - Responds to commands
164
+ - Handles reconnection
165
+
166
+ ## Error Handling
167
+
168
+ The API methods throw exceptions for error conditions:
169
+ - `ValueError` for invalid input parameters
170
+ - `Exception` for API errors with error messages
171
+
172
+ Example:
173
+ ```python
174
+ try:
175
+ await api.post_chat(channel_id="123", content="")
176
+ except ValueError as e:
177
+ print("Invalid parameters:", e)
178
+ except Exception as e:
179
+ print("API error:", e)
180
+ ```
181
+
182
+ ## Available Scopes
183
+
184
+ - `user:read` - Access user information
185
+ - `channel:read` - Access channel information
186
+ - `channel:write` - Update channel metadata
187
+ - `chat:write` - Send chat messages
188
+ - `events:subscribe` - Subscribe to channel events
189
+
190
+ ## Contributing
191
+
192
+ Contributions are welcome! Please feel free to submit a Pull Request.
193
+
194
+ ## License
195
+
196
+ This project is licensed under the MIT License - see the LICENSE file for details.
@@ -0,0 +1,8 @@
1
+ kickpython/__init__.py,sha256=kBeAyCTyN4fTvXXNk0gPGYMnpEl4KEsqVKy5Fd17D_0,153
2
+ kickpython/api.py,sha256=4cXmef_8VUymLdfFSRlEZ9gUubzMYbqF5gQmSS0iYLA,30865
3
+ kickpython/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ kickpython-0.1.0.dist-info/LICENSE,sha256=Eq9Igq8OyVjZRODIgyVcVjG4TBJUELQCpG-ULLNTw9Q,1070
5
+ kickpython-0.1.0.dist-info/METADATA,sha256=inbdvmWbu1DwRD28o9dAeSYUK7TKcNEHaCKid_ZGIjE,4752
6
+ kickpython-0.1.0.dist-info/WHEEL,sha256=nn6H5-ilmfVryoAQl3ZQ2l8SH5imPWFpm1A5FgEuFV4,91
7
+ kickpython-0.1.0.dist-info/top_level.txt,sha256=mDDQz6hz_Z8Vc4djAyfeKkoZK5UgBJbQJfGVP9_Jh-w,11
8
+ kickpython-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.8.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ kickpython