Muttered3 commited on
Commit
f144f7f
·
verified ·
1 Parent(s): 06bf70a

Delete bot.py

Browse files
Files changed (1) hide show
  1. bot.py +0 -459
bot.py DELETED
@@ -1,459 +0,0 @@
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()