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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import threading, telebot, subprocess, os, tempfile, shutil, requests, logging, sqlite3, psutil, time, re, sys, platform, uuid, hashlib, json, signal, zipfile, traceback, functools, random, string
|
| 2 |
+
from datetime import datetime, timedelta
|
| 3 |
+
from telebot import types
|
| 4 |
+
import telebot.apihelper
|
| 5 |
+
|
| 6 |
+
telebot.apihelper.ENABLE_MIDDLEWARE = False
|
| 7 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 8 |
+
logger = logging.getLogger("WhiteWolfUltimate")
|
| 9 |
+
|
| 10 |
+
TOKEN = '7847673598:AAGeqJb591uZWCwpSqS8VJGWTRtDOr0CTEE'
|
| 11 |
+
ADMIN_ID = 6812997550
|
| 12 |
+
OWNER_ID = 6812997550
|
| 13 |
+
YOUR_USERNAME = '@j49_c'
|
| 14 |
+
CHANNELS = ['@EQJ_1']
|
| 15 |
+
UPDATE_CHANNEL = 'https://t.me/EQJ_1'
|
| 16 |
+
BOT_NAME = 'White Wolf Hosting'
|
| 17 |
+
DEVELOPER = '@j49_c'
|
| 18 |
+
VERSION = '0.2'
|
| 19 |
+
|
| 20 |
+
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
|
| 21 |
+
HOSTING_DIR = os.path.join(BASE_DIR, 'wolf_hosting_cluster')
|
| 22 |
+
LOGS_DIR = os.path.join(BASE_DIR, 'wolf_logs')
|
| 23 |
+
BACKUP_DIR = os.path.join(BASE_DIR, 'wolf_backups')
|
| 24 |
+
PENDING_UPLOADS_DIR = os.path.join(BASE_DIR, 'pending_uploads')
|
| 25 |
+
IROTECH_DIR = os.path.join(BASE_DIR, 'wolf_data')
|
| 26 |
+
DATABASE_PATH = os.path.join(IROTECH_DIR, 'whitewolf_ultimate.db')
|
| 27 |
+
|
| 28 |
+
PLAN_LIMITS = {
|
| 29 |
+
'free': {'projects': 1, 'label': '๐ ู
ุฌุงูู', 'price': 0},
|
| 30 |
+
'silver': {'projects': 3, 'label': '๐ฅ ูุถู', 'price': 5},
|
| 31 |
+
'gold': {'projects': 5, 'label': '๐ฅ ุฐูุจู', 'price': 15},
|
| 32 |
+
'diamond': {'projects': 10, 'label': '๐ ู
ุงุณู', 'price': 40},
|
| 33 |
+
}
|
| 34 |
+
RATES = {'invite_reward': 1, 'plan_upgrade_silver': 5, 'plan_upgrade_gold': 15, 'plan_upgrade_diamond': 40}
|
| 35 |
+
MAX_FILE_SIZE_MB = 20
|
| 36 |
+
FILE_STATUS_PENDING = 'pending'
|
| 37 |
+
FILE_STATUS_APPROVED = 'approved'
|
| 38 |
+
FILE_STATUS_REJECTED = 'rejected'
|
| 39 |
+
|
| 40 |
+
MALWARE_SIGNATURES = [b'MZ', b'\x7fELF', b'\xfe\xed\xfa', b'\xce\xfa\xed\xfe', b'Rar!']
|
| 41 |
+
ENCRYPTED_FILE_INDICATORS = [b'openssl', b'encrypted', b'cipher', b'AES', b'DES', b'RSA', b'GPG', b'PGP']
|
| 42 |
+
SUSPICIOUS_KEYWORDS = [b'ransomware', b'trojan', b'virus', b'malware', b'backdoor', b'exploit', b'payload', b'botnet', b'keylogger', b'rootkit']
|
| 43 |
+
MALICIOUS_PYTHON_PATTERNS = [
|
| 44 |
+
r"os\.system\(", r"eval\(", r"exec\(", r"pickle\.load\(", r"marshal\.load\(",
|
| 45 |
+
r"shutil\.(rmtree|rm|move)\(.*root", r"import\s+ctypes", r"import\s+win32api",
|
| 46 |
+
r"sys\.exit\(", r"sys\.modules\.clear\(", r"subprocess\.Popen\(.*shell\s*=\s*True",
|
| 47 |
+
]
|
| 48 |
+
MALICIOUS_JAVASCRIPT_PATTERNS = [
|
| 49 |
+
r"require\s*\(\s*['\"]child_process['\"]\s*\)", r"eval\s*\(", r"new\s+Function\s*\(",
|
| 50 |
+
r"child_process\.(exec|spawn|fork|execSync|spawnSync)\(", r"fs\.(unlink|rm|rmSync|rmdir|rmdirSync).*root",
|
| 51 |
+
r"net\.(createServer|connect)\(",
|
| 52 |
+
]
|
| 53 |
+
TELEGRAM_MODULES = {
|
| 54 |
+
'telebot': 'pyTelegramBotAPI', 'telegram': 'python-telegram-bot', 'python_telegram_bot': 'python-telegram-bot',
|
| 55 |
+
'aiogram': 'aiogram', 'pyrogram': 'pyrogram', 'telethon': 'telethon', 'telethon.sync': 'telethon',
|
| 56 |
+
'telepot': 'telepot', 'pytg': 'pytg', 'tgcrypto': 'tgcrypto', 'telegram_upload': 'telegram-upload',
|
| 57 |
+
'telegram_send': 'telegram-send', 'bs4': 'beautifulsoup4', 'requests': 'requests', 'pillow': 'Pillow',
|
| 58 |
+
'cv2': 'opencv-python', 'yaml': 'PyYAML', 'dotenv': 'python-dotenv', 'dateutil': 'python-dateutil',
|
| 59 |
+
'pandas': 'pandas', 'numpy': 'numpy', 'flask': 'Flask', 'django': 'Django', 'sqlalchemy': 'SQLAlchemy',
|
| 60 |
+
'asyncio': None, 'json': None, 'datetime': None, 'os': None, 'sys': None, 're': None, 'time': None,
|
| 61 |
+
'math': None, 'random': None, 'logging': None, 'threading': None, 'subprocess': None, 'zipfile': None,
|
| 62 |
+
'tempfile': None, 'shutil': None, 'sqlite3': None, 'psutil': 'psutil', 'atexit': None, 'aiohttp': 'aiohttp',
|
| 63 |
+
'fastapi': 'fastapi', 'uvicorn': 'uvicorn', 'pydantic': 'pydantic', 'httpx': 'httpx', 'websockets': 'websockets',
|
| 64 |
+
'cryptography': 'cryptography', 'paramiko': 'paramiko', 'schedule': 'schedule', 'apscheduler': 'APScheduler',
|
| 65 |
+
'motor': 'motor', 'pymongo': 'pymongo', 'redis': 'redis', 'celery': 'celery', 'pika': 'pika', 'boto3': 'boto3',
|
| 66 |
+
'openai': 'openai', 'anthropic': 'anthropic', 'google': 'google-generativeai', 'PIL': 'Pillow', 'jwt': 'PyJWT',
|
| 67 |
+
'bcrypt': 'bcrypt', 'qrcode': 'qrcode', 'barcode': 'python-barcode',
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
for d in [HOSTING_DIR, LOGS_DIR, BACKUP_DIR, PENDING_UPLOADS_DIR, IROTECH_DIR]:
|
| 71 |
+
os.makedirs(d, exist_ok=True)
|
| 72 |
+
|
| 73 |
+
bot = telebot.TeleBot(TOKEN)
|
| 74 |
+
bot.skip_pending = True
|
| 75 |
+
|
| 76 |
+
maintenance_mode = False
|
| 77 |
+
spam_tracker = {}
|
| 78 |
+
user_states = {}
|
| 79 |
+
bot_processes = {}
|
| 80 |
+
project_start_times = {}
|
| 81 |
+
auto_restart_scripts = set()
|
| 82 |
+
|
| 83 |
+
class UltimateDatabase:
|
| 84 |
+
def __init__(self, db_path=DATABASE_PATH):
|
| 85 |
+
self.db_path = db_path
|
| 86 |
+
self.lock = threading.Lock()
|
| 87 |
+
self.init_db()
|
| 88 |
+
self.load_cache()
|
| 89 |
+
|
| 90 |
+
def get_conn(self):
|
| 91 |
+
conn = sqlite3.connect(self.db_path, check_same_thread=False)
|
| 92 |
+
conn.row_factory = sqlite3.Row
|
| 93 |
+
return conn
|
| 94 |
+
|
| 95 |
+
def init_db(self):
|
| 96 |
+
with self.get_conn() as conn:
|
| 97 |
+
c = conn.cursor()
|
| 98 |
+
c.execute('''CREATE TABLE IF NOT EXISTS users (
|
| 99 |
+
user_id INTEGER PRIMARY KEY, username TEXT, full_name TEXT, points INTEGER DEFAULT 0,
|
| 100 |
+
invited_by INTEGER, joined_at TIMESTAMP, is_banned INTEGER DEFAULT 0, ban_reason TEXT,
|
| 101 |
+
rewarded INTEGER DEFAULT 0, plan TEXT DEFAULT 'free', plan_expires TIMESTAMP, is_vip INTEGER DEFAULT 0,
|
| 102 |
+
total_invites INTEGER DEFAULT 0, notifications INTEGER DEFAULT 1, last_active TIMESTAMP)''')
|
| 103 |
+
c.execute('''CREATE TABLE IF NOT EXISTS projects (
|
| 104 |
+
project_id TEXT PRIMARY KEY, user_id INTEGER, file_name TEXT, file_type TEXT, path TEXT,
|
| 105 |
+
status TEXT DEFAULT 'pending', pid INTEGER, created_at TIMESTAMP, started_at TIMESTAMP,
|
| 106 |
+
stopped_at TIMESTAMP, auto_restart INTEGER DEFAULT 1, restart_count INTEGER DEFAULT 0,
|
| 107 |
+
notes TEXT, env_vars TEXT DEFAULT '{}', crash_count INTEGER DEFAULT 0)''')
|
| 108 |
+
c.execute('''CREATE TABLE IF NOT EXISTS coupons (
|
| 109 |
+
code TEXT PRIMARY KEY, type TEXT, value TEXT, max_uses INTEGER DEFAULT 1, used_count INTEGER DEFAULT 0,
|
| 110 |
+
created_at TIMESTAMP, expires_at TIMESTAMP, created_by INTEGER)''')
|
| 111 |
+
c.execute('''CREATE TABLE IF NOT EXISTS coupon_uses (
|
| 112 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT, code TEXT, user_id INTEGER, used_at TIMESTAMP)''')
|
| 113 |
+
c.execute('''CREATE TABLE IF NOT EXISTS activity_log (
|
| 114 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, action TEXT, details TEXT, timestamp TIMESTAMP)''')
|
| 115 |
+
c.execute('''CREATE TABLE IF NOT EXISTS project_logs (
|
| 116 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT, project_id TEXT, log_type TEXT, content TEXT, timestamp TIMESTAMP)''')
|
| 117 |
+
c.execute('''CREATE TABLE IF NOT EXISTS notifications (
|
| 118 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, message TEXT, is_read INTEGER DEFAULT 0, created_at TIMESTAMP)''')
|
| 119 |
+
c.execute('''CREATE TABLE IF NOT EXISTS config (key TEXT PRIMARY KEY, value TEXT)''')
|
| 120 |
+
c.execute('''CREATE TABLE IF NOT EXISTS templates (
|
| 121 |
+
template_id TEXT PRIMARY KEY, name TEXT, description TEXT, path TEXT, downloads INTEGER DEFAULT 0, created_at TIMESTAMP)''')
|
| 122 |
+
c.execute('''CREATE TABLE IF NOT EXISTS transactions (
|
| 123 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, type TEXT, amount INTEGER, description TEXT, timestamp TIMESTAMP)''')
|
| 124 |
+
c.execute('''CREATE TABLE IF NOT EXISTS admins (user_id INTEGER PRIMARY KEY)''')
|
| 125 |
+
c.execute('''CREATE TABLE IF NOT EXISTS banned_users (user_id INTEGER PRIMARY KEY, reason TEXT, ban_date TEXT)''')
|
| 126 |
+
c.execute('''CREATE TABLE IF NOT EXISTS user_env_vars (user_id INTEGER, var_name TEXT, var_value TEXT, PRIMARY KEY (user_id, var_name))''')
|
| 127 |
+
c.execute('''CREATE TABLE IF NOT EXISTS auto_restart (user_id INTEGER, file_name TEXT, PRIMARY KEY (user_id, file_name))''')
|
| 128 |
+
c.execute('INSERT OR IGNORE INTO admins (user_id) VALUES (?)', (ADMIN_ID,))
|
| 129 |
+
conn.commit()
|
| 130 |
+
|
| 131 |
+
def load_cache(self):
|
| 132 |
+
pass
|
| 133 |
+
|
| 134 |
+
def register_user(self, user_id, username, full_name=None, inviter=None):
|
| 135 |
+
with self.get_conn() as conn:
|
| 136 |
+
c = conn.cursor()
|
| 137 |
+
c.execute('''INSERT OR IGNORE INTO users (user_id, username, full_name, points, invited_by, joined_at, last_active)
|
| 138 |
+
VALUES (?, ?, ?, ?, ?, ?, ?)''', (user_id, username, full_name, 0, inviter, datetime.now(), datetime.now()))
|
| 139 |
+
c.execute('UPDATE users SET last_active = ? WHERE user_id = ?', (datetime.now(), user_id))
|
| 140 |
+
conn.commit()
|
| 141 |
+
|
| 142 |
+
def get_user(self, user_id):
|
| 143 |
+
with self.get_conn() as conn:
|
| 144 |
+
c = conn.cursor()
|
| 145 |
+
c.execute('SELECT * FROM users WHERE user_id = ?', (user_id,))
|
| 146 |
+
return c.fetchone()
|
| 147 |
+
|
| 148 |
+
def get_all_users(self):
|
| 149 |
+
with self.get_conn() as conn:
|
| 150 |
+
c = conn.cursor()
|
| 151 |
+
return c.execute('SELECT * FROM users ORDER BY joined_at DESC').fetchall()
|
| 152 |
+
|
| 153 |
+
def get_active_users(self, hours=24):
|
| 154 |
+
cutoff = datetime.now() - timedelta(hours=hours)
|
| 155 |
+
with self.get_conn() as conn:
|
| 156 |
+
c = conn.cursor()
|
| 157 |
+
return c.execute('SELECT * FROM users WHERE last_active > ?', (cutoff,)).fetchall()
|
| 158 |
+
|
| 159 |
+
def update_user_field(self, user_id, field, value):
|
| 160 |
+
with self.get_conn() as conn:
|
| 161 |
+
c = conn.cursor()
|
| 162 |
+
c.execute(f'UPDATE users SET {field} = ? WHERE user_id = ?', (value, user_id))
|
| 163 |
+
conn.commit()
|
| 164 |
+
|
| 165 |
+
def add_points(self, user_id, amount, description=''):
|
| 166 |
+
with self.get_conn() as conn:
|
| 167 |
+
c = conn.cursor()
|
| 168 |
+
c.execute('UPDATE users SET points = points + ? WHERE user_id = ?', (amount, user_id))
|
| 169 |
+
c.execute('INSERT INTO transactions (user_id, type, amount, description, timestamp) VALUES (?,?,?,?,?)',
|
| 170 |
+
(user_id, 'credit', amount, description, datetime.now()))
|
| 171 |
+
conn.commit()
|
| 172 |
+
|
| 173 |
+
def deduct_points(self, user_id, amount, description=''):
|
| 174 |
+
with self.get_conn() as conn:
|
| 175 |
+
c = conn.cursor()
|
| 176 |
+
c.execute('UPDATE users SET points = points - ? WHERE user_id = ?', (amount, user_id))
|
| 177 |
+
c.execute('INSERT INTO transactions (user_id, type, amount, description, timestamp) VALUES (?,?,?,?,?)',
|
| 178 |
+
(user_id, 'debit', amount, description, datetime.now()))
|
| 179 |
+
conn.commit()
|
| 180 |
+
|
| 181 |
+
def get_user_plan(self, user_id):
|
| 182 |
+
u = self.get_user(user_id)
|
| 183 |
+
if not u: return 'free'
|
| 184 |
+
if u['plan'] != 'free' and u['plan_expires']:
|
| 185 |
+
try:
|
| 186 |
+
if datetime.fromisoformat(str(u['plan_expires'])) < datetime.now():
|
| 187 |
+
self.update_user_field(user_id, 'plan', 'free')
|
| 188 |
+
return 'free'
|
| 189 |
+
except: pass
|
| 190 |
+
return u['plan'] or 'free'
|
| 191 |
+
|
| 192 |
+
def get_plan_limit(self, user_id):
|
| 193 |
+
if user_id == ADMIN_ID: return 999
|
| 194 |
+
u = self.get_user(user_id)
|
| 195 |
+
if u and u['is_vip']: return 999
|
| 196 |
+
return PLAN_LIMITS.get(self.get_user_plan(user_id), PLAN_LIMITS['free'])['projects']
|
| 197 |
+
|
| 198 |
+
def add_project(self, project_id, user_id, file_name, file_type, path, notes=''):
|
| 199 |
+
with self.get_conn() as conn:
|
| 200 |
+
c = conn.cursor()
|
| 201 |
+
c.execute('''INSERT INTO projects (project_id, user_id, file_name, file_type, path, status, created_at, notes, env_vars)
|
| 202 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)''', (project_id, user_id, file_name, file_type, path, 'pending', datetime.now(), notes, '{}'))
|
| 203 |
+
conn.commit()
|
| 204 |
+
|
| 205 |
+
def update_project_status(self, project_id, status, pid=None):
|
| 206 |
+
with self.get_conn() as conn:
|
| 207 |
+
c = conn.cursor()
|
| 208 |
+
now = datetime.now()
|
| 209 |
+
if status == 'running':
|
| 210 |
+
c.execute('UPDATE projects SET status = ?, pid = ?, started_at = ? WHERE project_id = ?', (status, pid, now, project_id))
|
| 211 |
+
elif status in ('stopped', 'crashed', 'pending'):
|
| 212 |
+
c.execute('UPDATE projects SET status = ?, pid = NULL, stopped_at = ? WHERE project_id = ?', (status, now, project_id))
|
| 213 |
+
else:
|
| 214 |
+
c.execute('UPDATE projects SET status = ?, pid = ? WHERE project_id = ?', (status, pid, project_id))
|
| 215 |
+
conn.commit()
|
| 216 |
+
|
| 217 |
+
def get_user_projects(self, user_id):
|
| 218 |
+
with self.get_conn() as conn:
|
| 219 |
+
c = conn.cursor()
|
| 220 |
+
return c.execute('SELECT * FROM projects WHERE user_id = ? ORDER BY created_at DESC', (user_id,)).fetchall()
|
| 221 |
+
|
| 222 |
+
def get_project(self, project_id):
|
| 223 |
+
with self.get_conn() as conn:
|
| 224 |
+
c = conn.cursor()
|
| 225 |
+
return c.execute('SELECT * FROM projects WHERE project_id = ?', (project_id,)).fetchone()
|
| 226 |
+
|
| 227 |
+
def delete_project(self, project_id):
|
| 228 |
+
with self.get_conn() as conn:
|
| 229 |
+
c = conn.cursor()
|
| 230 |
+
c.execute('DELETE FROM projects WHERE project_id = ?', (project_id,))
|
| 231 |
+
conn.commit()
|
| 232 |
+
|
| 233 |
+
def set_auto_restart(self, project_id, value):
|
| 234 |
+
with self.get_conn() as conn:
|
| 235 |
+
c = conn.cursor()
|
| 236 |
+
c.execute('UPDATE projects SET auto_restart = ? WHERE project_id = ?', (value, project_id))
|
| 237 |
+
conn.commit()
|
| 238 |
+
|
| 239 |
+
def add_project_log(self, project_id, log_type, content):
|
| 240 |
+
with self.get_conn() as conn:
|
| 241 |
+
c = conn.cursor()
|
| 242 |
+
c.execute('INSERT INTO project_logs (project_id, log_type, content, timestamp) VALUES (?, ?, ?, ?)',
|
| 243 |
+
(project_id, log_type, content[:2000], datetime.now()))
|
| 244 |
+
conn.commit()
|
| 245 |
+
|
| 246 |
+
def get_project_logs(self, project_id, limit=20):
|
| 247 |
+
with self.get_conn() as conn:
|
| 248 |
+
c = conn.cursor()
|
| 249 |
+
return c.execute('SELECT * FROM project_logs WHERE project_id = ? ORDER BY timestamp DESC LIMIT ?', (project_id, limit)).fetchall()
|
| 250 |
+
|
| 251 |
+
def clear_project_logs(self, project_id):
|
| 252 |
+
with self.get_conn() as conn:
|
| 253 |
+
c = conn.cursor()
|
| 254 |
+
c.execute('DELETE FROM project_logs WHERE project_id = ?', (project_id,))
|
| 255 |
+
conn.commit()
|
| 256 |
+
|
| 257 |
+
def set_project_env(self, project_id, env_dict):
|
| 258 |
+
with self.get_conn() as conn:
|
| 259 |
+
c = conn.cursor()
|
| 260 |
+
c.execute('UPDATE projects SET env_vars = ? WHERE project_id = ?', (json.dumps(env_dict), project_id))
|
| 261 |
+
conn.commit()
|
| 262 |
+
|
| 263 |
+
def save_env_var(self, user_id, var_name, var_value):
|
| 264 |
+
with self.get_conn() as conn:
|
| 265 |
+
c = conn.cursor()
|
| 266 |
+
c.execute('INSERT OR REPLACE INTO user_env_vars (user_id, var_name, var_value) VALUES (?, ?, ?)', (user_id, var_name, var_value))
|
| 267 |
+
conn.commit()
|
| 268 |
+
|
| 269 |
+
def get_user_env_vars(self, user_id):
|
| 270 |
+
with self.get_conn() as conn:
|
| 271 |
+
c = conn.cursor()
|
| 272 |
+
rows = c.execute('SELECT var_name, var_value FROM user_env_vars WHERE user_id = ?', (user_id,)).fetchall()
|
| 273 |
+
return {r['var_name']: r['var_value'] for r in rows}
|
| 274 |
+
|
| 275 |
+
def delete_env_var(self, user_id, var_name):
|
| 276 |
+
with self.get_conn() as conn:
|
| 277 |
+
c = conn.cursor()
|
| 278 |
+
c.execute('DELETE FROM user_env_vars WHERE user_id = ? AND var_name = ?', (user_id, var_name))
|
| 279 |
+
conn.commit()
|
| 280 |
+
|
| 281 |
+
def add_notification(self, user_id, message):
|
| 282 |
+
with self.get_conn() as conn:
|
| 283 |
+
c = conn.cursor()
|
| 284 |
+
c.execute('INSERT INTO notifications (user_id, message, created_at) VALUES (?, ?, ?)', (user_id, message, datetime.now()))
|
| 285 |
+
conn.commit()
|
| 286 |
+
|
| 287 |
+
def get_notifications(self, user_id, unread_only=False):
|
| 288 |
+
with self.get_conn() as conn:
|
| 289 |
+
c = conn.cursor()
|
| 290 |
+
if unread_only:
|
| 291 |
+
return c.execute('SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 10', (user_id,)).fetchall()
|
| 292 |
+
return c.execute('SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 20', (user_id,)).fetchall()
|
| 293 |
+
|
| 294 |
+
def mark_notifications_read(self, user_id):
|
| 295 |
+
with self.get_conn() as conn:
|
| 296 |
+
c = conn.cursor()
|
| 297 |
+
c.execute('UPDATE notifications SET is_read = 1 WHERE user_id = ?', (user_id,))
|
| 298 |
+
conn.commit()
|
| 299 |
+
|
| 300 |
+
def ban_user(self, user_id, reason=''):
|
| 301 |
+
with self.get_conn() as conn:
|
| 302 |
+
c = conn.cursor()
|
| 303 |
+
c.execute('UPDATE users SET is_banned = 1, ban_reason = ? WHERE user_id = ?', (reason, user_id))
|
| 304 |
+
c.execute('INSERT OR REPLACE INTO banned_users (user_id, reason, ban_date) VALUES (?, ?, ?)', (user_id, reason, datetime.now().isoformat()))
|
| 305 |
+
conn.commit()
|
| 306 |
+
|
| 307 |
+
def unban_user(self, user_id):
|
| 308 |
+
with self.get_conn() as conn:
|
| 309 |
+
c = conn.cursor()
|
| 310 |
+
c.execute('UPDATE users SET is_banned = 0, ban_reason = NULL WHERE user_id = ?', (user_id,))
|
| 311 |
+
c.execute('DELETE FROM banned_users WHERE user_id = ?', (user_id,))
|
| 312 |
+
conn.commit()
|
| 313 |
+
|
| 314 |
+
def is_banned(self, user_id):
|
| 315 |
+
u = self.get_user(user_id)
|
| 316 |
+
return u and u['is_banned'] == 1
|
| 317 |
+
|
| 318 |
+
def set_vip(self, user_id, status=1):
|
| 319 |
+
self.update_user_field(user_id, 'is_vip', status)
|
| 320 |
+
|
| 321 |
+
def set_plan(self, user_id, plan, days=30):
|
| 322 |
+
exp = datetime.now() + timedelta(days=days)
|
| 323 |
+
self.update_user_field(user_id, 'plan', plan)
|
| 324 |
+
with self.get_conn() as conn:
|
| 325 |
+
c = conn.cursor()
|
| 326 |
+
c.execute('UPDATE users SET plan_expires = ? WHERE user_id = ?', (exp, user_id))
|
| 327 |
+
conn.commit()
|
| 328 |
+
|
| 329 |
+
def add_coupon(self, code, ctype, value, max_uses, days_valid, created_by):
|
| 330 |
+
exp = datetime.now() + timedelta(days=days_valid)
|
| 331 |
+
with self.get_conn() as conn:
|
| 332 |
+
c = conn.cursor()
|
| 333 |
+
c.execute('''INSERT INTO coupons (code, type, value, max_uses, used_count, created_at, expires_at, created_by)
|
| 334 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''', (code.upper(), ctype, value, max_uses, 0, datetime.now(), exp, created_by))
|
| 335 |
+
conn.commit()
|
| 336 |
+
|
| 337 |
+
def use_coupon(self, code, user_id):
|
| 338 |
+
code = code.upper()
|
| 339 |
+
with self.get_conn() as conn:
|
| 340 |
+
c = conn.cursor()
|
| 341 |
+
c.execute('SELECT * FROM coupons WHERE code = ?', (code,))
|
| 342 |
+
cp = c.fetchone()
|
| 343 |
+
if not cp: return None, 'ููุฏ ุบูุฑ ุตุญูุญ'
|
| 344 |
+
if cp['used_count'] >= cp['max_uses']: return None, 'ุงุณุชูููุฏ'
|
| 345 |
+
try:
|
| 346 |
+
if datetime.fromisoformat(str(cp['expires_at'])) < datetime.now(): return None, 'ู
ูุชูู ุงูุตูุงุญูุฉ'
|
| 347 |
+
except: pass
|
| 348 |
+
c.execute('SELECT * FROM coupon_uses WHERE code = ? AND user_id = ?', (code, user_id))
|
| 349 |
+
if c.fetchone(): return None, 'ู
ุณุชุฎุฏู
ู
ุณุจูุงู'
|
| 350 |
+
c.execute('UPDATE coupons SET used_count = used_count + 1 WHERE code = ?', (code,))
|
| 351 |
+
c.execute('INSERT INTO coupon_uses (code, user_id, used_at) VALUES (?, ?, ?)', (code, user_id, datetime.now()))
|
| 352 |
+
conn.commit()
|
| 353 |
+
return cp, None
|
| 354 |
+
|
| 355 |
+
def get_stats(self):
|
| 356 |
+
with self.get_conn() as conn:
|
| 357 |
+
c = conn.cursor()
|
| 358 |
+
return {
|
| 359 |
+
'total_users': c.execute('SELECT COUNT(*) FROM users').fetchone()[0],
|
| 360 |
+
'banned_users': c.execute('SELECT COUNT(*) FROM users WHERE is_banned = 1').fetchone()[0],
|
| 361 |
+
'vip_users': c.execute('SELECT COUNT(*) FROM users WHERE is_vip = 1').fetchone()[0],
|
| 362 |
+
'total_projects': c.execute('SELECT COUNT(*) FROM projects').fetchone()[0],
|
| 363 |
+
'running_projects': c.execute("SELECT COUNT(*) FROM projects WHERE status = 'running'").fetchone()[0],
|
| 364 |
+
'pending_projects': c.execute("SELECT COUNT(*) FROM projects WHERE status = 'pending'").fetchone()[0],
|
| 365 |
+
'total_coupons': c.execute('SELECT COUNT(*) FROM coupons').fetchone()[0],
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
def add_activity(self, user_id, action, details=''):
|
| 369 |
+
with self.get_conn() as conn:
|
| 370 |
+
c = conn.cursor()
|
| 371 |
+
c.execute('INSERT INTO activity_log (user_id, action, details, timestamp) VALUES (?, ?, ?, ?)',
|
| 372 |
+
(user_id, action, details, datetime.now()))
|
| 373 |
+
conn.commit()
|
| 374 |
+
|
| 375 |
+
def get_config(self, key, default=None):
|
| 376 |
+
with self.get_conn() as conn:
|
| 377 |
+
c = conn.cursor()
|
| 378 |
+
r = c.execute('SELECT value FROM config WHERE key = ?', (key,)).fetchone()
|
| 379 |
+
return r['value'] if r else default
|
| 380 |
+
|
| 381 |
+
def set_config(self, key, value):
|
| 382 |
+
with self.get_conn() as conn:
|
| 383 |
+
c = conn.cursor()
|
| 384 |
+
c.execute('INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)', (key, str(value)))
|
| 385 |
+
conn.commit()
|
| 386 |
+
|
| 387 |
+
db = UltimateDatabase()
|
| 388 |
+
|
| 389 |
+
class SystemEngine:
|
| 390 |
+
@staticmethod
|
| 391 |
+
def check_subscription(user_id):
|
| 392 |
+
if user_id == ADMIN_ID: return True
|
| 393 |
+
u = db.get_user(user_id)
|
| 394 |
+
if u and u['is_vip']: return True
|
| 395 |
+
for ch in CHANNELS:
|
| 396 |
+
try:
|
| 397 |
+
m = bot.get_chat_member(ch, user_id)
|
| 398 |
+
if m.status not in ['member', 'administrator', 'creator']: return False
|
| 399 |
+
except: return False
|
| 400 |
+
return True
|
| 401 |
+
|
| 402 |
+
@staticmethod
|
| 403 |
+
def get_resource_usage():
|
| 404 |
+
cpu = psutil.cpu_percent(interval=0.5)
|
| 405 |
+
ram = psutil.virtual_memory()
|
| 406 |
+
disk = psutil.disk_usage('/')
|
| 407 |
+
return {'cpu': cpu, 'ram_percent': ram.percent, 'ram_used': round(ram.used/(1024**3),2), 'ram_total': round(ram.total/(1024**3),2),
|
| 408 |
+
'disk_percent': disk.percent, 'disk_used': round(disk.used/(1024**3),2), 'disk_total': round(disk.total/(1024**3),2)}
|
| 409 |
+
|
| 410 |
+
@staticmethod
|
| 411 |
+
def get_system_info():
|
| 412 |
+
bt = datetime.fromtimestamp(psutil.boot_time())
|
| 413 |
+
upt = datetime.now() - bt
|
| 414 |
+
h, rem = divmod(int(upt.total_seconds()), 3600)
|
| 415 |
+
m = rem // 60
|
| 416 |
+
return {'os': platform.system(), 'python': platform.python_version(), 'uptime': f"{h}h {m}m", 'cpu_count': psutil.cpu_count(), 'hostname': platform.node()}
|
| 417 |
+
|
| 418 |
+
@staticmethod
|
| 419 |
+
def validate_python_file(path):
|
| 420 |
+
try:
|
| 421 |
+
with open(path, 'r', encoding='utf-8', errors='ignore') as f: src = f.read()
|
| 422 |
+
import ast; ast.parse(src)
|
| 423 |
+
return True, None
|
| 424 |
+
except SyntaxError as e: return False, str(e)
|
| 425 |
+
except: return False, 'ุฎุทุฃ ุบูุฑ ู
ุนุฑูู'
|
| 426 |
+
|
| 427 |
+
@staticmethod
|
| 428 |
+
def get_file_preview(path, lines=30):
|
| 429 |
+
try:
|
| 430 |
+
with open(path, 'r', encoding='utf-8', errors='ignore') as f: return ''.join(f.readlines()[:lines])
|
| 431 |
+
except: return 'ุชุนุฐูุฑ ูุฑุงุกุฉ ุงูู
ูู'
|
| 432 |
+
|
| 433 |
+
@staticmethod
|
| 434 |
+
def is_suspicious_file(file_content, file_name):
|
| 435 |
+
fl = file_name.lower()
|
| 436 |
+
sus_ext = ['.exe','.dll','.bat','.cmd','.scr','.com','.pif','.msi','.hta','.cpl','.jar','.bin','.deb','.rpm','.apk','.dmg','.iso','.img']
|
| 437 |
+
if any(fl.endswith(e) for e in sus_ext): return True, f"ุงู
ุชุฏุงุฏ ู
ุดุจูู: {file_name}"
|
| 438 |
+
for sig in MALWARE_SIGNATURES:
|
| 439 |
+
if file_content.startswith(sig): return True, f"ุชูููุน ุฎุจูุซ: {sig}"
|
| 440 |
+
sample = file_content[:4096]
|
| 441 |
+
for ind in ENCRYPTED_FILE_INDICATORS:
|
| 442 |
+
if ind in sample: return True, f"ู
ุคุดุฑ ุชุดููุฑ: {ind.decode('utf-8', errors='ignore')}"
|
| 443 |
+
st = sample.decode('utf-8', errors='ignore').lower()
|
| 444 |
+
for kw in SUSPICIOUS_KEYWORDS:
|
| 445 |
+
if kw.decode('utf-8').lower() in st: return True, f"ููู
ุฉ ู
ุดุจููุฉ: {kw.decode('utf-8')}"
|
| 446 |
+
if sample.startswith(b'MZ') or sample.startswith(b'\x7fELF'): return True, "ู
ูู ุชูููุฐู"
|
| 447 |
+
return False, "ุขู
ู"
|
| 448 |
+
|
| 449 |
+
@staticmethod
|
| 450 |
+
def scan_for_malicious_code(path, ftype):
|
| 451 |
+
try:
|
| 452 |
+
with open(path, 'r', encoding='utf-8', errors='ignore') as f: content = f.read()
|
| 453 |
+
patterns = MALICIOUS_PYTHON_PATTERNS if ftype=='py' else MALICIOUS_JAVASCRIPT_PATTERNS if ftype=='js' else []
|
| 454 |
+
for p in patterns:
|
| 455 |
+
if re.search(p, content, re.I|re.DOTALL): return True
|
| 456 |
+
return False
|
| 457 |
+
except: return False
|
| 458 |
+
|
| 459 |
+
@staticmethod
|
| 460 |
+
def install_packages(script_path, message_obj=None):
|
| 461 |
+
try:
|
| 462 |
+
with open(script_path, 'r', encoding='utf-8', errors='ignore') as f: content = f.read()
|
| 463 |
+
imports = re.findall(r'^(?:import|from)\s+([\w\d_]+)', content, re.M)
|
| 464 |
+
std = {'os','sys','time','re','math','random','json','threading','subprocess','sqlite3','datetime','tempfile','shutil','logging','psutil','platform','uuid','hashlib','base64','signal','io','zipfile','traceback','functools','string','collections','itertools','pathlib','socket','struct','enum','copy','abc','typing','dataclasses','contextlib','weakref','gc','inspect','ast','dis','types','warnings','unittest','http','urllib','email','html','xml','csv','configparser','argparse','queue','multiprocessing','concurrent','asyncio','select','selectors','ssl','getpass','pwd','grp','stat','glob'}
|
| 465 |
+
installed, failed = [], []
|
| 466 |
+
for lib in set(imports):
|
| 467 |
+
if lib in std: continue
|
| 468 |
+
pkg = TELEGRAM_MODULES.get(lib, lib)
|
| 469 |
+
if pkg is None: continue
|
| 470 |
+
try:
|
| 471 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", pkg, "--quiet"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=60)
|
| 472 |
+
installed.append(lib)
|
| 473 |
+
except: failed.append(lib)
|
| 474 |
+
return installed, failed
|
| 475 |
+
except: return [], []
|
| 476 |
+
|
| 477 |
+
@staticmethod
|
| 478 |
+
def attempt_install_npm(module_name, cwd, message_obj):
|
| 479 |
+
try:
|
| 480 |
+
subprocess.run(['npm', 'install', module_name], capture_output=True, text=True, check=False, cwd=cwd)
|
| 481 |
+
return True
|
| 482 |
+
except FileNotFoundError: return False
|
| 483 |
+
except: return False
|
| 484 |
+
|
| 485 |
+
@staticmethod
|
| 486 |
+
def generate_coupon_code(length=8):
|
| 487 |
+
return ''.join(random.choices(string.ascii_uppercase+string.digits, k=length))
|
| 488 |
+
|
| 489 |
+
@staticmethod
|
| 490 |
+
def format_duration(sec):
|
| 491 |
+
if sec < 60: return f"{int(sec)}ุซ"
|
| 492 |
+
elif sec < 3600: return f"{int(sec//60)}ุฏ"
|
| 493 |
+
else: return f"{int(sec//3600)}ุณ {int((sec%3600)//60)}ุฏ"
|
| 494 |
+
|
| 495 |
+
@staticmethod
|
| 496 |
+
def backup_project(project_id):
|
| 497 |
+
p = db.get_project(project_id)
|
| 498 |
+
if not p or not os.path.exists(p['path']): return None
|
| 499 |
+
name = f"{project_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.py"
|
| 500 |
+
path = os.path.join(BACKUP_DIR, name)
|
| 501 |
+
shutil.copy2(p['path'], path)
|
| 502 |
+
return path
|
| 503 |
+
|
| 504 |
+
def run_script(script_path, user_id, cwd, file_name, message_obj=None, attempt=1, proj_id=None):
|
| 505 |
+
if attempt > 2:
|
| 506 |
+
if message_obj: safe_send(message_obj.chat.id, f"โ ูุดู ุชุดุบูู `{file_name}` ุจุนุฏ ู
ุญุงููุชูู")
|
| 507 |
+
return
|
| 508 |
+
if not os.path.exists(script_path):
|
| 509 |
+
if message_obj: safe_send(message_obj.chat.id, f"โ ุงูู
ูู ุบูุฑ ู
ูุฌูุฏ")
|
| 510 |
+
return
|
| 511 |
+
if attempt == 1:
|
| 512 |
+
try:
|
| 513 |
+
proc = subprocess.Popen([sys.executable, script_path], cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 514 |
+
stdout, stderr = proc.communicate(timeout=5)
|
| 515 |
+
if proc.returncode != 0 and stderr:
|
| 516 |
+
m = re.search(r"ModuleNotFoundError: No module named '(.+?)'", stderr)
|
| 517 |
+
if m:
|
| 518 |
+
lib = m.group(1).strip().strip("'\"")
|
| 519 |
+
pkg = TELEGRAM_MODULES.get(lib, lib)
|
| 520 |
+
if pkg:
|
| 521 |
+
subprocess.run([sys.executable, "-m", "pip", "install", pkg], capture_output=True)
|
| 522 |
+
time.sleep(2)
|
| 523 |
+
threading.Thread(target=run_script, args=(script_path, user_id, cwd, file_name, message_obj, attempt+1, proj_id)).start()
|
| 524 |
+
return
|
| 525 |
+
except subprocess.TimeoutExpired: pass
|
| 526 |
+
except: pass
|
| 527 |
+
log_path = os.path.join(cwd, f"{os.path.splitext(file_name)[0]}.log")
|
| 528 |
+
try:
|
| 529 |
+
logf = open(log_path, 'w', encoding='utf-8')
|
| 530 |
+
except:
|
| 531 |
+
if message_obj: safe_send(message_obj.chat.id, "โ ูุดู ูุชุญ ู
ูู ุงูุณุฌู")
|
| 532 |
+
return
|
| 533 |
+
env = os.environ.copy()
|
| 534 |
+
env.update(db.get_user_env_vars(user_id))
|
| 535 |
+
try:
|
| 536 |
+
proc = subprocess.Popen([sys.executable, '-u', script_path], cwd=cwd, stdout=logf, stderr=logf, stdin=subprocess.PIPE, env=env)
|
| 537 |
+
except Exception as e:
|
| 538 |
+
logf.close()
|
| 539 |
+
if message_obj: safe_send(message_obj.chat.id, f"โ ูุดู ุงูุชุดุบูู: {e}")
|
| 540 |
+
return
|
| 541 |
+
bot_processes[proj_id or f"{user_id}_{file_name}"] = proc
|
| 542 |
+
if proj_id:
|
| 543 |
+
db.update_project_status(proj_id, 'running', proc.pid)
|
| 544 |
+
db.add_project_log(proj_id, 'system', f'ุจุฏุฃ ุงูุชุดุบูู (PID: {proc.pid})')
|
| 545 |
+
if message_obj: safe_send(message_obj.chat.id, f"โ
ุชู
ุชุดุบูู `{file_name}` (PID: {proc.pid})")
|
| 546 |
+
|
| 547 |
+
def run_js_script(script_path, user_id, cwd, file_name, message_obj=None, attempt=1, proj_id=None):
|
| 548 |
+
if attempt > 2:
|
| 549 |
+
if message_obj: safe_send(message_obj.chat.id, f"โ ูุดู ุชุดุบูู JS `{file_name}`")
|
| 550 |
+
return
|
| 551 |
+
if not os.path.exists(script_path):
|
| 552 |
+
if message_obj: safe_send(message_obj.chat.id, f"โ ุงูู
ูู ุบูุฑ ู
ูุฌูุฏ")
|
| 553 |
+
return
|
| 554 |
+
if attempt == 1:
|
| 555 |
+
try:
|
| 556 |
+
proc = subprocess.Popen(['node', script_path], cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 557 |
+
stdout, stderr = proc.communicate(timeout=5)
|
| 558 |
+
if proc.returncode != 0 and stderr:
|
| 559 |
+
m = re.search(r"Cannot find module '(.+?)'", stderr)
|
| 560 |
+
if m:
|
| 561 |
+
mod = m.group(1).strip().strip("'\"")
|
| 562 |
+
if not mod.startswith('.') and not mod.startswith('/'):
|
| 563 |
+
SystemEngine.attempt_install_npm(mod, cwd, message_obj)
|
| 564 |
+
time.sleep(2)
|
| 565 |
+
threading.Thread(target=run_js_script, args=(script_path, user_id, cwd, file_name, message_obj, attempt+1, proj_id)).start()
|
| 566 |
+
return
|
| 567 |
+
except subprocess.TimeoutExpired: pass
|
| 568 |
+
except: pass
|
| 569 |
+
log_path = os.path.join(cwd, f"{os.path.splitext(file_name)[0]}.log")
|
| 570 |
+
try:
|
| 571 |
+
logf = open(log_path, 'w', encoding='utf-8')
|
| 572 |
+
except:
|
| 573 |
+
if message_obj: safe_send(message_obj.chat.id, "โ ูุดู ูุชุญ ุงูุณุฌู")
|
| 574 |
+
return
|
| 575 |
+
env = os.environ.copy()
|
| 576 |
+
env.update(db.get_user_env_vars(user_id))
|
| 577 |
+
try:
|
| 578 |
+
proc = subprocess.Popen(['node', script_path], cwd=cwd, stdout=logf, stderr=logf, stdin=subprocess.PIPE, env=env)
|
| 579 |
+
except Exception as e:
|
| 580 |
+
logf.close()
|
| 581 |
+
if message_obj: safe_send(message_obj.chat.id, f"โ ูุดู ุชุดุบูู Node: {e}")
|
| 582 |
+
return
|
| 583 |
+
bot_processes[proj_id or f"{user_id}_{file_name}"] = proc
|
| 584 |
+
if proj_id:
|
| 585 |
+
db.update_project_status(proj_id, 'running', proc.pid)
|
| 586 |
+
db.add_project_log(proj_id, 'system', f'ุจุฏุฃ ุชุดุบูู Node (PID: {proc.pid})')
|
| 587 |
+
if message_obj: safe_send(message_obj.chat.id, f"โ
ุชู
ุชุดุบูู JS `{file_name}` (PID: {proc.pid})")
|
| 588 |
+
|
| 589 |
+
def kill_process_tree(proc):
|
| 590 |
+
try:
|
| 591 |
+
if proc and proc.poll() is None:
|
| 592 |
+
parent = psutil.Process(proc.pid)
|
| 593 |
+
for child in parent.children(recursive=True):
|
| 594 |
+
child.terminate()
|
| 595 |
+
parent.terminate()
|
| 596 |
+
except: pass
|
| 597 |
+
|
| 598 |
+
def safe_send(chat_id, text, **kwargs):
|
| 599 |
+
try: return bot.send_message(chat_id, text, **kwargs)
|
| 600 |
+
except Exception as e: logger.warning(f"Send error: {e}")
|
| 601 |
+
|
| 602 |
+
def safe_edit(chat_id, msg_id, text, **kwargs):
|
| 603 |
+
try: return bot.edit_message_text(text, chat_id, msg_id, **kwargs)
|
| 604 |
+
except Exception as e: logger.warning(f"Edit error: {e}")
|
| 605 |
+
|
| 606 |
+
def notify_user(user_id, message):
|
| 607 |
+
db.add_notification(user_id, message)
|
| 608 |
+
try: bot.send_message(user_id, f"๐ {message}")
|
| 609 |
+
except: pass
|
| 610 |
+
|
| 611 |
+
class WolfUI:
|
| 612 |
+
@staticmethod
|
| 613 |
+
def main_menu(user_id):
|
| 614 |
+
markup = types.InlineKeyboardMarkup(row_width=2)
|
| 615 |
+
markup.add(types.InlineKeyboardButton("๐ค ุฑูุน ู
ุดุฑูุน", callback_data="ui_upload"), types.InlineKeyboardButton("๐ ู
ุดุงุฑูุนู", callback_data="ui_projects"))
|
| 616 |
+
markup.add(types.InlineKeyboardButton("๐ค ุงูู
ูู ุงูุดุฎุตู", callback_data="ui_profile"), types.InlineKeyboardButton("๐ ูุณุจ ุงูููุงุท", callback_data="ui_earn"))
|
| 617 |
+
markup.add(types.InlineKeyboardButton("๐๏ธ ููุจูู", callback_data="ui_coupon"), types.InlineKeyboardButton("๐ ุงูู
ุชุตุฏุฑูู", callback_data="ui_leaderboard"))
|
| 618 |
+
markup.add(types.InlineKeyboardButton("๐ ุงูู
ุชุฌุฑ", callback_data="ui_store"), types.InlineKeyboardButton("๐ฃ ุงูุฅุดุนุงุฑุงุช", callback_data="ui_notifications"))
|
| 619 |
+
markup.add(types.InlineKeyboardButton("๐ ุงูููุงูุจ", callback_data="ui_templates"), types.InlineKeyboardButton("โ ู
ุณุงุนุฏุฉ", callback_data="ui_help"))
|
| 620 |
+
markup.add(types.InlineKeyboardButton("โ๏ธ ุงูุฅุนุฏุงุฏุงุช", callback_data="ui_settings"))
|
| 621 |
+
if user_id == ADMIN_ID: markup.add(types.InlineKeyboardButton("๐ ููุญุฉ ุงูู
ุทูุฑ", callback_data="admin_root"))
|
| 622 |
+
return markup
|
| 623 |
+
|
| 624 |
+
@staticmethod
|
| 625 |
+
def sub_check_menu():
|
| 626 |
+
markup = types.InlineKeyboardMarkup()
|
| 627 |
+
for ch in CHANNELS: markup.add(types.InlineKeyboardButton(f"ุงูุงูุถู
ุงู
{ch}", url=f"https://t.me/{ch[1:]}"))
|
| 628 |
+
markup.add(types.InlineKeyboardButton("โ
ุชู
ุงูุงุดุชุฑุงู", callback_data="verify_access"))
|
| 629 |
+
return markup
|
| 630 |
+
|
| 631 |
+
@staticmethod
|
| 632 |
+
def project_control(project_id, status, auto_restart=1):
|
| 633 |
+
markup = types.InlineKeyboardMarkup(row_width=2)
|
| 634 |
+
if status == 'running': markup.add(types.InlineKeyboardButton("๐ ุฅููุงู", callback_data=f"proc_stop_{project_id}"))
|
| 635 |
+
else: markup.add(types.InlineKeyboardButton("โถ๏ธ ุชุดุบูู", callback_data=f"proc_start_{project_id}"))
|
| 636 |
+
markup.add(types.InlineKeyboardButton("๐ ุณุฌูุงุช", callback_data=f"proc_logs_{project_id}"), types.InlineKeyboardButton("๐๏ธ ุนุฑุถ ุงูููุฏ", callback_data=f"proc_view_{project_id}"))
|
| 637 |
+
markup.add(types.InlineKeyboardButton("๐ ุฅุนุงุฏุฉ", callback_data=f"proc_restart_{project_id}"), types.InlineKeyboardButton("๐ ู
ูุงุญุธุงุช", callback_data=f"proc_note_{project_id}"))
|
| 638 |
+
markup.add(types.InlineKeyboardButton("๐ ู
ุชุบูุฑุงุช", callback_data=f"proc_env_{project_id}"), types.InlineKeyboardButton("๐พ ูุณุฎุฉ", callback_data=f"proc_backup_{project_id}"))
|
| 639 |
+
ar = "๐ ุฅููุงู ุงูุชููุงุฆู" if auto_restart else "๐ ุชูุนูู ุงูุชููุงุฆู"
|
| 640 |
+
markup.add(types.InlineKeyboardButton(ar, callback_data=f"proc_ar0_{project_id}" if auto_restart else f"proc_ar1_{project_id}"))
|
| 641 |
+
markup.add(types.InlineKeyboardButton("๐๏ธ ุญุฐู", callback_data=f"proc_del_{project_id}"), types.InlineKeyboardButton("๐ ุฑุฌูุน", callback_data="ui_projects"))
|
| 642 |
+
return markup
|
| 643 |
+
|
| 644 |
+
@staticmethod
|
| 645 |
+
def admin_panel():
|
| 646 |
+
markup = types.InlineKeyboardMarkup(row_width=2)
|
| 647 |
+
markup.add(types.InlineKeyboardButton("๐ข ุฅุฐุงุนุฉ", callback_data="root_bc"), types.InlineKeyboardButton("๐ ุฅุญุตุงุฆูุงุช", callback_data="root_stats"))
|
| 648 |
+
markup.add(types.InlineKeyboardButton("๐ฅ ุงูู
ุณุชุฎุฏู
ูู", callback_data="root_users"), types.InlineKeyboardButton("๐ ุงูู
ุดุงุฑูุน", callback_data="root_projects"))
|
| 649 |
+
markup.add(types.InlineKeyboardButton("๐๏ธ ุงูููุจููุงุช", callback_data="root_coupons"), types.InlineKeyboardButton("๐ฅ๏ธ ุงูุณูุฑูุฑ", callback_data="root_server"))
|
| 650 |
+
markup.add(types.InlineKeyboardButton("๐ซ ุญุธุฑ", callback_data="root_ban"), types.InlineKeyboardButton("๐ ูู", callback_data="root_unban"))
|
| 651 |
+
markup.add(types.InlineKeyboardButton("๐ VIP", callback_data="root_vip"), types.InlineKeyboardButton("๐ช ููุงุท", callback_data="root_give_points"))
|
| 652 |
+
markup.add(types.InlineKeyboardButton("๐ง ุตูุงูุฉ", callback_data="root_maintenance"), types.InlineKeyboardButton("๐ ุฑุฌูุน", callback_data="main_back"))
|
| 653 |
+
return markup
|
| 654 |
+
|
| 655 |
+
@staticmethod
|
| 656 |
+
def store_menu():
|
| 657 |
+
markup = types.InlineKeyboardMarkup(row_width=1)
|
| 658 |
+
for k, v in PLAN_LIMITS.items():
|
| 659 |
+
if k == 'free': continue
|
| 660 |
+
markup.add(types.InlineKeyboardButton(f"{v['label']} - {v['projects']} ู
ุดุงุฑูุน - {v['price']} ููุทุฉ", callback_data=f"buy_plan_{k}"))
|
| 661 |
+
markup.add(types.InlineKeyboardButton("๐ ุฑุฌูุน", callback_data="main_back"))
|
| 662 |
+
return markup
|
| 663 |
+
|
| 664 |
+
@staticmethod
|
| 665 |
+
def back_button(cb='main_back'): return types.InlineKeyboardMarkup().add(types.InlineKeyboardButton("๐ ุฑุฌูุน", callback_data=cb))
|
| 666 |
+
@staticmethod
|
| 667 |
+
def confirm_delete(pid): return types.InlineKeyboardMarkup().add(types.InlineKeyboardButton("โ
ูุนู
", callback_data=f"proc_delconfirm_{pid}"), types.InlineKeyboardButton("โ ูุง", callback_data=f"ctrl_view_{pid}"))
|
| 668 |
+
|
| 669 |
+
@bot.message_handler(commands=['start'])
|
| 670 |
+
def start_cmd(message):
|
| 671 |
+
uid = message.from_user.id
|
| 672 |
+
args = message.text.split()
|
| 673 |
+
inviter = int(args[1]) if len(args)>1 and args[1].isdigit() and int(args[1])!=uid else None
|
| 674 |
+
db.register_user(uid, message.from_user.username or '', f"{message.from_user.first_name or ''} {message.from_user.last_name or ''}".strip(), inviter)
|
| 675 |
+
if db.is_banned(uid): safe_send(message.chat.id, "๐ซ ู
ุญุธูุฑ"); return
|
| 676 |
+
if not SystemEngine.check_subscription(uid):
|
| 677 |
+
safe_send(message.chat.id, "โ ๏ธ ุงุดุชุฑู ูู ุงูููุงุฉ ุฃููุงู:", reply_markup=WolfUI.sub_check_menu()); return
|
| 678 |
+
u = db.get_user(uid)
|
| 679 |
+
if inviter and u and not u['rewarded'] and SystemEngine.check_subscription(uid):
|
| 680 |
+
db.add_points(inviter, RATES['invite_reward'], f'ุฏุนูุฉ @{message.from_user.username}')
|
| 681 |
+
db.update_user_field(uid, 'rewarded', 1)
|
| 682 |
+
db.update_user_field(inviter, 'total_invites', (db.get_user(inviter)['total_invites'] or 0)+1)
|
| 683 |
+
try: safe_send(inviter, f"๐ +{RATES['invite_reward']} ููุทุฉ ูุฏุนูุชู @{message.from_user.username}")
|
| 684 |
+
except: pass
|
| 685 |
+
db.add_activity(uid, 'start')
|
| 686 |
+
unread = len(db.get_notifications(uid, unread_only=True))
|
| 687 |
+
plan = db.get_user_plan(uid)
|
| 688 |
+
txt = f"๐บ ุฃููุงู {u['full_name'] or u['username']}!\n๐ฆ ุฎุทุชู: {PLAN_LIMITS[plan]['label']}" + (f"\n๐ {unread} ุฅุดุนุงุฑุงุช" if unread else "")
|
| 689 |
+
safe_send(message.chat.id, txt, reply_markup=WolfUI.main_menu(uid))
|
| 690 |
+
|
| 691 |
+
@bot.callback_query_handler(func=lambda c: c.data == "verify_access")
|
| 692 |
+
def verify_access(call):
|
| 693 |
+
if SystemEngine.check_subscription(call.from_user.id):
|
| 694 |
+
try: bot.delete_message(call.message.chat.id, call.message.message_id)
|
| 695 |
+
except: pass
|
| 696 |
+
start_cmd(call.message)
|
| 697 |
+
else: bot.answer_callback_query(call.id, "โ ูู
ุชุดุชุฑู", show_alert=True)
|
| 698 |
+
|
| 699 |
+
@bot.callback_query_handler(func=lambda c: c.data == "main_back")
|
| 700 |
+
def main_back(call): safe_edit(call.message.chat.id, call.message.message_id, "๐บ ุงููุงุฆู
ุฉ ุงูุฑุฆูุณูุฉ", reply_markup=WolfUI.main_menu(call.from_user.id))
|
| 701 |
+
|
| 702 |
+
@bot.callback_query_handler(func=lambda c: c.data.startswith("ui_"))
|
| 703 |
+
def ui_handler(call):
|
| 704 |
+
uid = call.from_user.id
|
| 705 |
+
act = call.data[3:]
|
| 706 |
+
if db.is_banned(uid): bot.answer_callback_query(call.id, "๐ซ ู
ุญุธูุฑ", show_alert=True); return
|
| 707 |
+
if act == "profile":
|
| 708 |
+
u = db.get_user(uid); res = SystemEngine.get_resource_usage(); projs = db.get_user_projects(uid); running = sum(1 for p in projs if p['status']=='running')
|
| 709 |
+
msg = f"๐ค {u['full_name'] or u['username']}\n๐ {uid}\n๐ฐ {u['points']} ููุทุฉ\n๐ฆ {PLAN_LIMITS[db.get_user_plan(uid)]['label']}\n๐ {len(projs)}/{db.get_plan_limit(uid)}\n๐ข {running}\n๐ฅ๏ธ CPU {res['cpu']}% RAM {res['ram_percent']}%"
|
| 710 |
+
safe_edit(call.message.chat.id, call.message.message_id, msg, reply_markup=WolfUI.main_menu(uid))
|
| 711 |
+
elif act == "upload":
|
| 712 |
+
if not SystemEngine.check_subscription(uid): safe_edit(call.message.chat.id, call.message.message_id, "โ ๏ธ ุงุดุชุฑู ุฃููุงู", reply_markup=WolfUI.sub_check_menu()); return
|
| 713 |
+
if len([p for p in db.get_user_projects(uid) if p['status']!='deleted']) >= db.get_plan_limit(uid) and uid!=ADMIN_ID:
|
| 714 |
+
bot.answer_callback_query(call.id, "โ ๏ธ ูุตูุช ููุญุฏ", show_alert=True); return
|
| 715 |
+
user_states[uid] = {'state': 'awaiting_file'}
|
| 716 |
+
msg = safe_send(call.message.chat.id, "๐ค ุฃุฑุณู ู
ูู .py ุฃู .js ุฃู .zip\n/cancel ููุฅูุบุงุก")
|
| 717 |
+
bot.register_next_step_handler(msg, process_file_upload)
|
| 718 |
+
elif act == "projects":
|
| 719 |
+
projs = db.get_user_projects(uid)
|
| 720 |
+
if not projs: bot.answer_callback_query(call.id, "๐ญ ูุง ู
ุดุงุฑูุน"); return
|
| 721 |
+
mk = types.InlineKeyboardMarkup()
|
| 722 |
+
for p in projs[:20]:
|
| 723 |
+
icon = {'running':'๐ข','stopped':'๐ด','pending':'โณ','crashed':'๐ฅ'}.get(p['status'],'โ')
|
| 724 |
+
mk.add(types.InlineKeyboardButton(f"{icon} {p['file_name']}", callback_data=f"ctrl_view_{p['project_id']}"))
|
| 725 |
+
mk.add(types.InlineKeyboardButton("๐ ุฑุฌูุน", callback_data="main_back"))
|
| 726 |
+
safe_edit(call.message.chat.id, call.message.message_id, "๐ ู
ุดุงุฑูุนู", reply_markup=mk)
|
| 727 |
+
elif act == "earn":
|
| 728 |
+
link = f"https://t.me/{bot.get_me().username}?start={uid}"
|
| 729 |
+
safe_edit(call.message.chat.id, call.message.message_id, f"๐ ุฑุงุจุท ุงูุฏุนูุฉ:\n`{link}`\n๐ฐ ุฑุตูุฏู: {db.get_user(uid)['points']}", reply_markup=WolfUI.back_button())
|
| 730 |
+
elif act == "store": safe_edit(call.message.chat.id, call.message.message_id, f"๐ ุฑุตูุฏู: {db.get_user(uid)['points']}\nุงุฎุชุฑ ุฎุทุฉ:", reply_markup=WolfUI.store_menu())
|
| 731 |
+
elif act == "coupon":
|
| 732 |
+
user_states[uid] = {'state': 'awaiting_coupon'}
|
| 733 |
+
msg = safe_send(call.message.chat.id, "๐๏ธ ุฃุฑุณู ููุฏ ุงูููุจูู:")
|
| 734 |
+
bot.register_next_step_handler(msg, process_coupon)
|
| 735 |
+
elif act == "leaderboard": pass
|
| 736 |
+
elif act == "notifications":
|
| 737 |
+
notifs = db.get_notifications(uid); db.mark_notifications_read(uid)
|
| 738 |
+
if not notifs: bot.answer_callback_query(call.id, "๐ญ ูุง ุฅุดุนุงุฑุงุช")
|
| 739 |
+
else: safe_edit(call.message.chat.id, call.message.message_id, "\n".join([f"โข {n['message']}" for n in notifs[:10]]), reply_markup=WolfUI.back_button())
|
| 740 |
+
elif act == "templates": bot.answer_callback_query(call.id, "๐ ูุฑูุจุงู")
|
| 741 |
+
elif act == "help": safe_edit(call.message.chat.id, call.message.message_id, "โ ุงูุฏุนู
: @j49_c", reply_markup=WolfUI.back_button())
|
| 742 |
+
elif act == "settings": safe_edit(call.message.chat.id, call.message.message_id, "โ๏ธ ุงูุฅุนุฏุงุฏุงุช", reply_markup=WolfUI.back_button())
|
| 743 |
+
|
| 744 |
+
def process_coupon(message):
|
| 745 |
+
if message.text == '/cancel': user_states.pop(message.from_user.id, None); safe_send(message.chat.id, "โ ุฅูุบุงุก"); return
|
| 746 |
+
uid = message.from_user.id
|
| 747 |
+
cp, err = db.use_coupon(message.text.strip().upper(), uid)
|
| 748 |
+
if err: safe_send(message.chat.id, f"โ {err}"); return
|
| 749 |
+
if cp['type'] == 'points':
|
| 750 |
+
db.add_points(uid, int(cp['value']), f'ููุจูู {cp["code"]}')
|
| 751 |
+
safe_send(message.chat.id, f"โ
+{cp['value']} ููุทุฉ")
|
| 752 |
+
else:
|
| 753 |
+
db.set_plan(uid, cp['value'], 30)
|
| 754 |
+
safe_send(message.chat.id, f"โ
ุฎุทุฉ {cp['value']} ู
ูุนูุฉ")
|
| 755 |
+
user_states.pop(uid, None)
|
| 756 |
+
|
| 757 |
+
def process_file_upload(message):
|
| 758 |
+
if message.text == '/cancel': user_states.pop(message.from_user.id, None); safe_send(message.chat.id, "โ ุฅูุบุงุก"); return
|
| 759 |
+
uid = message.from_user.id
|
| 760 |
+
user_states.pop(uid, None)
|
| 761 |
+
if not message.document: safe_send(message.chat.id, "โ ุฃุฑุณู ู
ูู"); return
|
| 762 |
+
fname = message.document.file_name
|
| 763 |
+
if not (fname.endswith('.py') or fname.endswith('.js') or fname.endswith('.zip')): safe_send(message.chat.id, "โ .py .js .zip ููุท"); return
|
| 764 |
+
if message.document.file_size > MAX_FILE_SIZE_MB*1024*1024: safe_send(message.chat.id, f"โ ุงูุญุฏ {MAX_FILE_SIZE_MB}MB"); return
|
| 765 |
+
finfo = bot.get_file(message.document.file_id)
|
| 766 |
+
content = bot.download_file(finfo.file_path)
|
| 767 |
+
proj_id = str(uuid.uuid4())[:8]
|
| 768 |
+
user_folder = os.path.join(HOSTING_DIR, str(uid))
|
| 769 |
+
os.makedirs(user_folder, exist_ok=True)
|
| 770 |
+
if fname.endswith('.zip'):
|
| 771 |
+
tdir = tempfile.mkdtemp()
|
| 772 |
+
zpath = os.path.join(tdir, fname)
|
| 773 |
+
with open(zpath, 'wb') as f: f.write(content)
|
| 774 |
+
with zipfile.ZipFile(zpath, 'r') as zf: zf.extractall(tdir)
|
| 775 |
+
py_files = [f for f in os.listdir(tdir) if f.endswith('.py')]
|
| 776 |
+
js_files = [f for f in os.listdir(tdir) if f.endswith('.js')]
|
| 777 |
+
main = None; ftype = None
|
| 778 |
+
if 'main.py' in py_files: main, ftype = 'main.py', 'py'
|
| 779 |
+
elif py_files: main, ftype = py_files[0], 'py'
|
| 780 |
+
elif 'index.js' in js_files: main, ftype = 'index.js', 'js'
|
| 781 |
+
elif js_files: main, ftype = js_files[0], 'js'
|
| 782 |
+
if not main: safe_send(message.chat.id, "โ ูุง ููุฌุฏ ู
ูู ูุงุจู ููุชุดุบูู"); shutil.rmtree(tdir); return
|
| 783 |
+
for item in os.listdir(tdir):
|
| 784 |
+
src = os.path.join(tdir, item); dst = os.path.join(user_folder, item)
|
| 785 |
+
if os.path.isdir(dst): shutil.rmtree(dst)
|
| 786 |
+
elif os.path.exists(dst): os.remove(dst)
|
| 787 |
+
shutil.move(src, dst)
|
| 788 |
+
shutil.rmtree(tdir)
|
| 789 |
+
file_path = os.path.join(user_folder, main)
|
| 790 |
+
fname = main
|
| 791 |
+
else:
|
| 792 |
+
ftype = 'py' if fname.endswith('.py') else 'js'
|
| 793 |
+
file_path = os.path.join(user_folder, fname)
|
| 794 |
+
with open(file_path, 'wb') as f: f.write(content)
|
| 795 |
+
is_susp, reason = SystemEngine.is_suspicious_file(content, fname)
|
| 796 |
+
if is_susp and uid != ADMIN_ID: safe_send(message.chat.id, f"๐ซ ู
ูู ู
ุดุจูู: {reason}"); os.remove(file_path); return
|
| 797 |
+
if SystemEngine.scan_for_malicious_code(file_path, ftype) and uid != ADMIN_ID: safe_send(message.chat.id, "๐ซ ููุฏ ุฎุจูุซ"); os.remove(file_path); return
|
| 798 |
+
db.add_project(proj_id, uid, fname, ftype, file_path)
|
| 799 |
+
db.add_activity(uid, 'upload', fname)
|
| 800 |
+
markup = types.InlineKeyboardMarkup().add(types.InlineKeyboardButton("โ
ูุจูู", callback_data=f"adm_ok_{proj_id}"), types.InlineKeyboardButton("โ ุฑูุถ", callback_data=f"adm_no_{proj_id}"))
|
| 801 |
+
preview = SystemEngine.get_file_preview(file_path, 10)
|
| 802 |
+
cap = f"๐ฅ ุทูุจ ุฌุฏูุฏ\n๐ค {uid}\n๐ {fname}\n๐ {proj_id}\n```{preview[:800]}```"
|
| 803 |
+
try:
|
| 804 |
+
with open(file_path, 'rb') as f: bot.send_document(ADMIN_ID, f, caption=cap, reply_markup=markup)
|
| 805 |
+
except: safe_send(ADMIN_ID, cap, reply_markup=markup)
|
| 806 |
+
safe_send(message.chat.id, "โณ ุชู
ุงูุฅุฑุณุงู ููุฅุฏุงุฑุฉ ููู
ุฑุงุฌุนุฉ")
|
| 807 |
+
|
| 808 |
+
@bot.callback_query_handler(func=lambda c: c.data.startswith("adm_"))
|
| 809 |
+
def admin_decision(call):
|
| 810 |
+
if call.from_user.id != ADMIN_ID: return
|
| 811 |
+
_, act, pid = call.data.split('_')
|
| 812 |
+
p = db.get_project(pid)
|
| 813 |
+
if not p: bot.answer_callback_query(call.id, "โ ุบูุฑ ู
ูุฌูุฏ"); return
|
| 814 |
+
if act == "ok":
|
| 815 |
+
db.update_project_status(pid, "approved")
|
| 816 |
+
if p['user_id'] != ADMIN_ID and not db.get_user(p['user_id'])['is_vip']: db.deduct_points(p['user_id'], 1, f'ุชูุนูู {p["file_name"]}')
|
| 817 |
+
if p['file_type'] == 'py': threading.Thread(target=run_script, args=(p['path'], p['user_id'], os.path.dirname(p['path']), p['file_name'], None, 1, pid)).start()
|
| 818 |
+
else: threading.Thread(target=run_js_script, args=(p['path'], p['user_id'], os.path.dirname(p['path']), p['file_name'], None, 1, pid)).start()
|
| 819 |
+
notify_user(p['user_id'], f"โ
ุชู
ูุจูู {p['file_name']}")
|
| 820 |
+
try: bot.edit_message_caption("โ
ุชู
ุงููุจูู", ADMIN_ID, call.message.message_id)
|
| 821 |
+
except: pass
|
| 822 |
+
else:
|
| 823 |
+
os.remove(p['path']) if os.path.exists(p['path']) else None
|
| 824 |
+
db.delete_project(pid)
|
| 825 |
+
notify_user(p['user_id'], f"โ ุชู
ุฑูุถ {p['file_name']}")
|
| 826 |
+
try: bot.edit_message_caption("โ ุชู
ุงูุฑูุถ", ADMIN_ID, call.message.message_id)
|
| 827 |
+
except: pass
|
| 828 |
+
|
| 829 |
+
@bot.callback_query_handler(func=lambda c: c.data.startswith("ctrl_view_"))
|
| 830 |
+
def view_project(call):
|
| 831 |
+
pid = call.data[10:]
|
| 832 |
+
p = db.get_project(pid)
|
| 833 |
+
if not p: bot.answer_callback_query(call.id, "โ ุบูุฑ ู
ูุฌูุฏ"); return
|
| 834 |
+
if p['user_id'] != call.from_user.id and call.from_user.id != ADMIN_ID: bot.answer_callback_query(call.id, "๐ซ ุตูุงุญูุฉ"); return
|
| 835 |
+
st = {'running':'๐ข','stopped':'๐ด','pending':'โณ','crashed':'๐ฅ'}.get(p['status'], p['status'])
|
| 836 |
+
upt = ''
|
| 837 |
+
if p['status']=='running' and pid in project_start_times: upt = f"\nโฑ๏ธ {SystemEngine.format_duration(time.time()-project_start_times[pid])}"
|
| 838 |
+
msg = f"๐ {p['file_name']} ({p['file_type']})\n๐ {pid}\n๐ฆ {st}{upt}\n๐ ุชููุงุฆู: {'โ
' if p['auto_restart'] else 'โ'}"
|
| 839 |
+
safe_edit(call.message.chat.id, call.message.message_id, msg, reply_markup=WolfUI.project_control(pid, p['status'], p['auto_restart']))
|
| 840 |
+
|
| 841 |
+
@bot.callback_query_handler(func=lambda c: c.data.startswith("proc_"))
|
| 842 |
+
def proc_control(call):
|
| 843 |
+
uid = call.from_user.id
|
| 844 |
+
parts = call.data.split('_')
|
| 845 |
+
act = parts[1]
|
| 846 |
+
pid = '_'.join(parts[2:])
|
| 847 |
+
p = db.get_project(pid)
|
| 848 |
+
if not p or (p['user_id']!=uid and uid!=ADMIN_ID): bot.answer_callback_query(call.id, "๐ซ"); return
|
| 849 |
+
if act == "stop":
|
| 850 |
+
if pid in bot_processes: kill_process_tree(bot_processes.pop(pid)); db.update_project_status(pid, 'stopped')
|
| 851 |
+
bot.answer_callback_query(call.id, "๐ ุชููู"); view_project(call)
|
| 852 |
+
elif act == "start":
|
| 853 |
+
if p['status']=='running': bot.answer_callback_query(call.id, "โ ๏ธ ูุนู
ู"); return
|
| 854 |
+
if p['file_type']=='py': threading.Thread(target=run_script, args=(p['path'], p['user_id'], os.path.dirname(p['path']), p['file_name'], None, 1, pid)).start()
|
| 855 |
+
else: threading.Thread(target=run_js_script, args=(p['path'], p['user_id'], os.path.dirname(p['path']), p['file_name'], None, 1, pid)).start()
|
| 856 |
+
bot.answer_callback_query(call.id, "โถ๏ธ ุชุดุบูู"); time.sleep(2); view_project(call)
|
| 857 |
+
elif act == "restart":
|
| 858 |
+
if pid in bot_processes: kill_process_tree(bot_processes.pop(pid))
|
| 859 |
+
if p['file_type']=='py': threading.Thread(target=run_script, args=(p['path'], p['user_id'], os.path.dirname(p['path']), p['file_name'], None, 1, pid)).start()
|
| 860 |
+
else: threading.Thread(target=run_js_script, args=(p['path'], p['user_id'], os.path.dirname(p['path']), p['file_name'], None, 1, pid)).start()
|
| 861 |
+
bot.answer_callback_query(call.id, "๐ ุฅุนุงุฏุฉ"); time.sleep(2); view_project(call)
|
| 862 |
+
elif act == "logs":
|
| 863 |
+
logs = db.get_project_logs(pid, 15)
|
| 864 |
+
if not logs: bot.answer_callback_query(call.id, "๐ญ"); return
|
| 865 |
+
txt = "\n".join([f"[{l['timestamp'][:16]}] {l['content'][:200]}" for l in reversed(logs)])
|
| 866 |
+
safe_edit(call.message.chat.id, call.message.message_id, txt[:4000], reply_markup=WolfUI.back_button(f"ctrl_view_{pid}"))
|
| 867 |
+
elif act == "view":
|
| 868 |
+
prev = SystemEngine.get_file_preview(p['path'], 40)
|
| 869 |
+
safe_edit(call.message.chat.id, call.message.message_id, f"```{prev[:3000]}```", reply_markup=WolfUI.back_button(f"ctrl_view_{pid}"))
|
| 870 |
+
elif act == "del":
|
| 871 |
+
safe_edit(call.message.chat.id, call.message.message_id, f"โ ๏ธ ุญุฐู {p['file_name']}ุ", reply_markup=WolfUI.confirm_delete(pid))
|
| 872 |
+
elif act == "delconfirm":
|
| 873 |
+
if pid in bot_processes: kill_process_tree(bot_processes.pop(pid))
|
| 874 |
+
os.remove(p['path']) if os.path.exists(p['path']) else None
|
| 875 |
+
db.delete_project(pid); bot.answer_callback_query(call.id, "๐๏ธ ุญุฐู"); ui_handler(type('',(),{'data':'ui_projects','message':call.message,'from_user':call.from_user,'id':call.id})())
|
| 876 |
+
elif act == "ar0": db.set_auto_restart(pid, 0); view_project(call)
|
| 877 |
+
elif act == "ar1": db.set_auto_restart(pid, 1); view_project(call)
|
| 878 |
+
elif act == "backup":
|
| 879 |
+
bp = SystemEngine.backup_project(pid)
|
| 880 |
+
if bp: bot.send_document(call.message.chat.id, open(bp,'rb'), caption=f"ูุณุฎุฉ {p['file_name']}")
|
| 881 |
+
else: bot.answer_callback_query(call.id, "โ ูุดู")
|
| 882 |
+
|
| 883 |
+
@bot.callback_query_handler(func=lambda c: c.data == "admin_root")
|
| 884 |
+
def admin_root(call):
|
| 885 |
+
if call.from_user.id != ADMIN_ID: return
|
| 886 |
+
safe_edit(call.message.chat.id, call.message.message_id, "๐ ููุญุฉ ุงูู
ุทูุฑ", reply_markup=WolfUI.admin_panel())
|
| 887 |
+
|
| 888 |
+
@bot.callback_query_handler(func=lambda c: c.data.startswith("root_"))
|
| 889 |
+
def admin_actions(call):
|
| 890 |
+
if call.from_user.id != ADMIN_ID: return
|
| 891 |
+
act = call.data[5:]
|
| 892 |
+
if act == "stats":
|
| 893 |
+
s = db.get_stats(); r = SystemEngine.get_resource_usage(); si = SystemEngine.get_system_info()
|
| 894 |
+
msg = f"๐ฅ {s['total_users']} | ๐ซ {s['banned_users']} | ๐ {s['vip_users']}\n๐ {s['total_projects']} | ๐ข {s['running_projects']}\n๐ฅ๏ธ CPU {r['cpu']}% RAM {r['ram_percent']}%\nโฑ๏ธ {si['uptime']}"
|
| 895 |
+
safe_edit(call.message.chat.id, call.message.message_id, msg, reply_markup=WolfUI.back_button("admin_root"))
|
| 896 |
+
elif act == "server":
|
| 897 |
+
si = SystemEngine.get_system_info(); r = SystemEngine.get_resource_usage()
|
| 898 |
+
msg = f"๐ฅ๏ธ {si['hostname']}\n๐ป {si['os']}\n๐ {si['python']}\nโฑ๏ธ {si['uptime']}\n๐ง {si['cpu_count']} cores\n๐ CPU {r['cpu']}% RAM {r['ram_percent']}%"
|
| 899 |
+
safe_edit(call.message.chat.id, call.message.message_id, msg, reply_markup=WolfUI.back_button("admin_root"))
|
| 900 |
+
elif act == "bc":
|
| 901 |
+
user_states[ADMIN_ID] = {'state': 'broadcast'}
|
| 902 |
+
msg = safe_send(ADMIN_ID, "๐ข ุฃุฑุณู ุฑุณุงูุฉ ุงูุจุซ:")
|
| 903 |
+
bot.register_next_step_handler(msg, do_broadcast)
|
| 904 |
+
elif act == "ban":
|
| 905 |
+
user_states[ADMIN_ID] = {'state': 'ban'}; safe_send(ADMIN_ID, "๐ซ ุฃุฑุณู ID:")
|
| 906 |
+
bot.register_next_step_handler(msg, lambda m: db.ban_user(int(m.text)) or safe_send(ADMIN_ID, "โ
ุชู
"))
|
| 907 |
+
elif act == "maintenance":
|
| 908 |
+
global maintenance_mode; maintenance_mode = not maintenance_mode
|
| 909 |
+
bot.answer_callback_query(call.id, f"๐ง {maintenance_mode}")
|
| 910 |
+
|
| 911 |
+
def do_broadcast(msg):
|
| 912 |
+
if msg.text == '/cancel': user_states.pop(ADMIN_ID); return
|
| 913 |
+
users = db.get_all_users(); cnt = 0
|
| 914 |
+
for u in users:
|
| 915 |
+
try: bot.send_message(u['user_id'], msg.text); cnt += 1
|
| 916 |
+
except: pass
|
| 917 |
+
safe_send(ADMIN_ID, f"โ
ุฃูุฑุณู ูู {cnt}")
|
| 918 |
+
|
| 919 |
+
@bot.message_handler(commands=['cancel'])
|
| 920 |
+
def cancel_cmd(m): user_states.pop(m.from_user.id, None); safe_send(m.chat.id, "โ ุฅูุบุงุก")
|
| 921 |
+
|
| 922 |
+
@bot.message_handler(commands=['id'])
|
| 923 |
+
def id_cmd(m): safe_send(m.chat.id, f"๐ {m.from_user.id}")
|
| 924 |
+
|
| 925 |
+
@bot.message_handler(commands=['ping'])
|
| 926 |
+
def ping_cmd(m):
|
| 927 |
+
s = time.time(); msg = safe_send(m.chat.id, "๐")
|
| 928 |
+
bot.edit_message_text(f"๐ {round((time.time()-s)*1000)}ms", m.chat.id, msg.message_id)
|
| 929 |
+
|
| 930 |
+
def monitor_processes():
|
| 931 |
+
while True:
|
| 932 |
+
for pid, proc in list(bot_processes.items()):
|
| 933 |
+
if proc.poll() is not None:
|
| 934 |
+
p = db.get_project(pid)
|
| 935 |
+
if p and p['auto_restart']:
|
| 936 |
+
db.update_project_status(pid, 'crashed')
|
| 937 |
+
if p['file_type']=='py': threading.Thread(target=run_script, args=(p['path'], p['user_id'], os.path.dirname(p['path']), p['file_name'], None, 1, pid)).start()
|
| 938 |
+
else: threading.Thread(target=run_js_script, args=(p['path'], p['user_id'], os.path.dirname(p['path']), p['file_name'], None, 1, pid)).start()
|
| 939 |
+
else: db.update_project_status(pid, 'stopped')
|
| 940 |
+
del bot_processes[pid]
|
| 941 |
+
time.sleep(10)
|
| 942 |
+
|
| 943 |
+
threading.Thread(target=monitor_processes, daemon=True).start()
|
| 944 |
+
|
| 945 |
+
if __name__ == '__main__':
|
| 946 |
+
logger.info(f"๐บ White Wolf Ultimate v{VERSION}")
|
| 947 |
+
while True:
|
| 948 |
+
try: bot.infinity_polling(timeout=60)
|
| 949 |
+
except Exception as e: logger.error(f"Poll error: {e}"); time.sleep(10)
|