Muttered3 commited on
Commit
cc5bd79
Β·
verified Β·
1 Parent(s): 3226d6d

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +374 -348
bot.py CHANGED
@@ -1,433 +1,459 @@
 
 
 
 
1
  import asyncio
2
- import io
3
- import uuid
4
- import html
5
- from functools import wraps
6
  from datetime import datetime, timezone
 
7
  import pandas as pd
8
 
9
- from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
10
- from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes
11
- from telegram.error import TelegramError
12
 
13
  import config
14
  import database
15
- import scanner
16
- from wordlist import fetch_word_list
17
  from job_state import job
18
- import keep_alive
 
19
 
20
- # ── Admin guard ────────────────────────────────────────────────────────────
21
 
22
- def admin_only(func):
23
- @wraps(func)
24
- async def wrapper(update: Update, context: ContextTypes.DEFAULT_TYPE):
25
- if update.effective_user.id not in config.ADMIN_USER_IDS:
26
- return
27
- return await func(update, context)
28
- return wrapper
29
 
30
- # ── Builders ───────────────────────────────────────────────────────────────
 
31
 
32
- def build_progress_card(job_id, completed, total, elapsed, available_count) -> str:
33
- if total == 0:
34
- pct = 0.0
35
- else:
36
- pct = round((completed / total) * 100, 1)
37
-
38
- bar = job.get_bar(15)
39
- job_short = str(job_id)[:8] if job_id else "None"
40
-
41
- return (
42
- f"β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”\n"
43
- f"β”‚ πŸ“Š SCAN PROGRESS β”‚\n"
44
- f"β”‚ Job: {job_short:<22} β”‚\n"
45
- f"β”‚ {bar} {pct}% β”‚\n"
46
- f"β”‚ Done : {completed:,}/{total:,} β”‚\n"
47
- f"β”‚ Found: {available_count} available β”‚\n"
48
- f"β”‚ Time : {elapsed:<22} β”‚\n"
49
- f"β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜"
50
- )
51
 
52
  def build_stats_card(stats: dict) -> str:
53
- taken = stats.get("Taken", 0)
54
- avail = stats.get("Available", 0)
55
- unavail = stats.get("Unavailable", 0)
56
- blocked = stats.get("BLOCKED: Max Retries Hit", 0)
57
- total = stats.get("Total", 0)
58
- other = total - (taken + avail + unavail + blocked)
59
-
60
- return (
61
- f"β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”\n"
62
- f"β”‚ πŸ“¦ DATABASE STATS β”‚\n"
63
- f"β”‚ Taken : {taken:>8,} β”‚\n"
64
- f"β”‚ Available : {avail:>8,} β”‚\n"
65
- f"β”‚ Unavailable : {unavail:>8,} β”‚\n"
66
- f"β”‚ Blocked : {blocked:>8,} β”‚\n"
67
- f"β”‚ Other : {other:>8,} β”‚\n"
68
- f"β”‚ ─────────────────────────── β”‚\n"
69
- f"β”‚ Total : {total:>8,} β”‚\n"
70
- f"β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜"
71
- )
72
 
73
  def build_settings_text() -> str:
74
- return (
75
- f"╔══════════════════════════════╗\n"
76
- f"β•‘ βš™οΈ BOT SETTINGS β•‘\n"
77
- f"╠══════════════════════════════╣\n"
78
- f"β•‘ Workers : {config.WORKERS:<12} β•‘\n"
79
- f"β•‘ Batch size : {config.BATCH_SIZE:<12} β•‘\n"
80
- f"β•‘ Delay (s) : {config.DELAY_BETWEEN_REQUESTS:<12.1f} β•‘\n"
81
- f"β•‘ Min word len : {config.MIN_WORD_LEN:<12} β•‘\n"
82
- f"β•‘ Max word len : {config.MAX_WORD_LEN:<12} β•‘\n"
83
- f"β•‘ Max retries : {config.MAX_RETRIES:<12} β•‘\n"
84
- f"β•‘ Proxies : {len(config.PROXY_POOL):<4} loaded β•‘\n"
85
- f"β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•"
86
- )
87
 
88
  def build_settings_keyboard() -> InlineKeyboardMarkup:
