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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|