Spaces:
Paused
Paused
Update bot.py
Browse files
bot.py
CHANGED
|
@@ -1,509 +1,619 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
import os
|
| 7 |
-
import
|
|
|
|
| 8 |
import uuid
|
| 9 |
-
import
|
| 10 |
-
import
|
| 11 |
import zipfile
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
import logging
|
| 13 |
-
import
|
| 14 |
-
from
|
| 15 |
-
|
| 16 |
-
# مكتبات النظام الخارجي (يجب توفرها)
|
| 17 |
-
import psutil
|
| 18 |
-
import telebot
|
| 19 |
-
from telebot import types
|
| 20 |
|
| 21 |
-
# =================
|
|
|
|
|
|
|
| 22 |
TOKEN = '7847673598:AAGeqJb591uZWCwpSqS8VJGWTRtDOr0CTEE'
|
| 23 |
ADMIN_ID = 6812997550
|
| 24 |
-
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
| 29 |
|
| 30 |
-
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
# إعداد ال
|
| 33 |
-
bot = telebot.TeleBot(TOKEN, parse_mode='Markdown')
|
| 34 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
conn.row_factory = sqlite3.Row
|
| 46 |
return conn
|
| 47 |
|
| 48 |
-
def
|
| 49 |
-
with self.
|
|
|
|
| 50 |
c.execute('''CREATE TABLE IF NOT EXISTS users (
|
| 51 |
-
user_id INTEGER PRIMARY KEY, username TEXT,
|
|
|
|
|
|
|
| 52 |
)''')
|
| 53 |
c.execute('''CREATE TABLE IF NOT EXISTS projects (
|
| 54 |
-
project_id TEXT PRIMARY KEY, user_id INTEGER, file_name TEXT,
|
| 55 |
-
|
|
|
|
| 56 |
)''')
|
| 57 |
-
c.
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
def
|
| 66 |
-
with self.
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
def
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
class SecurityScanner:
|
| 91 |
-
"""نظام فحص أمني دقيق لمنع الملفات الخبيثة وتأمين السيرفر"""
|
| 92 |
-
DANGEROUS_PATTERNS =[
|
| 93 |
-
rb"os\.system", rb"os\.popen", rb"subprocess", rb"eval\(", rb"exec\(",
|
| 94 |
-
rb"__import__", rb"pty\.spawn", rb"shutil\.rmtree", rb"sys\.exit"
|
| 95 |
-
]
|
| 96 |
-
|
| 97 |
@staticmethod
|
| 98 |
-
def
|
|
|
|
| 99 |
try:
|
| 100 |
-
with open(file_path, '
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
return
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
@staticmethod
|
| 119 |
-
def
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
@staticmethod
|
| 126 |
-
def run_container(proj_id, file_path, file_type):
|
| 127 |
-
if not DockerManager.check_system():
|
| 128 |
-
return False, "⚠️ نظام Docker غير متصل بالسيرفر."
|
| 129 |
-
|
| 130 |
-
container_name = f"wolf_{proj_id}"
|
| 131 |
-
proj_dir = os.path.dirname(os.path.abspath(file_path))
|
| 132 |
-
file_name = os.path.basename(file_path)
|
| 133 |
-
|
| 134 |
-
DockerManager.remove_container(proj_id)
|
| 135 |
-
|
| 136 |
-
# القيود الذكية حسب الطلب + خاصية Auto Restart
|
| 137 |
-
cmd =[
|
| 138 |
-
'docker', 'run', '-d',
|
| 139 |
-
'--name', container_name,
|
| 140 |
-
'--memory=256m',
|
| 141 |
-
'--cpus=0.5',
|
| 142 |
-
'--pids-limit=64',
|
| 143 |
-
'--network=bridge',
|
| 144 |
-
'--restart=on-failure:5',
|
| 145 |
-
'-v', f"{proj_dir}:/app",
|
| 146 |
-
'-w', '/app'
|
| 147 |
-
]
|
| 148 |
-
|
| 149 |
-
if file_type == 'py':
|
| 150 |
-
req_path = os.path.join(proj_dir, 'requirements.txt')
|
| 151 |
-
pip_cmd = "pip install -r requirements.txt > /dev/null 2>&1" if os.path.exists(req_path) else "pip install --quiet pyTelegramBotAPI requests aiohttp python-dotenv > /dev/null 2>&1"
|
| 152 |
-
cmd.extend(['python:3.10-slim', 'sh', '-c', f"{pip_cmd} && python -u {file_name}"])
|
| 153 |
-
else:
|
| 154 |
-
cmd.extend(['node:18-alpine', 'sh', '-c', f"npm install --quiet > /dev/null 2>&1 && node {file_name}"])
|
| 155 |
-
|
| 156 |
try:
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
except
|
| 160 |
-
return False, "⚠️ فشل بدء حاوية المشروع."
|
| 161 |
-
|
| 162 |
-
@staticmethod
|
| 163 |
-
def stop_container(proj_id):
|
| 164 |
-
subprocess.run(['docker', 'stop', '-t', '2', f"wolf_{proj_id}"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 165 |
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
| 169 |
|
| 170 |
-
@staticmethod
|
| 171 |
-
def get_logs(proj_id):
|
| 172 |
try:
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
@staticmethod
|
| 179 |
-
def
|
|
|
|
| 180 |
try:
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
if status == 'exited': return '🔴 متوقف'
|
| 185 |
-
if status == 'restarting': return '⏳ يعيد التشغيل'
|
| 186 |
-
return f"⚪ {status}"
|
| 187 |
-
except: return "⚪ غير متصل"
|
| 188 |
-
|
| 189 |
-
class UIEngine:
|
| 190 |
-
"""محرك واجهة المستخدم المتطور"""
|
| 191 |
-
@staticmethod
|
| 192 |
-
def safe_send(chat_id, text, markup=None):
|
| 193 |
-
try: return bot.send_message(chat_id, text, reply_markup=markup, parse_mode='Markdown')
|
| 194 |
-
except: pass
|
| 195 |
-
|
| 196 |
-
@staticmethod
|
| 197 |
-
def safe_edit(call, text, markup=None):
|
| 198 |
-
try: bot.edit_message_text(text, call.message.chat.id, call.message.message_id, reply_markup=markup, parse_mode='Markdown')
|
| 199 |
except: pass
|
| 200 |
|
| 201 |
@staticmethod
|
| 202 |
-
def
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
@staticmethod
|
| 206 |
-
def
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
@staticmethod
|
| 225 |
-
def
|
| 226 |
markup = types.InlineKeyboardMarkup(row_width=2)
|
| 227 |
-
markup.add(
|
| 228 |
-
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
return markup
|
| 231 |
|
| 232 |
@staticmethod
|
| 233 |
-
def
|
| 234 |
markup = types.InlineKeyboardMarkup(row_width=2)
|
| 235 |
-
if
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
markup.add(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
return markup
|
| 242 |
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
user_states = {}
|
| 246 |
|
| 247 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
|
| 249 |
@bot.message_handler(commands=['start'])
|
| 250 |
-
def
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
text = (
|
| 256 |
-
f"
|
| 257 |
-
"
|
| 258 |
-
"
|
| 259 |
-
"
|
| 260 |
-
"اختر من القائمة أدناه للبدء:"
|
| 261 |
)
|
| 262 |
-
|
| 263 |
|
| 264 |
-
@bot.
|
| 265 |
-
def
|
| 266 |
-
|
| 267 |
-
|
|
|
|
| 268 |
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
limit = 1 if user.get('plan') != 'vip' else 10
|
| 272 |
-
if uid == ADMIN_ID: limit = 999
|
| 273 |
-
|
| 274 |
-
if len(projs) >= limit:
|
| 275 |
-
UIEngine.safe_send(msg.chat.id, "⚠️ **وصلت للحد الأقصى للمشاريع المسموحة في باقتك.**")
|
| 276 |
-
user_states.pop(uid, None)
|
| 277 |
-
return
|
| 278 |
-
|
| 279 |
-
fname = msg.document.file_name
|
| 280 |
-
if not (fname.endswith('.py') or fname.endswith('.js') or fname.endswith('.zip')):
|
| 281 |
-
UIEngine.safe_send(msg.chat.id, "⚠️ **عذراً،** النظام يدعم ملفات `.py`, `.js`, و `.zip` فقط.")
|
| 282 |
-
return
|
| 283 |
-
|
| 284 |
-
UIEngine.safe_send(msg.chat.id, "⏳ جاري تحميل وفحص الملف بأمان...")
|
| 285 |
-
|
| 286 |
-
try:
|
| 287 |
-
file_info = bot.get_file(msg.document.file_id)
|
| 288 |
-
content = bot.download_file(file_info.file_path)
|
| 289 |
-
except:
|
| 290 |
-
return UIEngine.safe_send(msg.chat.id, "❌ حدث خطأ أثناء جلب الملف من تيليجرام.")
|
| 291 |
-
|
| 292 |
-
proj_id = str(uuid.uuid4())[:8]
|
| 293 |
-
user_dir = os.path.join(HOSTING_DIR, str(uid))
|
| 294 |
-
os.makedirs(user_dir, exist_ok=True)
|
| 295 |
-
tmp_path = os.path.join(user_dir, f"tmp_{proj_id}_{fname}")
|
| 296 |
-
|
| 297 |
-
with open(tmp_path, 'wb') as f: f.write(content)
|
| 298 |
-
|
| 299 |
-
# معالجة ملفات ZIP
|
| 300 |
-
if fname.endswith('.zip'):
|
| 301 |
-
extract_dir = os.path.join(user_dir, proj_id)
|
| 302 |
-
with zipfile.ZipFile(tmp_path, 'r') as zf: zf.extractall(extract_dir)
|
| 303 |
-
os.remove(tmp_path)
|
| 304 |
-
|
| 305 |
-
main_file = next((os.path.join(r, f) for r, d, files in os.walk(extract_dir) for f in files if f in['main.py', 'bot.py', 'index.js']), None)
|
| 306 |
-
if not main_file:
|
| 307 |
-
shutil.rmtree(extract_dir)
|
| 308 |
-
return UIEngine.safe_send(msg.chat.id, "⚠️ **لم يتم العثور على ملف التشغيل.** يجب أن يحتوي المجلد على `main.py` أو `bot.py` أو `index.js`.")
|
| 309 |
-
|
| 310 |
-
for r, d, files in os.walk(extract_dir):
|
| 311 |
-
for f in files:
|
| 312 |
-
if f.endswith('.py') or f.endswith('.js'):
|
| 313 |
-
safe, sec_msg = SecurityScanner.scan_file(os.path.join(r, f))
|
| 314 |
-
if not safe:
|
| 315 |
-
shutil.rmtree(extract_dir)
|
| 316 |
-
return UIEngine.safe_send(msg.chat.id, f"🚫 **تم رفض الكود لاحتوائه على ثغرة أو أمر خطير:**\n{sec_msg}")
|
| 317 |
-
|
| 318 |
-
final_path = main_file
|
| 319 |
-
fname = os.path.basename(main_file)
|
| 320 |
-
else:
|
| 321 |
-
# معالجة ملف فردي
|
| 322 |
-
safe, sec_msg = SecurityScanner.scan_file(tmp_path)
|
| 323 |
-
if not safe:
|
| 324 |
-
os.remove(tmp_path)
|
| 325 |
-
return UIEngine.safe_send(msg.chat.id, f"🚫 **مرفوض:**\n{sec_msg}")
|
| 326 |
-
|
| 327 |
-
final_path = os.path.join(user_dir, f"{proj_id}_{fname}")
|
| 328 |
-
os.rename(tmp_path, final_path)
|
| 329 |
-
|
| 330 |
-
file_type = 'py' if fname.endswith('.py') else 'js'
|
| 331 |
-
db.add_project(proj_id, uid, fname, file_type, final_path)
|
| 332 |
-
user_states.pop(uid, None)
|
| 333 |
-
|
| 334 |
-
markup = types.InlineKeyboardMarkup().add(
|
| 335 |
-
UIEngine.btn("▶️ تشغيل الآن", f"proj_start_{proj_id}"),
|
| 336 |
-
UIEngine.btn("🔙 القائمة", "main_menu")
|
| 337 |
-
)
|
| 338 |
-
UIEngine.safe_send(msg.chat.id, "✅ **تم معالجة ورفع المشروع بأمان!**\nهو الآن معزول بالكامل وجاهز للاستخدام.", markup)
|
| 339 |
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
data = call.data
|
| 344 |
-
user = db.get_user(uid)
|
| 345 |
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
|
| 354 |
-
elif
|
| 355 |
-
|
| 356 |
-
|
|
|
|
| 357 |
|
|
|
|
| 358 |
markup = types.InlineKeyboardMarkup(row_width=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
for p in projs:
|
| 360 |
-
icon = "🟢" if '
|
| 361 |
-
markup.add(
|
| 362 |
-
markup.add(
|
| 363 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 369 |
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
elif data.startswith("proj_start_"):
|
| 380 |
-
pid = data.split("_")[2]
|
| 381 |
-
p = db.get_project(pid)
|
| 382 |
-
UIEngine.loading(call, "⏳ جاري إعداد وتجهيز الحاوية المعزولة...")
|
| 383 |
-
success, msg = DockerManager.run_container(pid, p['path'], p['file_type'])
|
| 384 |
-
bot.answer_callback_query(call.id, msg, show_alert=not success)
|
| 385 |
-
|
| 386 |
-
call.data = f"proj_view_{pid}"
|
| 387 |
-
handle_callbacks(call)
|
| 388 |
-
|
| 389 |
-
elif data.startswith("proj_stop_"):
|
| 390 |
-
pid = data.split("_")[2]
|
| 391 |
-
UIEngine.loading(call, "🛑 جاري إيقاف العملية بأمان...")
|
| 392 |
-
DockerManager.stop_container(pid)
|
| 393 |
-
bot.answer_callback_query(call.id, "✅ تم إيقاف المشروع.")
|
| 394 |
-
|
| 395 |
-
call.data = f"proj_view_{pid}"
|
| 396 |
-
handle_callbacks(call)
|
| 397 |
-
|
| 398 |
-
elif data.startswith("proj_restart_"):
|
| 399 |
-
pid = data.split("_")[2]
|
| 400 |
-
p = db.get_project(pid)
|
| 401 |
-
UIEngine.loading(call, "🔄 جاري إعادة الإقلاع...")
|
| 402 |
-
DockerManager.run_container(pid, p['path'], p['file_type'])
|
| 403 |
-
bot.answer_callback_query(call.id, "✅ تمت إعادة التشغيل.")
|
| 404 |
-
|
| 405 |
-
call.data = f"proj_view_{pid}"
|
| 406 |
-
handle_callbacks(call)
|
| 407 |
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
|
|
|
|
|
|
| 450 |
)
|
| 451 |
-
|
|
|
|
| 452 |
|
| 453 |
-
elif
|
| 454 |
-
|
| 455 |
-
|
|
|
|
| 456 |
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
f"🐳 **حالة محرك Docker:** `{'نشط 🟢' if DockerManager.check_system() else 'مغلق 🔴'}`\n"
|
| 462 |
-
)
|
| 463 |
-
UIEngine.safe_edit(call, text, types.InlineKeyboardMarkup().add(UIEngine.btn("🔙 القائمة", "main_menu")))
|
| 464 |
|
| 465 |
-
elif data == "ui_admin":
|
| 466 |
-
if uid != ADMIN_ID: return
|
| 467 |
-
users_count = db._get_conn().execute("SELECT COUNT(*) FROM users").fetchone()[0]
|
| 468 |
-
projs_count = db._get_conn().execute("SELECT COUNT(*) FROM projects").fetchone()[0]
|
| 469 |
-
|
| 470 |
text = (
|
| 471 |
-
f"
|
| 472 |
-
f"👥
|
| 473 |
-
f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 474 |
)
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
|
|
|
|
|
|
|
|
|
| 495 |
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 504 |
if __name__ == '__main__':
|
| 505 |
-
|
| 506 |
try:
|
| 507 |
-
bot.infinity_polling(timeout=60,
|
| 508 |
except Exception as e:
|
| 509 |
-
|
|
|
|
| 1 |
+
import telebot
|
| 2 |
+
from telebot import types
|
| 3 |
+
import docker
|
| 4 |
+
import sqlite3
|
| 5 |
+
import threading
|
| 6 |
import os
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
import uuid
|
| 10 |
+
import json
|
| 11 |
+
import psutil
|
| 12 |
import zipfile
|
| 13 |
+
import shutil
|
| 14 |
+
import ast
|
| 15 |
+
import random
|
| 16 |
+
import string
|
| 17 |
import logging
|
| 18 |
+
from datetime import datetime, timedelta
|
| 19 |
+
from apscheduler.schedulers.background import BackgroundScheduler
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
# ==========================================
|
| 22 |
+
# ⚙️ الإعدادات الأساسية (Configuration)
|
| 23 |
+
# ==========================================
|
| 24 |
TOKEN = '7847673598:AAGeqJb591uZWCwpSqS8VJGWTRtDOr0CTEE'
|
| 25 |
ADMIN_ID = 6812997550
|
| 26 |
+
YOUR_USERNAME = '@EQJ_1'
|
| 27 |
+
CHANNELS =['@EQJ_1']
|
| 28 |
|
| 29 |
+
HOSTING_DIR = 'wolf_projects'
|
| 30 |
+
BACKUP_DIR = 'wolf_backups'
|
| 31 |
+
DB_NAME = 'whitewolf_cloud.db'
|
| 32 |
+
VERSION = '6.0.0 Ultimate Docker Edition'
|
| 33 |
|
| 34 |
+
# إنشاء مسارات النظام
|
| 35 |
+
for d in [HOSTING_DIR, BACKUP_DIR]:
|
| 36 |
+
os.makedirs(d, exist_ok=True)
|
| 37 |
|
| 38 |
+
# إعداد السجلات
|
|
|
|
| 39 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 40 |
+
logger = logging.getLogger("WhiteWolf-Cloud")
|
| 41 |
+
|
| 42 |
+
bot = telebot.TeleBot(TOKEN, parse_mode="Markdown")
|
| 43 |
+
|
| 44 |
+
# الاتصال بـ Docker
|
| 45 |
+
try:
|
| 46 |
+
docker_client = docker.from_env()
|
| 47 |
+
logger.info("✅ تم الاتصال بمحرك Docker بنجاح!")
|
| 48 |
+
except Exception as e:
|
| 49 |
+
logger.error(f"❌ فشل الاتصال بـ Docker: {e}")
|
| 50 |
+
docker_client = None
|
| 51 |
+
|
| 52 |
+
# ==========================================
|
| 53 |
+
# 📊 الخطط والأسعار (Plans & Pricing)
|
| 54 |
+
# ==========================================
|
| 55 |
+
PLAN_LIMITS = {
|
| 56 |
+
'free': {'projects': 1, 'label': '🆓 مجاني', 'price': 0, 'ram': '50m'},
|
| 57 |
+
'silver': {'projects': 3, 'label': '🥈 فضي', 'price': 10, 'ram': '100m'},
|
| 58 |
+
'gold': {'projects': 5, 'label': '🥇 ذهبي', 'price': 25, 'ram': '250m'},
|
| 59 |
+
'diamond': {'projects': 10, 'label': '💎 ماسي', 'price': 50, 'ram': '512m'},
|
| 60 |
+
}
|
| 61 |
+
INVITE_REWARD = 2
|
| 62 |
+
|
| 63 |
+
# ==========================================
|
| 64 |
+
# 🗄️ محرك قاعدة البيانات (Database Engine)
|
| 65 |
+
# ==========================================
|
| 66 |
+
class DatabaseEngine:
|
| 67 |
+
def __init__(self):
|
| 68 |
+
self.lock = threading.Lock()
|
| 69 |
+
self.init_db()
|
| 70 |
+
|
| 71 |
+
def get_conn(self):
|
| 72 |
+
conn = sqlite3.connect(DB_NAME, check_same_thread=False)
|
| 73 |
conn.row_factory = sqlite3.Row
|
| 74 |
return conn
|
| 75 |
|
| 76 |
+
def init_db(self):
|
| 77 |
+
with self.lock, self.get_conn() as conn:
|
| 78 |
+
c = conn.cursor()
|
| 79 |
c.execute('''CREATE TABLE IF NOT EXISTS users (
|
| 80 |
+
user_id INTEGER PRIMARY KEY, username TEXT, points INTEGER DEFAULT 0,
|
| 81 |
+
plan TEXT DEFAULT 'free', plan_expires TIMESTAMP, is_vip INTEGER DEFAULT 0,
|
| 82 |
+
total_invites INTEGER DEFAULT 0, is_banned INTEGER DEFAULT 0, joined_at TIMESTAMP
|
| 83 |
)''')
|
| 84 |
c.execute('''CREATE TABLE IF NOT EXISTS projects (
|
| 85 |
+
project_id TEXT PRIMARY KEY, user_id INTEGER, file_name TEXT, path TEXT,
|
| 86 |
+
container_id TEXT, status TEXT DEFAULT 'pending', auto_restart INTEGER DEFAULT 1,
|
| 87 |
+
env_vars TEXT DEFAULT '{}', created_at TIMESTAMP
|
| 88 |
)''')
|
| 89 |
+
c.execute('''CREATE TABLE IF NOT EXISTS coupons (
|
| 90 |
+
code TEXT PRIMARY KEY, value INTEGER, max_uses INTEGER, used_count INTEGER DEFAULT 0
|
| 91 |
+
)''')
|
| 92 |
+
c.execute('''CREATE TABLE IF NOT EXISTS templates (
|
| 93 |
+
id TEXT PRIMARY KEY, name TEXT, desc TEXT, path TEXT, downloads INTEGER DEFAULT 0
|
| 94 |
+
)''')
|
| 95 |
+
conn.commit()
|
| 96 |
+
|
| 97 |
+
def add_user(self, user_id, username):
|
| 98 |
+
with self.lock, self.get_conn() as conn:
|
| 99 |
+
conn.execute('INSERT OR IGNORE INTO users (user_id, username, joined_at) VALUES (?, ?, ?)',
|
| 100 |
+
(user_id, username, datetime.now()))
|
| 101 |
+
conn.commit()
|
| 102 |
+
|
| 103 |
+
def get_user(self, user_id):
|
| 104 |
+
with self.get_conn() as conn:
|
| 105 |
+
return conn.execute('SELECT * FROM users WHERE user_id = ?', (user_id,)).fetchone()
|
| 106 |
+
|
| 107 |
+
def add_points(self, user_id, amount):
|
| 108 |
+
with self.lock, self.get_conn() as conn:
|
| 109 |
+
conn.execute('UPDATE users SET points = points + ? WHERE user_id = ?', (amount, user_id))
|
| 110 |
+
conn.commit()
|
| 111 |
+
|
| 112 |
+
def deduct_points(self, user_id, amount):
|
| 113 |
+
with self.lock, self.get_conn() as conn:
|
| 114 |
+
conn.execute('UPDATE users SET points = points - ? WHERE user_id = ?', (amount, user_id))
|
| 115 |
+
conn.commit()
|
| 116 |
+
|
| 117 |
+
def set_plan(self, user_id, plan, days=30):
|
| 118 |
+
expires = datetime.now() + timedelta(days=days)
|
| 119 |
+
with self.lock, self.get_conn() as conn:
|
| 120 |
+
conn.execute('UPDATE users SET plan = ?, plan_expires = ? WHERE user_id = ?', (plan, expires, user_id))
|
| 121 |
+
conn.commit()
|
| 122 |
+
|
| 123 |
+
def get_projects(self, user_id=None):
|
| 124 |
+
with self.get_conn() as conn:
|
| 125 |
+
if user_id: return conn.execute('SELECT * FROM projects WHERE user_id = ?', (user_id,)).fetchall()
|
| 126 |
+
return conn.execute('SELECT * FROM projects').fetchall()
|
| 127 |
+
|
| 128 |
+
def update_project_status(self, project_id, container_id, status):
|
| 129 |
+
with self.lock, self.get_conn() as conn:
|
| 130 |
+
conn.execute('UPDATE projects SET container_id = ?, status = ? WHERE project_id = ?',
|
| 131 |
+
(container_id, status, project_id))
|
| 132 |
+
conn.commit()
|
| 133 |
+
|
| 134 |
+
def delete_project(self, project_id):
|
| 135 |
+
with self.lock, self.get_conn() as conn:
|
| 136 |
+
conn.execute('DELETE FROM projects WHERE project_id = ?', (project_id,))
|
| 137 |
+
conn.commit()
|
| 138 |
+
|
| 139 |
+
db = DatabaseEngine()
|
| 140 |
+
|
| 141 |
+
# ==========================================
|
| 142 |
+
# 🛡️ محرك الأمان (Security Scanner)
|
| 143 |
+
# ==========================================
|
| 144 |
class SecurityScanner:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
@staticmethod
|
| 146 |
+
def is_safe_code(file_path, user_id):
|
| 147 |
+
if user_id == ADMIN_ID: return True, "Admin Bypass"
|
| 148 |
try:
|
| 149 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 150 |
+
tree = ast.parse(f.read())
|
| 151 |
+
banned_imports =['os', 'subprocess', 'pty', 'shutil', 'socket', 'sys']
|
| 152 |
+
banned_funcs =['eval', 'exec', 'open', 'system', 'popen']
|
| 153 |
+
for node in ast.walk(tree):
|
| 154 |
+
if isinstance(node, ast.Import):
|
| 155 |
+
for alias in node.names:
|
| 156 |
+
if alias.name in banned_imports: return False, f"مكتبة ممنوعة أمنياً: {alias.name}"
|
| 157 |
+
elif isinstance(node, ast.Call) and getattr(node.func, 'id', '') in banned_funcs:
|
| 158 |
+
return False, f"دالة خطيرة ممنوعة: {node.func.id}"
|
| 159 |
+
return True, "Safe"
|
| 160 |
+
except Exception as e:
|
| 161 |
+
return False, f"خطأ في بناء الكود: {str(e)[:50]}"
|
| 162 |
+
|
| 163 |
+
# ==========================================
|
| 164 |
+
# 🐳 محرك الدوكر السحابي (Docker Engine)
|
| 165 |
+
# ==========================================
|
| 166 |
+
class DockerEngine:
|
| 167 |
@staticmethod
|
| 168 |
+
def deploy(project_id, file_path, ram_limit, env_vars_str, auto_restart):
|
| 169 |
+
if not docker_client: return False, "نظام Docker معطل."
|
| 170 |
+
container_name = f"wolf_{project_id}"
|
| 171 |
+
|
| 172 |
+
# تنظيف الحاوية السابقة إن وجدت
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
try:
|
| 174 |
+
old = docker_client.containers.get(container_name)
|
| 175 |
+
old.remove(force=True)
|
| 176 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
+
abs_path = os.path.abspath(file_path)
|
| 179 |
+
project_dir = os.path.dirname(abs_path)
|
| 180 |
+
file_name = os.path.basename(abs_path)
|
| 181 |
+
env_dict = json.loads(env_vars_str) if env_vars_str else {}
|
| 182 |
+
restart_policy = {"Name": "always"} if auto_restart else {"Name": "no"}
|
| 183 |
|
|
|
|
|
|
|
| 184 |
try:
|
| 185 |
+
container = docker_client.containers.run(
|
| 186 |
+
"python:3.10-slim",
|
| 187 |
+
command=f"sh -c 'pip install -q pyTelegramBotAPI telebot requests bs4 numpy && python {file_name}'",
|
| 188 |
+
name=container_name,
|
| 189 |
+
volumes={project_dir: {'bind': '/app', 'mode': 'ro'}},
|
| 190 |
+
working_dir='/app',
|
| 191 |
+
environment=env_dict,
|
| 192 |
+
mem_limit=ram_limit,
|
| 193 |
+
restart_policy=restart_policy,
|
| 194 |
+
detach=True
|
| 195 |
+
)
|
| 196 |
+
return True, container.id
|
| 197 |
+
except Exception as e:
|
| 198 |
+
logger.error(f"Deploy Error: {e}")
|
| 199 |
+
return False, str(e)
|
| 200 |
|
| 201 |
@staticmethod
|
| 202 |
+
def stop_and_remove(project_id):
|
| 203 |
+
if not docker_client: return
|
| 204 |
try:
|
| 205 |
+
container = docker_client.containers.get(f"wolf_{project_id}")
|
| 206 |
+
container.stop(timeout=3)
|
| 207 |
+
container.remove(force=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
except: pass
|
| 209 |
|
| 210 |
@staticmethod
|
| 211 |
+
def get_logs(project_id):
|
| 212 |
+
if not docker_client: return "بدون سجلات."
|
| 213 |
+
try:
|
| 214 |
+
container = docker_client.containers.get(f"wolf_{project_id}")
|
| 215 |
+
return container.logs(tail=25).decode('utf-8', errors='ignore')
|
| 216 |
+
except: return "الحاوية لا تعمل أو لا توجد سجلات."
|
| 217 |
|
| 218 |
@staticmethod
|
| 219 |
+
def get_stats(project_id):
|
| 220 |
+
if not docker_client: return "N/A"
|
| 221 |
+
try:
|
| 222 |
+
container = docker_client.containers.get(f"wolf_{project_id}")
|
| 223 |
+
if container.status != 'running': return "متوقف 🔴"
|
| 224 |
+
stats = container.stats(stream=False)
|
| 225 |
+
ram_usage = stats['memory_stats'].get('usage', 0) / (1024 * 1024)
|
| 226 |
+
cpu_delta = stats['cpu_stats']['cpu_usage']['total_usage'] - stats['precpu_stats']['cpu_usage']['total_usage']
|
| 227 |
+
sys_delta = stats['cpu_stats']['system_cpu_usage'] - stats['precpu_stats']['system_cpu_usage']
|
| 228 |
+
cpu_percent = (cpu_delta / sys_delta) * stats['cpu_stats']['online_cpus'] * 100 if sys_delta > 0 else 0
|
| 229 |
+
return f"🟢 يعمل | RAM: {ram_usage:.1f}MB | CPU: {cpu_percent:.1f}%"
|
| 230 |
+
except: return "غير متاح"
|
| 231 |
+
|
| 232 |
+
# ==========================================
|
| 233 |
+
# 🎨 واجهة المستخدم (UI Engine)
|
| 234 |
+
# ==========================================
|
| 235 |
+
class UI:
|
|
|
|
| 236 |
@staticmethod
|
| 237 |
+
def main_menu(user_id):
|
| 238 |
markup = types.InlineKeyboardMarkup(row_width=2)
|
| 239 |
+
markup.add(
|
| 240 |
+
types.InlineKeyboardButton("📤 رفع مشروع (Deploy)", callback_data="ui_upload"),
|
| 241 |
+
types.InlineKeyboardButton("📋 إدارة مشاريعي", callback_data="ui_projects"),
|
| 242 |
+
types.InlineKeyboardButton("👤 حسابي", callback_data="ui_profile"),
|
| 243 |
+
types.InlineKeyboardButton("🛒 المتجر", callback_data="ui_store"),
|
| 244 |
+
types.InlineKeyboardButton("🔗 كسب نقاط", callback_data="ui_earn"),
|
| 245 |
+
types.InlineKeyboardButton("🎟️ استرداد كوبون", callback_data="ui_coupon"),
|
| 246 |
+
types.InlineKeyboardButton("📚 القوالب الجاهزة", callback_data="ui_templates"),
|
| 247 |
+
types.InlineKeyboardButton("👨💻 الدعم", url=f"https://t.me/{YOUR_USERNAME[1:]}")
|
| 248 |
+
)
|
| 249 |
+
if user_id == ADMIN_ID:
|
| 250 |
+
markup.add(types.InlineKeyboardButton("🛡️ لوحة المطور (Admin)", callback_data="admin_root"))
|
| 251 |
return markup
|
| 252 |
|
| 253 |
@staticmethod
|
| 254 |
+
def project_ctrl(project_id, status, auto_restart):
|
| 255 |
markup = types.InlineKeyboardMarkup(row_width=2)
|
| 256 |
+
if status == 'running':
|
| 257 |
+
markup.add(types.InlineKeyboardButton("🛑 إيقاف الحاوية", callback_data=f"p_stop_{project_id}"))
|
| 258 |
+
else:
|
| 259 |
+
markup.add(types.InlineKeyboardButton("▶️ تشغيل الحاوية", callback_data=f"p_start_{project_id}"))
|
| 260 |
+
|
| 261 |
+
markup.add(
|
| 262 |
+
types.InlineKeyboardButton("📋 السجلات (Logs)", callback_data=f"p_logs_{project_id}"),
|
| 263 |
+
types.InlineKeyboardButton("🔄 ريستارت", callback_data=f"p_restart_{project_id}"),
|
| 264 |
+
types.InlineKeyboardButton("🌍 المتغيرات (ENV)", callback_data=f"p_env_{project_id}"),
|
| 265 |
+
types.InlineKeyboardButton("📊 الإحصائيات الحية", callback_data=f"p_stats_{project_id}")
|
| 266 |
+
)
|
| 267 |
+
ar_text = "🔁 إيقاف الريستارت التلقائي" if auto_restart else "🔁 تفعيل الريستارت التلقائي"
|
| 268 |
+
markup.add(
|
| 269 |
+
types.InlineKeyboardButton(ar_text, callback_data=f"p_ar_{project_id}"),
|
| 270 |
+
types.InlineKeyboardButton("🗑️ حذف المشروع", callback_data=f"p_del_{project_id}")
|
| 271 |
+
)
|
| 272 |
+
markup.add(types.InlineKeyboardButton("🔙 رجوع", callback_data="ui_projects"))
|
| 273 |
return markup
|
| 274 |
|
| 275 |
+
@staticmethod
|
| 276 |
+
def back(callback_data="ui_main"):
|
| 277 |
+
return types.InlineKeyboardMarkup().add(types.InlineKeyboardButton("🔙 رجوع", callback_data=callback_data))
|
| 278 |
+
|
| 279 |
+
# ==========================================
|
| 280 |
+
# 🤖 دوال الاستقبال (Bot Handlers)
|
| 281 |
+
# ==========================================
|
| 282 |
user_states = {}
|
| 283 |
|
| 284 |
+
def check_sub(user_id):
|
| 285 |
+
if user_id == ADMIN_ID: return True
|
| 286 |
+
user = db.get_user(user_id)
|
| 287 |
+
if user and user['is_vip']: return True
|
| 288 |
+
for ch in CHANNELS:
|
| 289 |
+
try:
|
| 290 |
+
status = bot.get_chat_member(ch, user_id).status
|
| 291 |
+
if status not in ['member', 'administrator', 'creator']: return False
|
| 292 |
+
except: return False
|
| 293 |
+
return True
|
| 294 |
|
| 295 |
@bot.message_handler(commands=['start'])
|
| 296 |
+
def start_cmd(message):
|
| 297 |
+
user_id = message.from_user.id
|
| 298 |
+
username = message.from_user.username or f"User{user_id}"
|
| 299 |
+
db.add_user(user_id, username)
|
| 300 |
+
user = db.get_user(user_id)
|
| 301 |
+
|
| 302 |
+
if user['is_banned']:
|
| 303 |
+
return bot.reply_to(message, "🚫 حسابك محظور من استخدام النظام הסحابي.")
|
| 304 |
+
|
| 305 |
+
if not check_sub(user_id):
|
| 306 |
+
markup = types.InlineKeyboardMarkup()
|
| 307 |
+
for ch in CHANNELS: markup.add(types.InlineKeyboardButton("📡 اشترك هنا أولاً", url=f"https://t.me/{ch[1:]}"))
|
| 308 |
+
markup.add(types.InlineKeyboardButton("✅ تم الاشتراك", callback_data="ui_main"))
|
| 309 |
+
return bot.send_message(user_id, "⚠️ **يجب الاشتراك في القناة لاستخدام الاستضافة:**", reply_markup=markup)
|
| 310 |
+
|
| 311 |
+
# نظام الإحالة (Referral)
|
| 312 |
+
args = message.text.split()
|
| 313 |
+
if len(args) > 1 and args[1].isdigit():
|
| 314 |
+
inviter = int(args[1])
|
| 315 |
+
if inviter != user_id and not user['total_invites']: # استخدمناها كعلامة للـ rewarded
|
| 316 |
+
db.add_points(inviter, INVITE_REWARD)
|
| 317 |
+
with db.get_conn() as c:
|
| 318 |
+
c.execute('UPDATE users SET total_invites = total_invites + 1 WHERE user_id = ?', (inviter,))
|
| 319 |
+
c.execute('UPDATE users SET total_invites = -1 WHERE user_id = ?', (user_id,)) # علامة أنه دُعي
|
| 320 |
+
c.commit()
|
| 321 |
+
bot.send_message(inviter, f"🎉 لقد ربحت {INVITE_REWARD} نقطة لدعوتك مستخدم جديد!")
|
| 322 |
+
|
| 323 |
+
plan_name = PLAN_LIMITS.get(user['plan'], PLAN_LIMITS['free'])['label']
|
| 324 |
text = (
|
| 325 |
+
f"🐺 **مرحباً بك في White Wolf Cloud**\n\n"
|
| 326 |
+
f"أقوى نظام استضافة سحابي مبني على معمارية **Docker Containers**.\n"
|
| 327 |
+
f"نوفر لك أقصى درجات الأمان، الاستقرار، والعمل 24/7.\n\n"
|
| 328 |
+
f"📦 خطتك: {plan_name}"
|
|
|
|
| 329 |
)
|
| 330 |
+
bot.send_message(user_id, text, reply_markup=UI.main_menu(user_id))
|
| 331 |
|
| 332 |
+
@bot.callback_query_handler(func=lambda call: call.data.startswith("ui_"))
|
| 333 |
+
def ui_handler(call):
|
| 334 |
+
user_id = call.from_user.id
|
| 335 |
+
action = call.data[3:]
|
| 336 |
+
user = db.get_user(user_id)
|
| 337 |
|
| 338 |
+
if not check_sub(user_id):
|
| 339 |
+
return bot.answer_callback_query(call.id, "❌ يرجى الاشتراك بالقناة أولاً", show_alert=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
|
| 341 |
+
if action == "main":
|
| 342 |
+
plan_name = PLAN_LIMITS.get(user['plan'], PLAN_LIMITS['free'])['label']
|
| 343 |
+
safe_edit(call, f"🐺 **لوحة التحكم الرئيسية**\n📦 خطتك: {plan_name}", UI.main_menu(user_id))
|
|
|
|
|
|
|
| 344 |
|
| 345 |
+
elif action == "profile":
|
| 346 |
+
projs = db.get_projects(user_id)
|
| 347 |
+
plan_info = PLAN_LIMITS.get(user['plan'], PLAN_LIMITS['free'])
|
| 348 |
+
text = (
|
| 349 |
+
f"👤 **الملف الشخصي** {'💎 VIP' if user['is_vip'] else ''}\n\n"
|
| 350 |
+
f"🆔 الايدي: `{user_id}`\n"
|
| 351 |
+
f"💰 النقاط: `{user['points']}`\n"
|
| 352 |
+
f"📦 الخطة: {plan_info['label']}\n"
|
| 353 |
+
f"📂 المشاريع: `{len(projs)}/{plan_info['projects']}`\n"
|
| 354 |
+
f"🚀 الرام المسموح لكل مشروع: `{plan_info['ram']}`"
|
| 355 |
+
)
|
| 356 |
+
safe_edit(call, text, UI.back())
|
| 357 |
|
| 358 |
+
elif action == "earn":
|
| 359 |
+
link = f"https://t.me/{bot.get_me().username}?start={user_id}"
|
| 360 |
+
text = f"🔗 **رابط الدعوة الخاص بك:**\n`{link}`\n\n🎁 احصل على {INVITE_REWARD} نقطة لكل شخص يدخل."
|
| 361 |
+
safe_edit(call, text, UI.back())
|
| 362 |
|
| 363 |
+
elif action == "store":
|
| 364 |
markup = types.InlineKeyboardMarkup(row_width=1)
|
| 365 |
+
for k, v in PLAN_LIMITS.items():
|
| 366 |
+
if k == 'free': continue
|
| 367 |
+
markup.add(types.InlineKeyboardButton(f"{v['label']} | {v['projects']} مشاريع | {v['price']} نقطة", callback_data=f"buy_{k}"))
|
| 368 |
+
markup.add(types.InlineKeyboardButton("🔙 رجوع", callback_data="ui_main"))
|
| 369 |
+
safe_edit(call, f"🛒 **المتجر**\n💰 رصيدك: `{user['points']}` نقطة\nالمدة: 30 يوم.", markup)
|
| 370 |
+
|
| 371 |
+
elif action == "projects":
|
| 372 |
+
projs = db.get_projects(user_id)
|
| 373 |
+
if not projs: return bot.answer_callback_query(call.id, "📭 لا تمتلك أي مشاريع.", show_alert=True)
|
| 374 |
+
markup = types.InlineKeyboardMarkup()
|
| 375 |
for p in projs:
|
| 376 |
+
icon = "🟢" if p['status'] == 'running' else "🔴"
|
| 377 |
+
markup.add(types.InlineKeyboardButton(f"{icon} {p['file_name']}", callback_data=f"p_view_{p['project_id']}"))
|
| 378 |
+
markup.add(types.InlineKeyboardButton("🔙 رجوع", callback_data="ui_main"))
|
| 379 |
+
safe_edit(call, "📋 **قائمة مشاريعك السحابية:**", markup)
|
| 380 |
+
|
| 381 |
+
elif action == "upload":
|
| 382 |
+
limit = PLAN_LIMITS.get(user['plan'], PLAN_LIMITS['free'])['projects']
|
| 383 |
+
if len(db.get_projects(user_id)) >= limit and not user['is_vip'] and user_id != ADMIN_ID:
|
| 384 |
+
return bot.answer_callback_query(call.id, f"⚠️ وصلت للحد الأقصى ({limit}). قم بالترقية!", show_alert=True)
|
| 385 |
+
|
| 386 |
+
user_states[user_id] = 'upload'
|
| 387 |
+
safe_edit(call, "📤 **أرسل ملف المشروع الآن**\n(مسموح `.py` مفرد أو `.zip` لمشروع كامل)\n⌨️ أرسل /cancel للإلغاء", UI.back())
|
| 388 |
+
|
| 389 |
+
@bot.callback_query_handler(func=lambda call: call.data.startswith("buy_"))
|
| 390 |
+
def buy_plan(call):
|
| 391 |
+
plan_key = call.data[4:]
|
| 392 |
+
user = db.get_user(call.from_user.id)
|
| 393 |
+
price = PLAN_LIMITS[plan_key]['price']
|
| 394 |
+
|
| 395 |
+
if user['points'] < price:
|
| 396 |
+
return bot.answer_callback_query(call.id, f"❌ رصيدك غير كافٍ. تحتاج {price} نقطة.", show_alert=True)
|
| 397 |
+
|
| 398 |
+
db.deduct_points(user['user_id'], price)
|
| 399 |
+
db.set_plan(user['user_id'], plan_key)
|
| 400 |
+
bot.answer_callback_query(call.id, "✅ تم تفعيل الخطة بنجاح!", show_alert=True)
|
| 401 |
+
ui_handler(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data="ui_profile"))
|
| 402 |
+
|
| 403 |
+
# ==========================================
|
| 404 |
+
# 🚀 إدارة المشاريع السحابية (Project Control)
|
| 405 |
+
# ==========================================
|
| 406 |
+
@bot.callback_query_handler(func=lambda call: call.data.startswith("p_"))
|
| 407 |
+
def project_control(call):
|
| 408 |
+
user_id = call.from_user.id
|
| 409 |
+
parts = call.data.split('_')
|
| 410 |
+
action = parts[1]
|
| 411 |
+
project_id = parts[2]
|
| 412 |
+
|
| 413 |
+
with db.get_conn() as conn:
|
| 414 |
+
p = conn.execute('SELECT * FROM projects WHERE project_id = ?', (project_id,)).fetchone()
|
| 415 |
+
|
| 416 |
+
if not p or (p['user_id'] != user_id and user_id != ADMIN_ID):
|
| 417 |
+
return bot.answer_callback_query(call.id, "❌ المشروع غير موجود أو لا تملك صلاحية.", show_alert=True)
|
| 418 |
+
|
| 419 |
+
if action == "view":
|
| 420 |
+
stats = DockerEngine.get_stats(project_id) if p['status'] == 'running' else "متوقف 🔴"
|
| 421 |
+
text = f"📄 **معلومات المشروع:**\n📁 `{p['file_name']}`\n🆔 `{project_id}`\n📊 الحالة: {stats}"
|
| 422 |
+
safe_edit(call, text, UI.project_ctrl(project_id, p['status'], p['auto_restart']))
|
| 423 |
+
|
| 424 |
+
elif action == "start":
|
| 425 |
+
user = db.get_user(user_id)
|
| 426 |
+
ram_limit = PLAN_LIMITS.get(user['plan'], PLAN_LIMITS['free'])['ram']
|
| 427 |
+
success, cid = DockerEngine.deploy(project_id, p['path'], ram_limit, p['env_vars'], p['auto_restart'])
|
| 428 |
+
if success:
|
| 429 |
+
db.update_project_status(project_id, cid, 'running')
|
| 430 |
+
bot.answer_callback_query(call.id, "▶️ تم التشغيل في حاوية معزولة!")
|
| 431 |
+
else:
|
| 432 |
+
bot.answer_callback_query(call.id, f"❌ فشل: {cid}", show_alert=True)
|
| 433 |
+
project_control(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data=f"p_view_{project_id}"))
|
| 434 |
+
|
| 435 |
+
elif action == "stop":
|
| 436 |
+
DockerEngine.stop_and_remove(project_id)
|
| 437 |
+
db.update_project_status(project_id, None, 'stopped')
|
| 438 |
+
bot.answer_callback_query(call.id, "🛑 تم إيقاف الحاوية.")
|
| 439 |
+
project_control(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data=f"p_view_{project_id}"))
|
| 440 |
+
|
| 441 |
+
elif action == "restart":
|
| 442 |
+
bot.answer_callback_query(call.id, "🔄 جاري إعادة التشغيل...")
|
| 443 |
+
DockerEngine.stop_and_remove(project_id)
|
| 444 |
+
user = db.get_user(user_id)
|
| 445 |
+
ram_limit = PLAN_LIMITS.get(user['plan'], PLAN_LIMITS['free'])['ram']
|
| 446 |
+
success, cid = DockerEngine.deploy(project_id, p['path'], ram_limit, p['env_vars'], p['auto_restart'])
|
| 447 |
+
if success: db.update_project_status(project_id, cid, 'running')
|
| 448 |
+
project_control(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data=f"p_view_{project_id}"))
|
| 449 |
+
|
| 450 |
+
elif action == "logs":
|
| 451 |
+
logs = DockerEngine.get_logs(project_id)
|
| 452 |
+
safe_edit(call, f"📋 **السجلات (Logs):**\n```\n{logs[-3500:]}\n```", UI.back(f"p_view_{project_id}"))
|
| 453 |
+
|
| 454 |
+
elif action == "stats":
|
| 455 |
+
stats = DockerEngine.get_stats(project_id)
|
| 456 |
+
safe_edit(call, f"📊 **الموارد المستهلكة الآن:**\n{stats}", UI.back(f"p_view_{project_id}"))
|
| 457 |
+
|
| 458 |
+
elif action == "ar":
|
| 459 |
+
new_val = 0 if p['auto_restart'] else 1
|
| 460 |
+
with db.lock, db.get_conn() as conn:
|
| 461 |
+
conn.execute('UPDATE projects SET auto_restart = ? WHERE project_id = ?', (new_val, project_id))
|
| 462 |
+
conn.commit()
|
| 463 |
+
bot.answer_callback_query(call.id, "✅ تم التعديل.")
|
| 464 |
+
project_control(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data=f"p_view_{project_id}"))
|
| 465 |
+
|
| 466 |
+
elif action == "del":
|
| 467 |
+
DockerEngine.stop_and_remove(project_id)
|
| 468 |
+
try: shutil.rmtree(os.path.dirname(p['path'])) if os.path.isdir(os.path.dirname(p['path'])) else os.remove(p['path'])
|
| 469 |
+
except: pass
|
| 470 |
+
db.delete_project(project_id)
|
| 471 |
+
bot.answer_callback_query(call.id, "🗑️ تم الحذف نهائياً.", show_alert=True)
|
| 472 |
+
ui_handler(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data="ui_projects"))
|
| 473 |
|
| 474 |
+
# ==========================================
|
| 475 |
+
# 📤 نظام الرفع الذكي والمحمي (Upload Engine)
|
| 476 |
+
# ==========================================
|
| 477 |
+
@bot.message_handler(content_types=['document'])
|
| 478 |
+
def handle_docs(message):
|
| 479 |
+
user_id = message.from_user.id
|
| 480 |
+
if user_states.get(user_id) != 'upload': return
|
| 481 |
+
user_states.pop(user_id, None)
|
| 482 |
+
|
| 483 |
+
file_name = message.document.file_name
|
| 484 |
+
if not (file_name.endswith('.py') or file_name.endswith('.zip')):
|
| 485 |
+
return bot.reply_to(message, "❌ مسموح فقط بملفات `.py` أو `.zip`")
|
| 486 |
+
|
| 487 |
+
if message.document.file_size > 5 * 1024 * 1024:
|
| 488 |
+
return bot.reply_to(message, "❌ الحد الأقصى 5MB.")
|
| 489 |
|
| 490 |
+
msg = bot.reply_to(message, "⏳ جاري الفحص الأمني...")
|
| 491 |
+
project_id = str(uuid.uuid4())[:8]
|
| 492 |
+
proj_dir = os.path.join(HOSTING_DIR, f"{user_id}_{project_id}")
|
| 493 |
+
os.makedirs(proj_dir, exist_ok=True)
|
| 494 |
+
|
| 495 |
+
save_path = os.path.join(proj_dir, file_name)
|
| 496 |
+
downloaded = bot.download_file(bot.get_file(message.document.file_id).file_path)
|
| 497 |
+
|
| 498 |
+
with open(save_path, 'wb') as f: f.write(downloaded)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 499 |
|
| 500 |
+
main_file = save_path
|
| 501 |
+
if file_name.endswith('.zip'):
|
| 502 |
+
try:
|
| 503 |
+
with zipfile.ZipFile(save_path, 'r') as zf:
|
| 504 |
+
for member in zf.namelist():
|
| 505 |
+
if not os.path.realpath(os.path.join(proj_dir, member)).startswith(os.path.realpath(proj_dir)):
|
| 506 |
+
raise Exception("محاولة اختراق Zip Slip")
|
| 507 |
+
zf.extractall(proj_dir)
|
| 508 |
+
os.remove(save_path)
|
| 509 |
+
py_files = [f for f in os.listdir(proj_dir) if f.endswith('.py')]
|
| 510 |
+
if not py_files: raise Exception("لا يوجد ملف بايثون في הـ ZIP")
|
| 511 |
+
main_file = os.path.join(proj_dir, 'main.py' if 'main.py' in py_files else py_files[0])
|
| 512 |
+
file_name = os.path.basename(main_file)
|
| 513 |
+
except Exception as e:
|
| 514 |
+
shutil.rmtree(proj_dir)
|
| 515 |
+
return bot.edit_message_text(f"❌ خطأ بالملف المضغوط: {e}", message.chat.id, msg.message_id)
|
| 516 |
+
|
| 517 |
+
is_safe, reason = SecurityScanner.is_safe_code(main_file, user_id)
|
| 518 |
+
if not is_safe:
|
| 519 |
+
shutil.rmtree(proj_dir)
|
| 520 |
+
return bot.edit_message_text(f"🚨 **مرفوض أمنياً:**\n`{reason}`", message.chat.id, msg.message_id)
|
| 521 |
+
|
| 522 |
+
with db.lock, db.get_conn() as conn:
|
| 523 |
+
conn.execute('INSERT INTO projects (project_id, user_id, file_name, path, created_at) VALUES (?, ?, ?, ?, ?)',
|
| 524 |
+
(project_id, user_id, file_name, main_file, datetime.now()))
|
| 525 |
+
conn.commit()
|
| 526 |
+
|
| 527 |
+
bot.edit_message_text("✅ **تم قبول الكود وحفظه بنجاح!**\nاذهب إلى `مشاريعي` لتشغيله.", message.chat.id, msg.message_id, reply_markup=UI.main_menu(user_id))
|
| 528 |
+
|
| 529 |
+
# ==========================================
|
| 530 |
+
# 🛡️ لوحة المطور الأسطورية (Admin Panel)
|
| 531 |
+
# ==========================================
|
| 532 |
+
@bot.callback_query_handler(func=lambda call: call.data.startswith("admin_"))
|
| 533 |
+
def admin_panel(call):
|
| 534 |
+
if call.from_user.id != ADMIN_ID: return
|
| 535 |
+
action = call.data[6:]
|
| 536 |
+
|
| 537 |
+
if action == "root":
|
| 538 |
+
markup = types.InlineKeyboardMarkup(row_width=2)
|
| 539 |
+
markup.add(
|
| 540 |
+
types.InlineKeyboardButton("📊 إحصائيات النظام", callback_data="admin_stats"),
|
| 541 |
+
types.InlineKeyboardButton("📢 إذاعة للمستخدمين", callback_data="admin_bc"),
|
| 542 |
+
types.InlineKeyboardButton("🎁 إضافة كوبون", callback_data="admin_add_coupon"),
|
| 543 |
+
types.InlineKeyboardButton("🛑 إيقاف كل الحاويات", callback_data="admin_killall")
|
| 544 |
)
|
| 545 |
+
markup.add(types.InlineKeyboardButton("🔙 خروج من اللوحة", callback_data="ui_main"))
|
| 546 |
+
safe_edit(call, "🛡️ **لوحة التحكم المركزية السحابية**", markup)
|
| 547 |
|
| 548 |
+
elif action == "stats":
|
| 549 |
+
with db.get_conn() as conn:
|
| 550 |
+
users = conn.execute('SELECT COUNT(*) FROM users').fetchone()[0]
|
| 551 |
+
projs = conn.execute('SELECT COUNT(*) FROM projects').fetchone()[0]
|
| 552 |
|
| 553 |
+
cpu = psutil.cpu_percent()
|
| 554 |
+
ram = psutil.virtual_memory().percent
|
| 555 |
+
disk = psutil.disk_usage('/').percent
|
| 556 |
+
active_containers = len(docker_client.containers.list(filters={"name": "wolf_"})) if docker_client else 0
|
|
|
|
|
|
|
|
|
|
| 557 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
text = (
|
| 559 |
+
f"📊 **إحصائيات السيرفر السحابي**\n\n"
|
| 560 |
+
f"👥 المستخدمين: `{users}`\n"
|
| 561 |
+
f"📂 إجمالي المشاريع: `{projs}`\n"
|
| 562 |
+
f"🐳 الحاويات النشطة: `{active_containers}`\n\n"
|
| 563 |
+
f"🖥️ حالة الـ Host:\n"
|
| 564 |
+
f"🧠 المعالج: `{cpu}%`\n"
|
| 565 |
+
f"💾 الرام: `{ram}%`\n"
|
| 566 |
+
f"💿 التخزين: `{disk}%`"
|
| 567 |
)
|
| 568 |
+
safe_edit(call, text, UI.back("admin_root"))
|
| 569 |
+
|
| 570 |
+
elif action == "killall":
|
| 571 |
+
if docker_client:
|
| 572 |
+
for c in docker_client.containers.list(filters={"name": "wolf_"}): c.stop(timeout=1)
|
| 573 |
+
with db.lock, db.get_conn() as conn:
|
| 574 |
+
conn.execute('UPDATE projects SET status = "stopped", container_id = NULL')
|
| 575 |
+
conn.commit()
|
| 576 |
+
bot.answer_callback_query(call.id, "⚡ تم إعدام جميع الحاويات!", show_alert=True)
|
| 577 |
+
admin_panel(types.CallbackQuery(call.id, call.from_user, call.data, call.chat_instance, call.message, data="admin_root"))
|
| 578 |
+
|
| 579 |
+
# ==========================================
|
| 580 |
+
# 🕒 المهام المجدولة (Cron & Background)
|
| 581 |
+
# ==========================================
|
| 582 |
+
def system_maintenance():
|
| 583 |
+
# 1. تحديث الخطط المنتهية
|
| 584 |
+
with db.lock, db.get_conn() as conn:
|
| 585 |
+
expired = conn.execute("SELECT user_id FROM users WHERE plan != 'free' AND plan_expires < ?", (datetime.now(),)).fetchall()
|
| 586 |
+
for u in expired:
|
| 587 |
+
conn.execute("UPDATE users SET plan = 'free' WHERE user_id = ?", (u[0],))
|
| 588 |
+
try: bot.send_message(u[0], "⚠️ انتهت صلاحية خطتك المدفوعة.")
|
| 589 |
+
except: pass
|
| 590 |
+
conn.commit()
|
| 591 |
|
| 592 |
+
# 2. أخذ نسخة احتياطية من الداتا بيز
|
| 593 |
+
backup_path = os.path.join(BACKUP_DIR, f"db_backup_{datetime.now().strftime('%A')}.db")
|
| 594 |
+
shutil.copy2(DB_NAME, backup_path)
|
| 595 |
+
logger.info("✅ تمت الصيانة الدورية وأخذ نسخة احتياطية بنجاح.")
|
| 596 |
+
|
| 597 |
+
scheduler = BackgroundScheduler()
|
| 598 |
+
scheduler.add_job(system_maintenance, 'interval', hours=12)
|
| 599 |
+
scheduler.start()
|
| 600 |
+
|
| 601 |
+
# دوال المساعدة
|
| 602 |
+
def safe_edit(call, text, markup=None):
|
| 603 |
+
try: bot.edit_message_text(text, call.message.chat.id, call.message.message_id, reply_markup=markup, parse_mode="Markdown")
|
| 604 |
+
except: pass
|
| 605 |
+
|
| 606 |
+
@bot.message_handler(commands=['cancel'])
|
| 607 |
+
def cancel_cmd(message):
|
| 608 |
+
user_states.pop(message.from_user.id, None)
|
| 609 |
+
bot.reply_to(message, "❌ تم الإلغاء.", reply_markup=UI.main_menu(message.from_user.id))
|
| 610 |
+
|
| 611 |
+
# ==========================================
|
| 612 |
+
# 🚀 تشغيل النظام (Ignition)
|
| 613 |
+
# ==========================================
|
| 614 |
if __name__ == '__main__':
|
| 615 |
+
logger.info(f"🐺 إقلاع نظام White Wolf Cloud v{VERSION}...")
|
| 616 |
try:
|
| 617 |
+
bot.infinity_polling(timeout=60, long_polling_timeout=30)
|
| 618 |
except Exception as e:
|
| 619 |
+
logger.error(f"انقطاع عام: {e}")
|