89
- k = [
90
- [InlineKeyboardButton("βž• Workers", callback_data="cfg_inc_workers"), InlineKeyboardButton("βž– Workers", callback_data="cfg_dec_workers")],
91
- [InlineKeyboardButton("πŸ“‹ Batch +50", callback_data="cfg_inc_batch"), InlineKeyboardButton("πŸ“‹ Batch -50", callback_data="cfg_dec_batch")],
92
- [InlineKeyboardButton("⚑ Delay +", callback_data="cfg_inc_delay"), InlineKeyboardButton("⚑ Delay -", callback_data="cfg_dec_delay")],
93
- [InlineKeyboardButton("πŸ” Retry +1", callback_data="cfg_inc_retry"), InlineKeyboardButton("πŸ” Retry -1", callback_data="cfg_dec_retry")],
94
- [InlineKeyboardButton("πŸ“ Min +1", callback_data="cfg_inc_minlen"), InlineKeyboardButton("πŸ“ Min -1", callback_data="cfg_dec_minlen")],
95
- [InlineKeyboardButton("πŸ“ Max +1", callback_data="cfg_inc_maxlen"), InlineKeyboardButton("πŸ“ Max -1", callback_data="cfg_dec_maxlen")],
96
- [InlineKeyboardButton("πŸ”„ Reset Defaults", callback_data="cfg_reset"), InlineKeyboardButton("❌ Close", callback_data="cfg_close")]
97
- ]
98
- return InlineKeyboardMarkup(k)
99
-
100
- # ── Commands ───────────────────────────────────────────────────────────────
101
-
102
- @admin_only
103
- async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
104
- k = [
105
- [InlineKeyboardButton("πŸ” Scan", callback_data="cmd_scan"), InlineKeyboardButton("⏹ Stop", callback_data="cmd_stop"), InlineKeyboardButton("πŸ“Š Status", callback_data="cmd_status")],
106
- [InlineKeyboardButton("πŸ“¦ Stats", callback_data="cmd_stats"), InlineKeyboardButton("πŸ“‹ Available", callback_data="cmd_available"), InlineKeyboardButton("πŸ“€ Export", callback_data="cmd_export")],
107
- [InlineKeyboardButton("βš™οΈ Settings", callback_data="cmd_settings"), InlineKeyboardButton("πŸ”Œ Proxies", callback_data="cmd_proxies"), InlineKeyboardButton("πŸ“œ Jobs", callback_data="cmd_jobs")]
108
- ]
109
- await update.message.reply_text("<b>Fragment Username Scanner</b>\nSelect a command:", reply_markup=InlineKeyboardMarkup(k), parse_mode="HTML")
110
-
111
- @admin_only
112
- async def cmd_scan(update: Update, context: ContextTypes.DEFAULT_TYPE):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  if job.is_running():
114
- await update.message.reply_text("⚠️ A scan is already running. Use /stop first.")
115
  return
116
 
117
- msg = await update.message.reply_text("⏳ Fetching word list & checking DB...")
 
 
 
 
 
 
 
 
 
118
 
119
- try:
120
- full_list = await fetch_word_list()
121
- completed = await database.get_completed_words()
122
- words_to_scan = [w for w in full_list if w not in completed]
123
 
124
- if not words_to_scan:
125
- await msg.edit_text("βœ… All words already scanned. Use /stats to view results.")
126
- return
 
 
 
 
 
 
 
 
 
 
 
127
 
128
- job_id = uuid.uuid4().hex[:8]
 
 
 
129
 
130
- await database.save_job(job_id, {
131
- "total_words": len(words_to_scan),
132
- "completed_words": 0,
133
- "status": "running",
134
- "started_at": datetime.now(timezone.utc).isoformat(),
135
- "finished_at": "",
136
- "owner_id": str(update.effective_user.id),
137
- })
138
-
139
- async def progress_callback(completed_count, total_count, batch_results):
140
- await database.push_batch(batch_results)
141
- await database.update_job_progress(job_id, completed_count)
142
- job.completed_words = completed_count
143
-
144
- avail_count = sum(1 for r in batch_results if r["Status"] not in ["Taken", "Unavailable", "BLOCKED: Max Retries Hit"])
145
- context.user_data["avail_session_count"] = context.user_data.get("avail_session_count", 0) + avail_count
146
-
147
- card = build_progress_card(
148
- job_id, completed_count, total_count, job.get_elapsed(), context.user_data["avail_session_count"]
149
  )
150
-
151
- if "progress_msg_id" in context.user_data:
152
- try:
153
- await context.bot.edit_message_text(
154
- f"<pre>{html.escape(card)}</pre>",
155
- chat_id=update.effective_chat.id,
156
- message_id=context.user_data["progress_msg_id"],
157
- parse_mode="HTML"
158
- )
159
- except TelegramError:
160
- pass
161
-
162
- # Cleanup callback
163
- def done_callback(t):
164
- if not t.cancelled():
165
- asyncio.create_task(database.finish_job(job_id, "completed"))
 
166
  job.reset()
167
 
168
- task = asyncio.create_task(scanner.run_scan(words_to_scan, job_id, job.stop_event, progress_callback))
169
- task.add_done_callback(done_callback)
170
- job.start(task, job_id, len(words_to_scan))
171
- context.user_data["avail_session_count"] = 0
172
 
173
- card = build_progress_card(job_id, 0, len(words_to_scan), "00:00:00", 0)
174
- sent = await msg.edit_text(f"<pre>{html.escape(card)}</pre>", parse_mode="HTML")
175
- context.user_data["progress_msg_id"] = sent.message_id
176
-
177
- except Exception as e:
178
- await msg.edit_text(f"❌ Error starting scan: {html.escape(str(e))}")
179
-
180
- @admin_only
181
- async def cmd_stop(update: Update, context: ContextTypes.DEFAULT_TYPE):
182
  if not job.is_running():
183
- await update.message.reply_text("No active scan.")
184
  return
185
 
186
- job_id = job.current_job_id
187
  completed = job.completed_words
188
  total = job.total_words
 
189
  job.stop()
190
- if job_id:
191
- await database.finish_job(job_id, "stopped")
192
 
193
- await update.message.reply_text(
194
- f"⏹ Scan stopped.\nJob: {job_id}\nCompleted: {completed:,} / {total:,} words"
195
- )
196
 
197
- @admin_only
198
- async def cmd_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
199
- if not job.is_running():
 
 
 
 
 
200
  recent = await database.get_recent_jobs(1)
201
  if recent:
202
  j = recent[0]
203
- await update.message.reply_text(f"No active scan.\nLast job: {j.get('id')} ({j.get('status')})")
204
  else:
205
- await update.message.reply_text("No scan has been run yet.")
206
- return
207
-
208
- card = build_progress_card(job.current_job_id, job.completed_words, job.total_words, job.get_elapsed(), context.user_data.get("avail_session_count", 0))
209
- sent = await update.message.reply_text(f"<pre>{html.escape(card)}</pre>", parse_mode="HTML")
210
- context.user_data["progress_msg_id"] = sent.message_id
211
 
212
- @admin_only
213
- async def cmd_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
214
  stats = await database.get_stats()
215
- card = build_stats_card(stats)
216
- await update.message.reply_text(f"<pre>{html.escape(card)}</pre>", parse_mode="HTML")
217
 
218
- @admin_only
219
- async def cmd_available(update: Update, context: ContextTypes.DEFAULT_TYPE):
220
  rows = await database.get_available()
 
 
 
 
 
 
 
 
 
221
  if not rows:
222
- await update.message.reply_text("No available usernames found yet.")
223
  return
224
 
225
  if len(rows) <= 50:
226
- lines = [f"@{html.escape(r['username'])} β€” {html.escape(r.get('status', ''))}" for r in rows]
227
- await update.message.reply_text("\n".join(lines), parse_mode="HTML")
228
  else:
229
  df = pd.DataFrame(rows)
230
- csv_buf = io.BytesIO()
231
- df.to_csv(csv_buf, index=False)
232
- csv_buf.seek(0)
233
- filename = f"available_{datetime.now().strftime('%Y-%m-%d')}.csv"
234
- await update.message.reply_document(document=csv_buf, filename=filename)
235
-
236
- @admin_only
237
- async def cmd_export(update: Update, context: ContextTypes.DEFAULT_TYPE):
238
- msg = await update.message.reply_text("⏳ Generating export...")
239
  rows = await database.export_all()
240
  if not rows:
241
- await msg.edit_text("Database is empty.")
242
  return
243
-
244
  df = pd.DataFrame(rows)
245
- csv_buf = io.BytesIO()
246
- df.to_csv(csv_buf, index=False)
247
- csv_buf.seek(0)
 
 
 
 
 
 
 
 
248
 
249
- filename = f"Fragment_DB_{datetime.now().strftime('%Y-%m-%d')}.csv"
250
- await update.message.reply_document(document=csv_buf, filename=filename)
251
- await msg.delete()
252
- await update.message.reply_text(f"πŸ“€ Exported {len(rows):,} records.")
253
-
254
- @admin_only
255
- async def cmd_jobs(update: Update, context: ContextTypes.DEFAULT_TYPE):
256
- jobs = await database.get_recent_jobs(5)
257
  if not jobs:
258
- await update.message.reply_text("No recent jobs.")
259
  return
260
 
261
  lines = []
262
  for j in jobs:
263
- d = j.get('started_at', '')[:10]
264
- lines.append(f"Job {j.get('id')} | {j.get('status')} | {j.get('completed_words')}/{j.get('total_words')} | {d}")
265
-
266
- await update.message.reply_text("\n".join(lines))
267
 
268
- @admin_only
269
- async def cmd_settings(update: Update, context: ContextTypes.DEFAULT_TYPE):
270
- await update.message.reply_text(
271
- f"<pre>{html.escape(build_settings_text())}</pre>",
272
  reply_markup=build_settings_keyboard(),
273
- parse_mode="HTML"
274
  )
275
 
276
- @admin_only
277
- async def cmd_proxies(update: Update, context: ContextTypes.DEFAULT_TYPE):
278
- args = context.args
279
  if not args:
280
- await update.message.reply_text(f"Use: /proxies [list|add <str>|clear]\nCurrent: {len(config.PROXY_POOL)} loaded.")
281
  return
282
-
283
  sub = args[0].lower()
284
  if sub == "list":
285
- px = await database.get_proxies()
286
- await update.message.reply_text("\n".join(px) if px else "No proxies.")
287
- elif sub == "add" and len(args) > 1:
288
- px = args[1]
289
- config.PROXY_POOL.append(px)
290
- await database.set_proxies(config.PROXY_POOL)
291
- await update.message.reply_text(f"Added. Total: {len(config.PROXY_POOL)}")
 
 
 
 
 
 
 
 
 
 
 
292
  elif sub == "clear":
293
- config.PROXY_POOL.clear()
294
  await database.set_proxies([])
295
- await update.message.reply_text("Proxies cleared.")
296
-
297
- @admin_only
298
- async def cmd_ping(update: Update, context: ContextTypes.DEFAULT_TYPE):
 
 
 
 
 
 
 
 
 
 
 
 
299
  db_ok = await database.ping_db()
300
- up = round(time.time() - keep_alive.START_TIME, 1)
301
  status = "🟒 Redis: connected" if db_ok else "πŸ”΄ Redis: unreachable"
302
- await update.message.reply_text(f"{status}\nUptime: {up}s")
 
 
303
 
