kickpython 0.1.0__py3-none-any.whl → 0.1.2__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.
@@ -0,0 +1,89 @@
1
+ import asyncio
2
+ import sqlite3
3
+ from kickpython import KickAPI
4
+ import logging
5
+ import os
6
+ from dotenv import load_dotenv
7
+
8
+ load_dotenv()
9
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
10
+ logger = logging.getLogger(__name__)
11
+
12
+ class ChatListener:
13
+ def __init__(self, proxy=None, proxy_auth=None, db_path="kick_tokens.db"):
14
+ self.api = KickAPI(db_path=db_path, proxy=proxy, proxy_auth=proxy_auth)
15
+ self.db_path = db_path
16
+ self.channels = []
17
+ self.running_tasks = {}
18
+ self.api.add_message_handler(self.message_handler)
19
+
20
+ async def message_handler(self, message):
21
+ if message.get('content') == '!test':
22
+ try:
23
+ chatroom_id = message.get('chat_id')
24
+ sender = message.get('sender_username')
25
+ logger.info(f"Received !test command from {sender} in chatroom {chatroom_id}")
26
+
27
+ channel_id = self.api.get_channel_id_from_chatroom(chatroom_id)
28
+ if channel_id:
29
+ token_exists = self.api.check_token_exists(channel_id)
30
+ if token_exists:
31
+ await self.api.post_chat(channel_id, "Working!")
32
+ logger.info(f"Sent 'Working!' response to channel {channel_id} (chatroom {chatroom_id})")
33
+ else:
34
+ logger.warning(f"No token found for channel {channel_id} (chatroom {chatroom_id}), can't respond")
35
+ else:
36
+ logger.warning(f"No channel ID mapping found for chatroom {chatroom_id}, can't respond")
37
+ except Exception as e:
38
+ logger.error(f"Error handling message: {e}")
39
+
40
+ async def start_listener_for_channel(self, chatroom_id, username):
41
+ try:
42
+ logger.info(f"Starting listener for {username} (chatroom ID: {chatroom_id})")
43
+ while True:
44
+ try:
45
+ await self.api.connect_to_chatroom(chatroom_id)
46
+ except Exception as e:
47
+ logger.error(f"Connection error for {username}: {e}")
48
+ await asyncio.sleep(5)
49
+ except asyncio.CancelledError:
50
+ logger.info(f"Listener for {username} was cancelled")
51
+ raise
52
+
53
+ async def start_all_listeners(self):
54
+ self.channels = await self.api.get_all_chatroom_ids()
55
+
56
+ tasks = []
57
+ for channel in self.channels:
58
+ task = asyncio.create_task(
59
+ self.start_listener_for_channel(
60
+ channel['chatroom_id'],
61
+ channel['username']
62
+ )
63
+ )
64
+ tasks.append(task)
65
+ self.running_tasks[channel['chatroom_id']] = task
66
+
67
+ await asyncio.sleep(1)
68
+
69
+ try:
70
+ await asyncio.gather(*tasks)
71
+ except Exception as e:
72
+ logger.error(f"Error in listeners: {e}")
73
+
74
+ async def main():
75
+ listener = ChatListener(
76
+ proxy=os.getenv('PROXY', None),
77
+ proxy_auth=os.getenv('PROXY_AUTH', None),
78
+ )
79
+
80
+ await listener.start_all_listeners()
81
+
82
+ if __name__ == "__main__":
83
+ try:
84
+ loop = asyncio.get_event_loop()
85
+ loop.run_until_complete(main())
86
+ except KeyboardInterrupt:
87
+ logger.info("Program interrupted by user")
88
+ except Exception as e:
89
+ logger.error(f"Unexpected error: {e}")
@@ -0,0 +1,200 @@
1
+ import asyncio
2
+ import os
3
+ import sys
4
+ import logging
5
+ import sqlite3
6
+ import time
7
+ from kickpython import KickAPI
8
+ from flask import Flask, request, redirect, session
9
+
10
+ logging.basicConfig(level=logging.INFO)
11
+ logger = logging.getLogger(__name__)
12
+
13
+ app = Flask(__name__)
14
+ app.secret_key = os.environ.get("FLASK_SECRET_KEY", os.urandom(24))
15
+
16
+ api = KickAPI(
17
+ client_id=os.environ.get("KICK_CLIENT_ID"),
18
+ client_secret=os.environ.get("KICK_CLIENT_SECRET"),
19
+ redirect_uri=os.environ.get("KICK_REDIRECT_URI", "http://localhost:5000/callback"),
20
+ session_ttl=3600 # Sessions expire after 1 hour if not used
21
+ )
22
+
23
+ @app.route('/')
24
+ def home():
25
+ return """
26
+ <h1>Kick OAuth Example</h1>
27
+ <p>Go to <a href="/auth">Start OAuth Flow</a> to begin authentication for a channel.</p>
28
+ <p>Or go to <a href="/manage">Manage Tokens</a> to see your authenticated channels.</p>
29
+ """
30
+
31
+ @app.route('/auth')
32
+ def start_auth():
33
+ auth_data = api.get_auth_url([
34
+ "user:read",
35
+ "channel:read",
36
+ "channel:write",
37
+ "chat:write",
38
+ "events:subscribe"
39
+ ])
40
+
41
+ # Store both state and code verifier in Flask session for later use
42
+ session['kick_state'] = auth_data["state"]
43
+ session['kick_code_verifier'] = auth_data["code_verifier"]
44
+
45
+ # Redirect user to Kick auth page
46
+ return redirect(auth_data["auth_url"])
47
+
48
+ @app.route('/callback')
49
+ def callback():
50
+ # Get query parameters
51
+ code = request.args.get('code')
52
+ received_state = request.args.get('state')
53
+
54
+ # Get session data from Flask session
55
+ expected_state = session.get('kick_state')
56
+ code_verifier = session.get('kick_code_verifier')
57
+
58
+ if not expected_state or not code_verifier:
59
+ return "Error: No session found. Please start over.", 400
60
+
61
+ # Verify state parameter to prevent CSRF
62
+ if received_state != expected_state:
63
+ return "Error: State mismatch. Possible CSRF attack.", 400
64
+
65
+ # Exchange code for token
66
+ async def exchange():
67
+ try:
68
+ result = await api.exchange_code(code, code_verifier)
69
+ if result:
70
+ # Start the automatic token refresh
71
+ await api.start_token_refresh()
72
+ return result
73
+ except ValueError as e:
74
+ return {"error": str(e)}
75
+
76
+ token_data = asyncio.run(exchange())
77
+
78
+ if not token_data or "error" in token_data:
79
+ error_msg = token_data.get("error", "Unknown error") if token_data else "Failed to exchange code for token"
80
+ return f"Error: {error_msg}", 400
81
+
82
+ return f"""
83
+ <h1>Authentication successful!</h1>
84
+ <p>Token has been saved for your channel</p>
85
+ <p>Access token: {token_data['access_token'][:10]}...</p>
86
+ <p>Refresh token: {token_data['refresh_token'][:10]}...</p>
87
+ <p>Scopes: {token_data['scope']}</p>
88
+ <p>Token expires in: {token_data['expires_in']} seconds</p>
89
+ <p><a href="/manage">Manage your tokens</a></p>
90
+ """
91
+
92
+ @app.route('/manage')
93
+ def manage_tokens():
94
+ # List all tokens in the database
95
+ conn = api._init_db() # Reuse the db connection method
96
+ cursor = conn.cursor()
97
+ cursor.execute("SELECT channel_id, scope, expires_at FROM tokens")
98
+ tokens = cursor.fetchall()
99
+ conn.close()
100
+
101
+ current_time = int(time.time())
102
+ html = "<h1>Managed Tokens</h1>"
103
+
104
+ if not tokens:
105
+ html += "<p>No tokens found. <a href='/auth'>Authenticate a channel</a></p>"
106
+ else:
107
+ html += "<table border='1'><tr><th>Channel ID</th><th>Scopes</th><th>Expires In</th><th>Actions</th></tr>"
108
+ for channel_id, scopes, expires_at in tokens:
109
+ expires_in = expires_at - current_time
110
+ status = "Valid" if expires_in > 0 else "Expired"
111
+ html += f"""
112
+ <tr>
113
+ <td>{channel_id}</td>
114
+ <td>{scopes}</td>
115
+ <td>{expires_in} seconds ({status})</td>
116
+ <td>
117
+ <a href='/refresh/{channel_id}'>Refresh</a> |
118
+ <a href='/revoke/{channel_id}'>Revoke</a>
119
+ </td>
120
+ </tr>
121
+ """
122
+ html += "</table>"
123
+
124
+ html += "<p><a href='/auth'>Authenticate a new channel</a></p>"
125
+ return html
126
+
127
+ @app.route('/refresh/<channel_id>')
128
+ def refresh_token(channel_id):
129
+ async def do_refresh():
130
+ return await api.refresh_token(channel_id)
131
+
132
+ result = asyncio.run(do_refresh())
133
+
134
+ if not result:
135
+ return "Failed to refresh token", 400
136
+
137
+ return f"""
138
+ <h1>Token Refreshed</h1>
139
+ <p>New token for channel {channel_id} expires in {result['expires_in']} seconds.</p>
140
+ <p><a href='/manage'>Back to token management</a></p>
141
+ """
142
+
143
+ @app.route('/revoke/<channel_id>')
144
+ def revoke_token(channel_id):
145
+ async def do_revoke():
146
+ return await api.revoke_token(channel_id)
147
+
148
+ result = asyncio.run(do_revoke())
149
+
150
+ if not result:
151
+ return "Failed to revoke token", 400
152
+
153
+ return f"""
154
+ <h1>Token Revoked</h1>
155
+ <p>The access token for channel {channel_id} has been revoked.</p>
156
+ <p><a href='/manage'>Back to token management</a></p>
157
+ """
158
+
159
+ # Example of using stored tokens with the API
160
+ async def example_api_usage(channel_id):
161
+ try:
162
+ # Get channel information with the stored token
163
+ channel_info = await api.get_channels(channel_id=channel_id)
164
+ print(f"Channel info: {channel_info}")
165
+
166
+ # Send a chat message
167
+ chat_result = await api.post_chat(channel_id, "Hello from the OAuth example!")
168
+ print(f"Chat message sent: {chat_result}")
169
+
170
+ # Update channel info
171
+ update_result = await api.update_channel(
172
+ channel_id=channel_id,
173
+ category_id=123, # Replace with actual category ID
174
+ stream_title="Updated via OAuth API"
175
+ )
176
+ print(f"Channel updated: {update_result}")
177
+
178
+ except Exception as e:
179
+ print(f"Error using API: {e}")
180
+ finally:
181
+ await api.close()
182
+
183
+ async def cleanup():
184
+ await api.stop_token_refresh()
185
+ await api.close()
186
+
187
+ if __name__ == "__main__":
188
+ if len(sys.argv) > 1 and sys.argv[1] == "api_example":
189
+ # Run the API usage example with a specified channel ID
190
+ if len(sys.argv) > 2:
191
+ channel_id = sys.argv[2]
192
+ asyncio.run(example_api_usage(channel_id))
193
+ else:
194
+ print("Please provide a channel ID: python oauth_example.py api_example CHANNEL_ID")
195
+ else:
196
+ # Start the Flask OAuth server
197
+ try:
198
+ app.run(debug=True, use_reloader=False)
199
+ finally:
200
+ asyncio.run(cleanup())
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: kickpython
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: Python wrapper for Kick.com API
5
5
  Home-page: https://github.com/berkay-digital/kickpython
