H3y-sam commited on
Commit
add04fc
Β·
verified Β·
1 Parent(s): 20640b8

Upload 54 files

Browse files
Files changed (4) hide show
  1. README.md +5 -2
  2. bot.py +35 -2
  3. handlers/commands.py +16 -1
  4. web_app/dashboard.html +6 -6
README.md CHANGED
@@ -188,8 +188,11 @@ The bot tracks the last **60 topics** per *(channel Γ— content type Γ— subject)*
188
 
189
  1. Create the Telegram channel
190
  2. Add your bot as Admin with Post Messages permission
191
- 3. Use the bot command: `/add_channel <key> <@channel_id> <Label>`
192
- Example: `/add_channel neet_2 @NEET_MyChannel "NEET Daily 2"`
 
 
 
193
  4. Or add via the **Web Dashboard β†’ Channel Manager**
194
 
195
  The new channel is automatically scheduled β€” no restart needed.
 
188
 
189
  1. Create the Telegram channel
190
  2. Add your bot as Admin with Post Messages permission
191
+ 3. Use the bot command: `/add_channel <key> <@channel_username or -100 ID> <Label>`
192
+ Example (Public): `/add_channel neet_2 @NEET_MyChannel "NEET Daily 2"`
193
+ Example (Private): `/add_channel mock_priv -1001234567890 "Private 1"`
194
+
195
+ *Tip: When you add the bot as an admin to a private channel, it will automatically DM you its numeric ID.*
196
  4. Or add via the **Web Dashboard β†’ Channel Manager**
197
 
198
  The new channel is automatically scheduled β€” no restart needed.
bot.py CHANGED
@@ -14,7 +14,8 @@ from http.server import BaseHTTPRequestHandler, HTTPServer
14
  from telegram import Update
15
  from telegram.ext import (
16
  ApplicationBuilder, CommandHandler,
17
- CallbackQueryHandler, MessageHandler, filters
 
18
  )
19
  from telegram.request import HTTPXRequest
20
 
@@ -183,8 +184,12 @@ class BotHandler(BaseHTTPRequestHandler):
183
  return
184
 
185
  if path == "/api/add-channel":
 
 
 
 
186
  ok = config_manager.add_channel(
187
- body.get("key"), body.get("id"), body.get("label"),
188
  body.get("exam_focus", []), body.get("subjects", []),
189
  body.get("mcq_only", False)
190
  )
@@ -268,6 +273,8 @@ class BotHandler(BaseHTTPRequestHandler):
268
 
269
  if path == "/api/verify-channel":
270
  ch_id = body.get("channel_id")
 
 
271
  if _bot_loop and _bot_app:
272
  async def _verify(ch_id):
273
  chat = await _bot_app.bot.get_chat(ch_id)
@@ -333,6 +340,31 @@ def run_bot_engine():
333
  _bot_loop.run_forever()
334
 
335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336
  async def _start_polling():
337
  global _bot_app
338
  import socket, ssl
@@ -396,6 +428,7 @@ async def _start_polling():
396
 
397
  # ── Register all handlers (restores buttons + all commands) ───────────────
398
  _bot_app.add_handler(CommandHandler("start", start_command))
 
399
  _bot_app.add_handler(CommandHandler("status", status_command))
400
  _bot_app.add_handler(CommandHandler("help", help_command))
401
  _bot_app.add_handler(CommandHandler("channels", channels_command))
 
14
  from telegram import Update
15
  from telegram.ext import (
16
  ApplicationBuilder, CommandHandler,
17
+ CallbackQueryHandler, MessageHandler, filters,
18
+ ChatMemberHandler
19
  )
20
  from telegram.request import HTTPXRequest
21
 
 
184
  return
185
 
186
  if path == "/api/add-channel":
187
+ cid = body.get("id")
188
+ if isinstance(cid, str) and cid.lstrip('-').isdigit():
189
+ cid = int(cid)
190
+
191
  ok = config_manager.add_channel(
192
+ body.get("key"), cid, body.get("label"),
193
  body.get("exam_focus", []), body.get("subjects", []),
194
  body.get("mcq_only", False)
195
  )
 