304
- # ── Callbacks ──────────────────────────────────────────────────────────────
305
-
306
- @admin_only
307
- async def cb_settings(update: Update, context: ContextTypes.DEFAULT_TYPE):
308
- query = update.callback_query
309
- action = query.data
310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  try:
312
- if action == "cfg_inc_workers":
313
- config.WORKERS = min(100, config.WORKERS + 1)
314
- elif action == "cfg_dec_workers":
315
- config.WORKERS = max(1, config.WORKERS - 1)
316
- elif action == "cfg_inc_batch":
317
- config.BATCH_SIZE = min(1000, config.BATCH_SIZE + 50)
318
- elif action == "cfg_dec_batch":
319
- config.BATCH_SIZE = max(50, config.BATCH_SIZE - 50)
320
- elif action == "cfg_inc_delay":
321
- config.DELAY_BETWEEN_REQUESTS = min(5.0, round(config.DELAY_BETWEEN_REQUESTS + 0.1, 1))
322
- elif action == "cfg_dec_delay":
323
- config.DELAY_BETWEEN_REQUESTS = max(0.1, round(config.DELAY_BETWEEN_REQUESTS - 0.1, 1))
324
- elif action == "cfg_inc_retry":
325
- config.MAX_RETRIES = min(10, config.MAX_RETRIES + 1)
326
- elif action == "cfg_dec_retry":
327
- config.MAX_RETRIES = max(1, config.MAX_RETRIES - 1)
328
- elif action == "cfg_inc_minlen":
329
- config.MIN_WORD_LEN = min(config.MAX_WORD_LEN - 1, config.MIN_WORD_LEN + 1)
330
- elif action == "cfg_dec_minlen":
331
- config.MIN_WORD_LEN = max(3, config.MIN_WORD_LEN - 1)
332
- elif action == "cfg_inc_maxlen":
333
- config.MAX_WORD_LEN = min(32, config.MAX_WORD_LEN + 1)
334
- elif action == "cfg_dec_maxlen":
335
- config.MAX_WORD_LEN = max(config.MIN_WORD_LEN + 1, config.MAX_WORD_LEN - 1)
336
- elif action == "cfg_reset":
337
- config.WORKERS = 35
338
- config.DELAY_BETWEEN_REQUESTS = 0.5
339
- config.MAX_RETRIES = 3
340
- config.BATCH_SIZE = 250
341
- config.MIN_WORD_LEN = 5
342
- config.MAX_WORD_LEN = 12
343
- elif action == "cfg_close":
344
- await query.answer()
345
- await query.delete_message()
346
- return
347
-
348
- # Save to DB
349
- await database.save_runtime_config({
350
- "workers": config.WORKERS,
351
- "batch_size": config.BATCH_SIZE,
352
- "delay": config.DELAY_BETWEEN_REQUESTS,
353
- "min_len": config.MIN_WORD_LEN,
354
- "max_len": config.MAX_WORD_LEN,
355
- "retries": config.MAX_RETRIES
356
- })
357
-
358
- await query.answer()
359
- await query.edit_message_text(
360
- f"<pre>{html.escape(build_settings_text())}</pre>",
361
  reply_markup=build_settings_keyboard(),
362
- parse_mode="HTML"
363
  )
364
- except telegram.error.TelegramError:
365
- await query.answer("Error updating settings.")
366
- except Exception:
367
- await query.answer()
368
-
369
- @admin_only
370
- async def cb_start_menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
371
- query = update.callback_query
372
- await query.answer()
373
-
374
- cmd_map = {
375
- "cmd_scan": cmd_scan,
376
- "cmd_stop": cmd_stop,
377
- "cmd_status": cmd_status,
378
- "cmd_stats": cmd_stats,
379
- "cmd_available": cmd_available,
380
- "cmd_export": cmd_export,
381
- "cmd_settings": cmd_settings,
382
- "cmd_proxies": cmd_proxies,
383
- "cmd_jobs": cmd_jobs
384
- }
385
- func = cmd_map.get(query.data)
386
- if func:
387
- # Pass the original update down; works for simple commands
388
- await func(update, context)
389
-
390
- # ── Entry ──────────────────────────────────────────────────────────────────
391
-
392
- async def run_bot():
393
- if not config.TELEGRAM_BOT_TOKEN:
394
- print("TELEGRAM_BOT_TOKEN missing.")
395
  return
 
 
 
 
396
 
 
 
 
397
  try:
398
- db_cfg = await database.load_runtime_config()
399
- if db_cfg:
400
- if "workers" in db_cfg: config.WORKERS = int(db_cfg["workers"])
401
- if "batch_size" in db_cfg: config.BATCH_SIZE = int(db_cfg["batch_size"])
402
- if "delay" in db_cfg: config.DELAY_BETWEEN_REQUESTS = float(db_cfg["delay"])
403
- if "min_len" in db_cfg: config.MIN_WORD_LEN = int(db_cfg["min_len"])
404
- if "max_len" in db_cfg: config.MAX_WORD_LEN = int(db_cfg["max_len"])
405
- if "retries" in db_cfg: config.MAX_RETRIES = int(db_cfg["retries"])
 
406
  config.PROXY_POOL = await database.get_proxies()
407
  except Exception as e:
408
- print(f"Failed to load config from Redis: {e}")
409
-
410
- app = Application.builder().token(config.TELEGRAM_BOT_TOKEN).build()
411
-
412
- app.add_handler(CommandHandler("start", cmd_start))
413
- app.add_handler(CommandHandler("scan", cmd_scan))
414
- app.add_handler(CommandHandler("resume", cmd_scan))
415
- app.add_handler(CommandHandler("stop", cmd_stop))
416
- app.add_handler(CommandHandler("status", cmd_status))
417
- app.add_handler(CommandHandler("stats", cmd_stats))
418
- app.add_handler(CommandHandler("available", cmd_available))
419
- app.add_handler(CommandHandler("export", cmd_export))
420
- app.add_handler(CommandHandler("jobs", cmd_jobs))
421
- app.add_handler(CommandHandler("settings", cmd_settings))
422
- app.add_handler(CommandHandler("proxies", cmd_proxies))
423
- app.add_handler(CommandHandler("ping", cmd_ping))
424
-
425
- app.add_handler(CallbackQueryHandler(cb_settings, pattern=r"^cfg_"))
426
- app.add_handler(CallbackQueryHandler(cb_start_menu, pattern=r"^cmd_"))
427
 