6
6
  Author: berkay.digital
@@ -0,0 +1,10 @@
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/examples/listen_all_channels.py,sha256=QhdqJopIKG-8sIpaRBYa8m7j1WH2Mk7e3hydBhrs9vw,3399
5
+ kickpython/examples/oauth.py,sha256=KkdWvXRRG-LlRb-vtZUVA3BbvVFCsSg02sRED8c4qqU,6615
6
+ kickpython-0.1.2.dist-info/LICENSE,sha256=Eq9Igq8OyVjZRODIgyVcVjG4TBJUELQCpG-ULLNTw9Q,1070
7
+ kickpython-0.1.2.dist-info/METADATA,sha256=4YDfQ17_iUuK4sAxBI-yrJr3G1FMcBFHfVaTMdazVu0,4752
8
+ kickpython-0.1.2.dist-info/WHEEL,sha256=nn6H5-ilmfVryoAQl3ZQ2l8SH5imPWFpm1A5FgEuFV4,91
9
+ kickpython-0.1.2.dist-info/top_level.txt,sha256=mDDQz6hz_Z8Vc4djAyfeKkoZK5UgBJbQJfGVP9_Jh-w,11
10
+ kickpython-0.1.2.dist-info/RECORD,,
@@ -1,8 +0,0 @@
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,,