273
 
274
  if path == "/api/verify-channel":
275
  ch_id = body.get("channel_id")
276
+ if isinstance(ch_id, str) and ch_id.lstrip('-').isdigit():
277
+ ch_id = int(ch_id)
278
  if _bot_loop and _bot_app:
279
  async def _verify(ch_id):
280
  chat = await _bot_app.bot.get_chat(ch_id)
 
340
  _bot_loop.run_forever()
341
 
342
 
343
+ async def chat_member_update(update: Update, context):
344
+ """Notify admins and log when bot is added to a channel (public or private)."""
345
+ result = update.my_chat_member
346
+ if not result:
347
+ return
348
+
349
+ # Check if we were promoted to admin or added to channel/group
350
+ chat = result.chat
351
+ new_status = result.new_chat_member.status
352
+ if new_status in ("administrator", "creator", "member"):
353
+ # We were added/promoted!
354
+ safe_title = chat.title.replace('<', '&lt;').replace('>', '&gt;')
355
+ msg = (f"πŸ€– <b>Bot Added to Chat/Channel!</b>\n"
356
+ f"Title: {safe_title}\n"
357
+ f"ID: <code>{chat.id}</code>\n"
358
+ f"Type: {chat.type}\n"
359
+ f"Added by: @{result.from_user.username or result.from_user.first_name}\n\n"
360
+ f"You can use this ID to add this private channel: \n<code>/add_channel my_key {chat.id} {safe_title}</code>\n"
361
+ f"Or via the Web Dashboard.")
362
+ for admin_id in ADMIN_USER_IDS:
363
+ try:
364
+ await context.bot.send_message(chat_id=admin_id, text=msg, parse_mode="HTML")
365
+ except Exception as e:
366
+ logger.error(f"Could not notify admin {admin_id} of new chat: {e}")
367
+
368
  async def _start_polling():
369
  global _bot_app
370
  import socket, ssl
 
428
 
429
  # ── Register all handlers (restores buttons + all commands) ───────────────
430
  _bot_app.add_handler(CommandHandler("start", start_command))
431
+ _bot_app.add_handler(ChatMemberHandler(chat_member_update, ChatMemberHandler.MY_CHAT_MEMBER))
432
  _bot_app.add_handler(CommandHandler("status", status_command))
433
  _bot_app.add_handler(CommandHandler("help", help_command))
434
  _bot_app.add_handler(CommandHandler("channels", channels_command))
handlers/commands.py CHANGED
@@ -33,7 +33,17 @@ async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
33
  active_chs = [c for c in config_manager.channels.values() if c.get("active")]
34
 
35
  if active_chs:
36
- ch_text = "\n\nπŸ”— *Join our Channels:*\n" + "\n".join([f"β€’ [{c['label']}]({c['id'] if c['id'].startswith('https') else 'https://t.me/'+c['id'].replace('@','')})" for c in active_chs[:5]])
 
 
 
 
 
 
 
 
 
 
37
  else:
38
  ch_text = f"\n\nπŸ”— *Join Main Channel:* [{s['main_channel_name']}]({s['main_channel_url']})"
39
 