428
- await app.initialize()
429
  await app.start()
430
- await app.updater.start_polling(drop_pending_updates=True)
431
- print("Telegram Bot Polling Started.")
432
-
433
- await asyncio.Event().wait()
 
1
+ # ════════════════════════════════════════
2
+ # FILE: bot.py
3
+ # ════════════════════════════════════════
4
+
5
  import asyncio
6
+ from uuid import uuid4
 
 
 
7
  from datetime import datetime, timezone
8
+ import io
9
  import pandas as pd
10
 
11
+ from pyrogram import Client, filters, enums
12
+ from pyrogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
13
+ from pyrogram.errors import MessageNotModified
14
 
15
  import config
16
  import database
 
 
17
  from job_state import job
18
+ import scanner
19
+ import wordlist
20
 
21
+ # ── Admin filter ─────────────────────────────────────────────────────────────
22
 
23
+ admin_filter = filters.create(
24
+ lambda _, __, m: (m.from_user.id if m.from_user else 0) in config.ADMIN_USER_IDS
25
+ )
 
 
 
 
26
 
27
+ def auth_cmd():
28
+ return filters.command & filters.private & admin_filter
29
 
30
+ # ── Card builders ─────────────────────────────────────────────────────────────
31
+
32
+ def build_progress_card(job_id: str, completed: int, total: int, bar: str, pct: float, elapsed: str, avail: int) -> str:
33
+ return f"""```
34
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
35
+ β”‚ πŸ“Š SCAN PROGRESS β”‚
36
+ β”‚ Job : {job_id:<20}β”‚
37
+ β”‚ {bar} {pct:5.1f}% β”‚
38
+ β”‚ Done: {completed:,}/{total:,}
39
+ β”‚ Found: {avail:<18} β”‚
40
+ β”‚ Time: {elapsed:<20} β”‚
41
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
42
+ ```"""
 
 
 
 
 
 
43
 
44
  def build_stats_card(stats: dict) -> str:
45
+ lines = [f"β”‚ {k:<14}: {v:>8,} β”‚" for k, v in stats.items()]
46
+ rows = "\n".join(lines)
47
+ return f"""```
48
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
49
+ β”‚ πŸ“¦ DATABASE STATS β”‚
50
+ {rows}
51
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
52
+ ```"""
 
 
 
 
 
 
 
 
 
 
 
53
 
54
  def build_settings_text() -> str:
55
+ return f"""```
56
+ ╔══════════════════════════════╗
57
+ β•‘ βš™οΈ BOT SETTINGS β•‘
58
+ ╠══════════════════════════════╣
59
+ β•‘ Workers : {config.WORKERS:<12} β•‘
60
+ β•‘ Batch size : {config.BATCH_SIZE:<12} β•‘
61
+ β•‘ Delay (s) : {config.DELAY_BETWEEN_REQUESTS:<12.1f} β•‘
62
+ β•‘ Min word len : {config.MIN_WORD_LEN:<12} β•‘
63
+ β•‘ Max word len : {config.MAX_WORD_LEN:<12} β•‘
64
+ β•‘ Max retries : {config.MAX_RETRIES:<12} β•‘
65
+ β•‘ Proxies : {len(config.PROXY_POOL):<6} loaded β•‘
66
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
67
+ ```"""
68
 
69
  def build_settings_keyboard() -> InlineKeyboardMarkup:
70
+ return InlineKeyboardMarkup([
71
+ [
72
+ InlineKeyboardButton("βž• Workers", callback_data="cfg_inc_workers"),
73
+ InlineKeyboardButton("βž– Workers", callback_data="cfg_dec_workers"),
74
+ InlineKeyboardButton("πŸ“‹ Batch +50", callback_data="cfg_inc_batch"),
75
+ InlineKeyboardButton("πŸ“‹ Batch -50", callback_data="cfg_dec_batch")
76
+ ],
77
+ [
78
+ InlineKeyboardButton("⚑ Delay +", callback_data="cfg_inc_delay"),
79
+ InlineKeyboardButton("⚑ Delay -", callback_data="cfg_dec_delay"),
80
+ InlineKeyboardButton("πŸ” Retry +1", callback_data="cfg_inc_retry"),
81
+ InlineKeyboardButton("πŸ” Retry -1", callback_data="cfg_dec_retry")
82
+ ],
83
+ [
84
+ InlineKeyboardButton("πŸ“ Min +1", callback_data="cfg_inc_minlen"),
85
+ InlineKeyboardButton("πŸ“ Min -1", callback_data="cfg_dec_minlen"),
86
+ InlineKeyboardButton("πŸ“ Max +1", callback_data="cfg_inc_maxlen"),
87
+ InlineKeyboardButton("πŸ“ Max -1", callback_data="cfg_dec_maxlen")
88
+ ],
89
+ [
90
+ InlineKeyboardButton("πŸ”„ Reset Defaults", callback_data="cfg_reset"),
91
+ InlineKeyboardButton("❌ Close", callback_data="cfg_close")
92
+ ]
93
+ ])
94
+
95
+ # ── Commands ──────────────────────────────────────────────────────────────────
96
+
97
+ @Client.on_message(filters.command("start") & filters.private & admin_filter)
98
+ async def cmd_start(client: Client, message: Message):
99
+ kb = InlineKeyboardMarkup([
100
+ [
101
+ InlineKeyboardButton("πŸ” /scan", callback_data="cmd_scan"),
102
+ InlineKeyboardButton("⏹ /stop", callback_data="cmd_stop"),
103
+ InlineKeyboardButton("πŸ“Š /status", callback_data="cmd_status")
104
+ ],
105
+ [
106
+ InlineKeyboardButton("πŸ“¦ /stats", callback_data="cmd_stats"),
107
+ InlineKeyboardButton("πŸ“‹ /available", callback_data="cmd_available"),
108
+ InlineKeyboardButton("πŸ“€ /export", callback_data="cmd_export")
109
+ ],
110
+ [
111
+ InlineKeyboardButton("βš™οΈ /settings", callback_data="cmd_settings"),
112
+ InlineKeyboardButton("πŸ”Œ /proxies", callback_data="cmd_proxies"),
113
+ InlineKeyboardButton("πŸ“œ /jobs", callback_data="cmd_jobs")
114
+ ],
115
+ [
116
+ InlineKeyboardButton("πŸ“ /ping", callback_data="cmd_ping")
117
+ ]
118
+ ])
119
+ await message.reply("Welcome to Fragment Scanner Bot.", reply_markup=kb)
120
+
121
+ @Client.on_message(filters.command("scan") & filters.private & admin_filter)
122
+ async def cmd_scan(client: Client, message: Message):
123
  if job.is_running():