@@ -128,6 +138,11 @@ async def add_channel_command(update: Update, context: ContextTypes.DEFAULT_TYPE
128
  return
129
 
130
  key, cid, label = args[0], args[1], " ".join(args[2:])
 
 
 
 
 
131
  config_manager.add_channel(key, cid, label)
132
  await reload_jobs(context.application)
133
  await update.message.reply_text(f"βœ… *Success!* Channel *{label}* has been registered and scheduled.", parse_mode="MarkdownV2")
 
33
  active_chs = [c for c in config_manager.channels.values() if c.get("active")]
34
 
35
  if active_chs:
36
+ links = []
37
+ for c in active_chs[:5]:
38
+ cid = str(c['id'])
39
+ if cid.startswith('https'):
40
+ link = cid
41
+ elif cid.startswith('@'):
42
+ link = f"https://t.me/{cid.replace('@', '')}"
43
+ else:
44
+ link = "https://t.me" # Fallback for private IDs without invite links
45
+ links.append(f"β€’ [{c['label']}]({link})")
46
+ ch_text = "\n\nπŸ”— *Join our Channels:*\n" + "\n".join(links)
47
  else:
48
  ch_text = f"\n\nπŸ”— *Join Main Channel:* [{s['main_channel_name']}]({s['main_channel_url']})"
49
 
 
138
  return
139
 
140
  key, cid, label = args[0], args[1], " ".join(args[2:])
141
+
142
+ # Let's ensure numeric IDs are cast to integer, as PTB requires int for numeric chat_ids
143
+ if cid.lstrip('-').isdigit():
144
+ cid = int(cid)
145
+
146
  config_manager.add_channel(key, cid, label)
147
  await reload_jobs(context.application)
148
  await update.message.reply_text(f"βœ… *Success!* Channel *{label}* has been registered and scheduled.", parse_mode="MarkdownV2")
web_app/dashboard.html CHANGED
@@ -764,9 +764,9 @@ h1, h2, h3, .sidebar-brand h2, .page-title, .card-title {
764
  </div>
765
 
766
  <div class="form-group">
767
- <label class="form-label">Channel Username *</label>
768
- <input class="form-input" id="new-ch-id" placeholder="@YourChannel" oninput="resetVerify()"/>
769
- <div class="form-hint">Must start with @. The bot must already be an admin of this channel.</div>
770
  </div>
771
  <button class="btn btn-ghost btn-sm" onclick="verifyChannel()" id="verify-btn">πŸ” Verify Channel</button>
772
  <div id="verify-result" class="verify-box"></div>
@@ -1107,7 +1107,7 @@ function resetVerify() {
1107
 
1108
  async function verifyChannel() {
1109
  const id = document.getElementById('new-ch-id').value.trim();
1110
- if (!id) { showToast('Enter a channel username first'); return; }
1111
  const btn = document.getElementById('verify-btn');
1112
  btn.textContent = '⏳ Verifying…'; btn.disabled = true;
1113
 
@@ -1128,9 +1128,9 @@ async function verifyChannel() {
1128
  document.getElementById('add-ch-form').style.display = 'block';
1129
  document.getElementById('add-ch-btn').disabled = false;
1130
  // Auto-fill key and label from verified data
1131
- const rawKey = d.username || id.replace('@','');
1132
  const key = rawKey.toLowerCase().replace(/[^a-z0-9]/g,'_');
1133
- document.getElementById('new-ch-key').value = key;
1134
  document.getElementById('new-ch-label').value = d.title;
1135
  } else {
1136
  verified = false;
 
764
  </div>
765
 
766
  <div class="form-group">
767
+ <label class="form-label">Channel Username or ID *</label>
768
+ <input class="form-input" id="new-ch-id" placeholder="@YourChannel or -100XXXXXXX" oninput="resetVerify()"/>
769
+ <div class="form-hint">Use @username for public channels or -100... integer ID for private channels. The bot must already be an admin.</div>
770
  </div>
771
  <button class="btn btn-ghost btn-sm" onclick="verifyChannel()" id="verify-btn">πŸ” Verify Channel</button>
772
  <div id="verify-result" class="verify-box"></div>
 
1107
 
1108
  async function verifyChannel() {
1109
  const id = document.getElementById('new-ch-id').value.trim();
1110
+ if (!id) { showToast('Enter a channel username or ID first'); return; }
1111
  const btn = document.getElementById('verify-btn');
1112
  btn.textContent = '⏳ Verifying…'; btn.disabled = true;
1113
 
 
1128
  document.getElementById('add-ch-form').style.display = 'block';
1129
  document.getElementById('add-ch-btn').disabled = false;
1130
  // Auto-fill key and label from verified data
1131
+ let rawKey = d.username || d.title || id.replace('@','').replace('-','');
1132
  const key = rawKey.toLowerCase().replace(/[^a-z0-9]/g,'_');
1133
+ document.getElementById('new-ch-key').value = key || `ch_${d.id}`;
1134
  document.getElementById('new-ch-label').value = d.title;
1135
  } else {
1136
  verified = false;