124
+ await message.reply("A scan is already running. Use /stop first.")
125
  return
126
 
127
+ words = []
128
+ if message.document and message.document.file_name.endswith('.txt'):
129
+ file_path = await message.download()
130
+ with open(file_path, 'r', encoding='utf-8') as f:
131
+ words = [line.strip().lower() for line in f if line.strip().isalpha()]
132
+ else:
133
+ words = await wordlist.fetch_word_list()
134
+
135
+ completed = await database.get_completed_words()
136
+ to_scan = [w for w in words if w not in completed]
137
 
138
+ if not to_scan:
139
+ await message.reply("All words scanned or empty list.")
140
+ return
 
141
 
142
+ job_id = uuid4().hex[:8]
143
+ await database.save_job(job_id, {
144
+ "total_words": len(to_scan),
145
+ "completed_words": 0,
146
+ "status": "running",
147
+ "started_at": datetime.now(timezone.utc).isoformat(),
148
+ "finished_at": "",
149
+ "owner_id": str(message.from_user.id)
150
+ })
151
+
152
+ progress_msg = await message.reply(
153
+ build_progress_card(job_id, 0, len(to_scan), job.get_bar(), 0.0, "00:00:00", 0),
154
+ parse_mode=enums.ParseMode.MARKDOWN
155
+ )
156
 
157
+ async def progress_callback(completed_count, total_count, batch):
158
+ await database.push_batch(batch)
159
+ await database.update_job_progress(job_id, completed_count)
160
+ job.completed_words = completed_count
161
 
162
+ avail = sum(1 for r in batch if r.get("Status") == "Available")
163
+
164
+ try:
165
+ await progress_msg.edit_text(
166
+ build_progress_card(job_id, completed_count, total_count, job.get_bar(), job.pct(), job.get_elapsed(), avail),
167
+ parse_mode=enums.ParseMode.MARKDOWN
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  )
169
+ except MessageNotModified:
170
+ pass
171
+ except Exception:
172
+ pass
173
+
174
+ async def _on_scan_done(task_future, j_id, cli):
175
+ try:
176
+ task_future.result()
177
+ await database.finish_job(j_id, "completed")
178
+ stats = await database.get_stats()
179
+ await cli.send_message(message.chat.id, build_stats_card(stats), parse_mode=enums.ParseMode.MARKDOWN)
180
+ except asyncio.CancelledError:
181
+ await database.finish_job(j_id, "stopped")
182
+ except Exception as e:
183
+ await database.finish_job(j_id, "error")
184
+ await cli.send_message(message.chat.id, f"Scan error: {e}")
185
+ finally:
186
  job.reset()
187
 
188
+ task = asyncio.create_task(scanner.run_scan(to_scan, job_id, job.stop_event, progress_callback))
189
+ task.add_done_callback(lambda t: asyncio.create_task(_on_scan_done(t, job_id, client)))
190
+ job.start(task, job_id, len(to_scan))
 
191
 
192
+ @Client.on_message(filters.command("stop") & filters.private & admin_filter)
193
+ async def cmd_stop(client: Client, message: Message):
 
 
 
 
 
 
 
194
  if not job.is_running():
195
+ await message.reply("No active scan.")
196
  return
197
 
198
+ current_job = job.current_job_id
199
  completed = job.completed_words
200
  total = job.total_words
201
+
202
  job.stop()
203
+ if current_job:
204
+ await database.finish_job(current_job, "stopped")
205
 
206
+ await message.reply(f"Job {current_job} stopped. {completed}/{total} words scanned.")
 
 
207
 
208
+ @Client.on_message(filters.command("status") & filters.private & admin_filter)
209
+ async def cmd_status(client: Client, message: Message):
210
+ if job.is_running():
211
+ await message.reply(
212
+ build_progress_card(job.current_job_id, job.completed_words, job.total_words, job.get_bar(), job.pct(), job.get_elapsed(), "N/A"),
213
+ parse_mode=enums.ParseMode.MARKDOWN
214
+ )
215
+ else:
216
  recent = await database.get_recent_jobs(1)
217
  if recent:
218
  j = recent[0]
219
+ await message.reply(f"Last Job: {j.get('job_id')} | {j.get('status')} | {j.get('completed_words')}/{j.get('total_words')}")
220
  else:
221
+ await message.reply("No scan run yet.")
 
 
 
 
 
222
 
223
+ @Client.on_message(filters.command("stats") & filters.private & admin_filter)
224
+ async def cmd_stats(client: Client, message: Message):
225
  stats = await database.get_stats()
226
+ await message.reply(build_stats_card(stats), parse_mode=enums.ParseMode.MARKDOWN)
 
227
 
228
+ @Client.on_message(filters.command("available") & filters.private & admin_filter)
229
+ async def cmd_available(client: Client, message: Message):
230
  rows = await database.get_available()
231
+
232
+ if len(message.command) >= 3:
233
+ try:
234
+ min_l = int(message.command[1])
235
+ max_l = int(message.command[2])
236
+ rows = [r for r in rows if min_l <= len(r.get("username", "")) <= max_l]
237
+ except ValueError:
238
+ pass
239
+
240
  if not rows:
241
+ await message.reply("No available usernames yet.")
242
  return
243
 
244
  if len(rows) <= 50:
245
+ lines = [f"@{r.get('username')} β€” {r.get('status')} β€” {r.get('timestamp', '')[:10]}" for r in rows]
246
+ await message.reply("\n".join(lines))
247
  else:
248
  df = pd.DataFrame(rows)
249
+ csv_buffer = io.BytesIO()
250
+ df.to_csv(csv_buffer, index=False)
251
+ csv_buffer.seek(0)
252
+ csv_buffer.name = f"available_{datetime.now().strftime('%Y%m%d')}.csv"
253
+ await message.reply_document(csv_buffer)
254
+
255
+ @Client.on_message(filters.command("export") & filters.private & admin_filter)
256
+ async def cmd_export(client: Client, message: Message):
 
257
  rows = await database.export_all()
258
  if not rows:
259
+ await message.reply("Database is empty.")
260
  return
261
+
262
  df = pd.DataFrame(rows)
263
+ csv_buffer = io.BytesIO()
264
+ df.to_csv(csv_buffer, index=False)
265
+ csv_buffer.seek(0)
266
+ csv_buffer.name = f"Fragment_DB_{datetime.now().strftime('%Y%m%d')}.csv"
267
+ await message.reply_document(csv_buffer, caption=f"πŸ“€ {len(rows):,} records exported.")
268
+
269
+ @Client.on_message(filters.command("jobs") & filters.private & admin_filter)
270
+ async def cmd_jobs(client: Client, message: Message):
271
+ n = 5
272
+ if len(message.command) > 1 and message.command[1].isdigit():
273
+ n = int(message.command[1])
274
 
275
+ jobs = await database.get_recent_jobs(n)
 
 
 
 
 
 
 
276
  if not jobs:
277
+ await message.reply("No recent jobs.")
278
  return
279
 
280
  lines = []
281
  for j in jobs:
282
+ lines.append(f"Job {j.get('job_id')} | {j.get('status')} | {j.get('completed_words')}/{j.get('total_words')} | {j.get('started_at', '')[:10]}")
283
+ await message.reply("\n".join(lines))
 
 
284
 
285
+ @Client.on_message(filters.command("settings") & filters.private & admin_filter)
286
+ async def cmd_settings(client: Client, message: Message):
287
+ await message.reply(
288
+ build_settings_text(),
289
  reply_markup=build_settings_keyboard(),
290
+ parse_mode=enums.ParseMode.MARKDOWN
291
  )
292
 
293
+ @Client.on_message(filters.command("proxies") & filters.private & admin_filter)
294
+ async def cmd_proxies(client: Client, message: Message):
295
+ args = message.command[1:]
296
  if not args:
297
+ await message.reply("Usage: /proxies list | add <str> | clear | load (with .txt attachment)")
298
  return
299
+
300
  sub = args[0].lower()
301
  if sub == "list":
302
+ proxies = await database.get_proxies()
303
+ if not proxies:
304
+ await message.reply("Proxy list is empty.")
305
+ return
306
+ lines = [f"{i+1}. {p}" for i, p in enumerate(proxies)]
307
+ await message.reply("\n".join(lines))
308
+
309
+ elif sub == "add":
310
+ if len(args) < 2:
311
+ await message.reply("Provide a proxy string.")
312
+ return
313
+ p_str = args[1]
314
+ proxies = await database.get_proxies()
315
+ proxies.append(p_str)
316
+ await database.set_proxies(proxies)
317
+ config.PROXY_POOL = proxies
318
+ await message.reply(f"Proxy added. Total: {len(proxies)}")
319
+
320
  elif sub == "clear":
 
321
  await database.set_proxies([])
322
+ config.PROXY_POOL = []
323
+ await message.reply("Proxies cleared.")
324
+
325
+ elif sub == "load":
326
+ if not message.document:
327
+ await message.reply("Please attach a .txt document for load.")
328
+ return
329
+ file_path = await message.download()
330
+ with open(file_path, 'r', encoding='utf-8') as f:
331
+ new_proxies = [line.strip() for line in f if line.strip()]
332
+ await database.set_proxies(new_proxies)
333
+ config.PROXY_POOL = new_proxies
334
+ await message.reply(f"Loaded {len(new_proxies)} proxies.")
335
+
336
+ @Client.on_message(filters.command("ping") & filters.private & admin_filter)
337
+ async def cmd_ping(client: Client, message: Message):
338
  db_ok = await database.ping_db()
 
339
  status = "🟒 Redis: connected" if db_ok else "πŸ”΄ Redis: unreachable"
340
+ from keep_alive import get_uptime
341
+ uptime = get_uptime()
342
+ await message.reply(f"{status}\nUptime: {uptime}")
343
 
344
+ # ── Callback: cfg_ ────────────────────────────────────────────────────────────
 
 
 
 
 
345
 
346
+ @Client.on_callback_query(filters.regex(r"^cfg_"))
347
+ async def cb_settings(client: Client, query: CallbackQuery):
348
+ if query.from_user.id not in config.ADMIN_USER_IDS:
349
+ await query.answer("Unauthorized.", show_alert=True)
350
+ return
351
+
352
+ await query.answer()
353
+
354
+ data = query.data
355
+ if data == "cfg_close":
356
+ await query.message.delete()
357
+ return
358
+
359
+ if data == "cfg_reset":
360
+ config.WORKERS = 35
361
+ config.BATCH_SIZE = 250
362
+ config.DELAY_BETWEEN_REQUESTS = 0.5
363
+ config.MAX_RETRIES = 3
364
+ config.MIN_WORD_LEN = 5
365
+ config.MAX_WORD_LEN = 12
366
+ else:
367
+ parts = data[4:].split("_", 1)
368
+ if len(parts) == 2:
369
+ action, param = parts
370
+
371
+ BOUNDS = {
372
+ "workers": (1, 100, 1),
373
+ "batch": (50, 1000, 50),
374
+ "delay": (0.1, 5.0, 0.1),
375
+ "retry": (1, 10, 1),
376
+ "minlen": (3, config.MAX_WORD_LEN - 1, 1),
377
+ "maxlen": (config.MIN_WORD_LEN + 1, 32, 1),
378
+ }
379
+ ATTR_MAP = {
380
+ "workers": "WORKERS",
381
+ "batch": "BATCH_SIZE",
382
+ "delay": "DELAY_BETWEEN_REQUESTS",
383
+ "retry": "MAX_RETRIES",
384
+ "minlen": "MIN_WORD_LEN",
385
+ "maxlen": "MAX_WORD_LEN"
386
+ }
387
+
388
+ if param in BOUNDS and param in ATTR_MAP:
389
+ lo, hi, step = BOUNDS[param]
390
+ attr = ATTR_MAP[param]
391
+ cur = getattr(config, attr)
392
+
393
+ if action == "inc":
394
+ new_val = cur + step
395
+ else:
396
+ new_val = cur - step
397
+
398
+ new_val = max(lo, min(hi, new_val))
399
+ if param == "delay":
400
+ new_val = round(new_val, 1)
401
+
402
+ setattr(config, attr, new_val)
403
+
404
+ # fix overlapping min/max bounds dynamically
405
+ if param == "minlen":
406
+ config.MAX_WORD_LEN = max(config.MAX_WORD_LEN, config.MIN_WORD_LEN + 1)
407
+ elif param == "maxlen":
408
+ config.MIN_WORD_LEN = min(config.MIN_WORD_LEN, config.MAX_WORD_LEN - 1)
409
+
410
+ await database.save_runtime_config({
411
+ "workers": config.WORKERS,
412
+ "batch_size": config.BATCH_SIZE,
413
+ "delay": config.DELAY_BETWEEN_REQUESTS,
414
+ "min_len": config.MIN_WORD_LEN,
415
+ "max_len": config.MAX_WORD_LEN,
416
+ "retries": config.MAX_RETRIES
417
+ })
418
+
419
  try:
420
+ await query.message.edit_text(
421
+ build_settings_text(),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422
  reply_markup=build_settings_keyboard(),
423
+ parse_mode=enums.ParseMode.MARKDOWN
424
  )
425
+ except MessageNotModified:
426
+ pass
427
+
428
+ # ── Callback: cmd_ ────────────────────────────────────────────────────────────
429
+
430
+ @Client.on_callback_query(filters.regex(r"^cmd_"))
431
+ async def cb_menu(client: Client, query: CallbackQuery):
432
+ if query.from_user.id not in config.ADMIN_USER_IDS:
433
+ await query.answer("Unauthorized.", show_alert=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
  return
435
+
436
+ await query.answer()
437
+ cmd = query.data[4:]
438
+ await client.send_message(query.from_user.id, f"/{cmd}")
439
 
440
+ # ── run_bot ───────────────────────────────────────────────────────────────────
441
+
442
+ async def run_bot(app: Client):
443
  try:
444
+ loaded_cfg = await database.load_runtime_config()
445
+ if loaded_cfg:
446
+ setattr(config, "WORKERS", loaded_cfg.get("workers", config.WORKERS))
447
+ setattr(config, "BATCH_SIZE", loaded_cfg.get("batch_size", config.BATCH_SIZE))
448
+ setattr(config, "DELAY_BETWEEN_REQUESTS", loaded_cfg.get("delay", config.DELAY_BETWEEN_REQUESTS))
449
+ setattr(config, "MIN_WORD_LEN", loaded_cfg.get("min_len", config.MIN_WORD_LEN))
450
+ setattr(config, "MAX_WORD_LEN", loaded_cfg.get("max_len", config.MAX_WORD_LEN))
451
+ setattr(config, "MAX_RETRIES", loaded_cfg.get("retries", config.MAX_RETRIES))
452
+
453
  config.PROXY_POOL = await database.get_proxies()
454
  except Exception as e:
455
+ print(f"Failed to load config/proxies from Redis: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456
 
 
457
  await app.start()
458
+ print("Pyrogram bot started.")
459
+ await asyncio.Event().wait()