import gradio as gr
import subprocess
import os
import sys
import json
import shutil
import signal
import psutil
import time
import threading
import traceback
from pathlib import Path
from datetime import datetime
# ===== مجلد العمل الرئيسي =====
WORKSPACE = os.path.join(os.path.expanduser("~"), "workspace")
os.makedirs(WORKSPACE, exist_ok=True)
os.chdir(WORKSPACE)
# ===== تخزين العمليات الجارية =====
running_processes = {}
process_lock = threading.Lock()
terminal_history = []
# ===== تنفيذ أوامر الطرفية =====
def execute_command(command, working_dir=None):
"""تنفيذ أمر في الطرفية مع دعم كامل"""
if not command or not command.strip():
return "⚠️ اكتب أمراً للتنفيذ"
work_dir = working_dir if working_dir and os.path.isdir(working_dir) else WORKSPACE
# حفظ في السجل
timestamp = datetime.now().strftime("%H:%M:%S")
terminal_history.append(f"[{timestamp}] $ {command}")
try:
# أوامر خاصة
cmd_parts = command.strip().split()
cmd_name = cmd_parts[0] if cmd_parts else ""
# أمر cd
if cmd_name == "cd":
target = cmd_parts[1] if len(cmd_parts) > 1 else WORKSPACE
if target == "~":
target = WORKSPACE
target_path = os.path.join(work_dir, target) if not os.path.isabs(target) else target
target_path = os.path.abspath(target_path)
if os.path.isdir(target_path):
os.chdir(target_path)
return f"📂 انتقلت إلى: {target_path}"
else:
return f"❌ المجلد غير موجود: {target_path}"
# أمر clear
if cmd_name in ("clear", "cls"):
terminal_history.clear()
return "🧹 تم مسح الشاشة"
# تنفيذ الأمر
env = os.environ.copy()
env['PYTHONUNBUFFERED'] = '1'
env['HOME'] = os.path.expanduser("~")
env['PATH'] = env.get('PATH', '') + ':/usr/local/bin:/usr/bin:/bin'
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=300,
cwd=work_dir,
env=env,
)
output_parts = []
if result.stdout:
output_parts.append(result.stdout)
if result.stderr:
# بعض البرامج تستخدم stderr للمعلومات العادية
if result.returncode == 0:
output_parts.append(result.stderr)
else:
output_parts.append(f"⚠️ STDERR:\n{result.stderr}")
if result.returncode != 0 and not output_parts:
output_parts.append(f"❌ Exit code: {result.returncode}")
if not output_parts:
output_parts.append("✅ تم التنفيذ بنجاح (بدون مخرجات)")
return '\n'.join(output_parts)
except subprocess.TimeoutExpired:
return "⏰ انتهت المهلة (5 دقائق). استخدم 'تشغيل في الخلفية' للعمليات الطويلة."
except FileNotFoundError:
return f"❌ الأمر غير موجود: {cmd_name}\nجرب: pip install أو apt-get install"
except Exception as e:
return f"❌ خطأ: {str(e)}"
# ===== تشغيل في الخلفية =====
def run_background(command, working_dir=None):
"""تشغيل أمر في الخلفية (للبوتات والسيرفرات)"""
if not command or not command.strip():
return "⚠️ اكتب أمراً للتشغيل"
work_dir = working_dir if working_dir and os.path.isdir(working_dir) else WORKSPACE
try:
env = os.environ.copy()
env['PYTHONUNBUFFERED'] = '1'
# إنشاء ملفات للمخرجات
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
log_file = os.path.join(WORKSPACE, f".logs/process_{timestamp}.log")
os.makedirs(os.path.dirname(log_file), exist_ok=True)
log_handle = open(log_file, 'w')
process = subprocess.Popen(
command,
shell=True,
stdout=log_handle,
stderr=subprocess.STDOUT,
cwd=work_dir,
env=env,
preexec_fn=os.setsid if os.name != 'nt' else None,
)
with process_lock:
running_processes[process.pid] = {
'command': command,
'pid': process.pid,
'start_time': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'log_file': log_file,
'process': process,
'log_handle': log_handle,
}
return (
f"✅ تم التشغيل في الخلفية!\n"
f"{'─' * 40}\n"
f"📋 PID: {process.pid}\n"
f"📝 الأمر: {command}\n"
f"📄 ملف السجل: {log_file}\n"
f"{'─' * 40}\n"
f"💡 لمتابعة المخرجات: cat {log_file}\n"
f"💡 لإيقاف العملية: استخدم زر إدارة العمليات"
)
except Exception as e:
return f"❌ خطأ في التشغيل: {str(e)}"
# ===== إدارة العمليات =====
def list_processes():
"""عرض العمليات الجارية"""
output_parts = ["🔄 العمليات الجارية في الخلفية:", "═" * 50]
with process_lock:
if not running_processes:
output_parts.append("📭 لا توجد عمليات جارية")
else:
for pid, info in list(running_processes.items()):
proc = info['process']
status = "🟢 يعمل" if proc.poll() is None else f"🔴 انتهى (code: {proc.returncode})"
# معلومات الذاكرة
mem_info = ""
try:
p = psutil.Process(pid)
mem = p.memory_info().rss / 1024 / 1024
cpu = p.cpu_percent()
mem_info = f" 💾 RAM: {mem:.1f}MB | CPU: {cpu:.1f}%"
except:
pass
output_parts.append(
f"\n📋 PID: {pid}\n"
f" 📝 الأمر: {info['command']}\n"
f" 🕐 بدأ: {info['start_time']}\n"
f" 📊 الحالة: {status}\n"
f"{mem_info}\n"
f" 📄 السجل: {info['log_file']}"
)
# عمليات النظام
output_parts.append(f"\n{'═' * 50}")
output_parts.append("📊 معلومات النظام:")
output_parts.append(f" 💾 RAM: {psutil.virtual_memory().percent}% مستخدم")
output_parts.append(f" 🖥️ CPU: {psutil.cpu_percent()}%")
output_parts.append(f" 💿 Disk: {psutil.disk_usage('/').percent}% مستخدم")
return '\n'.join(output_parts)
def stop_process(pid_str):
"""إيقاف عملية"""
if not pid_str or not pid_str.strip():
return "⚠️ أدخل رقم PID"
try:
pid = int(pid_str.strip())
except ValueError:
return "❌ PID يجب أن يكون رقماً"
with process_lock:
if pid in running_processes:
info = running_processes[pid]
proc = info['process']
try:
if os.name != 'nt':
os.killpg(os.getpgid(pid), signal.SIGTERM)
else:
proc.terminate()
proc.wait(timeout=5)
info['log_handle'].close()
del running_processes[pid]
return f"✅ تم إيقاف العملية {pid}"
except subprocess.TimeoutExpired:
if os.name != 'nt':
os.killpg(os.getpgid(pid), signal.SIGKILL)
else:
proc.kill()
info['log_handle'].close()
del running_processes[pid]
return f"⚠️ تم قتل العملية {pid} بالقوة"
except Exception as e:
return f"❌ خطأ: {str(e)}"
else:
# محاولة إيقاف عملية نظام
try:
os.kill(pid, signal.SIGTERM)
return f"✅ تم إرسال SIGTERM للعملية {pid}"
except ProcessLookupError:
return f"❌ العملية {pid} غير موجودة"
except Exception as e:
return f"❌ خطأ: {str(e)}"
def view_process_log(pid_str):
"""عرض سجل عملية"""
if not pid_str or not pid_str.strip():
return "⚠️ أدخل رقم PID"
try:
pid = int(pid_str.strip())
except ValueError:
return "❌ PID يجب أن يكون رقماً"
with process_lock:
if pid in running_processes:
log_file = running_processes[pid]['log_file']
try:
with open(log_file, 'r') as f:
content = f.read()
if not content:
return "📄 السجل فارغ حالياً..."
# آخر 100 سطر
lines = content.split('\n')
if len(lines) > 100:
return f"... (عرض آخر 100 سطر من {len(lines)})\n\n" + '\n'.join(lines[-100:])
return content
except Exception as e:
return f"❌ خطأ في قراءة السجل: {str(e)}"
else:
return f"❌ العملية {pid} غير موجودة في القائمة"
# ===== مدير الملفات =====
def list_files(path=None):
"""عرض محتويات مجلد"""
target = path if path and os.path.isdir(path) else os.getcwd()
target = os.path.abspath(target)
try:
items = sorted(os.listdir(target))
output_parts = [
f"📂 المجلد: {target}",
f"{'═' * 60}",
f"{'النوع':<6} {'الحجم':<12} {'التعديل':<20} {'الاسم'}",
f"{'─' * 60}",
]
total_size = 0
dir_count = 0
file_count = 0
for item in items:
full_path = os.path.join(target, item)
try:
stat = os.stat(full_path)
mod_time = datetime.fromtimestamp(stat.st_mtime).strftime("%Y-%m-%d %H:%M")
if os.path.isdir(full_path):
output_parts.append(f"📁 {'
':<12} {mod_time:<20} {item}/")
dir_count += 1
else:
size = stat.st_size
total_size += size
size_str = format_size(size)
# أيقونة حسب نوع الملف
icon = get_file_icon(item)
output_parts.append(f"{icon} {size_str:<12} {mod_time:<20} {item}")
file_count += 1
except PermissionError:
output_parts.append(f"🔒 {'N/A':<12} {'N/A':<20} {item}")
output_parts.append(f"{'─' * 60}")
output_parts.append(f"📊 {dir_count} مجلدات | {file_count} ملفات | الحجم: {format_size(total_size)}")
return '\n'.join(output_parts)
except PermissionError:
return f"🔒 لا يوجد صلاحية للوصول إلى: {target}"
except Exception as e:
return f"❌ خطأ: {str(e)}"
def format_size(size):
"""تنسيق حجم الملف"""
for unit in ['B', 'KB', 'MB', 'GB']:
if size < 1024:
return f"{size:.1f}{unit}"
size /= 1024
return f"{size:.1f}TB"
def get_file_icon(filename):
"""أيقونة حسب نوع الملف"""
ext = filename.rsplit('.', 1)[-1].lower() if '.' in filename else ''
icons = {
'py': '🐍', 'js': '📜', 'ts': '📘', 'html': '🌐', 'css': '🎨',
'json': '📋', 'yml': '⚙️', 'yaml': '⚙️', 'toml': '⚙️',
'md': '📝', 'txt': '📄', 'log': '📃', 'csv': '📊',
'jpg': '🖼️', 'png': '🖼️', 'gif': '🖼️', 'svg': '🖼️',
'mp3': '🎵', 'mp4': '🎬', 'zip': '📦', 'tar': '📦',
'gz': '📦', 'sh': '⚡', 'bash': '⚡', 'env': '🔐',
'db': '🗄️', 'sqlite': '🗄️', 'sql': '🗄️',
'dockerfile': '🐳', 'gitignore': '📌',
}
return icons.get(ext, '📄')
def read_file(filepath):
"""قراءة ملف"""
if not filepath or not filepath.strip():
return "⚠️ أدخل مسار الملف"
filepath = filepath.strip()
if not os.path.isabs(filepath):
filepath = os.path.join(os.getcwd(), filepath)
try:
if not os.path.exists(filepath):
return f"❌ الملف غير موجود: {filepath}"
size = os.path.getsize(filepath)
if size > 5 * 1024 * 1024: # 5MB limit
return f"⚠️ الملف كبير جداً ({format_size(size)}). استخدم head أو tail"
# فحص إذا كان ملف نصي
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
return f"📄 {filepath} ({format_size(size)}):\n{'─' * 40}\n{content}"
except UnicodeDecodeError:
return f"⚠️ هذا ملف ثنائي (binary) ولا يمكن عرضه كنص. الحجم: {format_size(size)}"
except PermissionError:
return f"🔒 لا يوجد صلاحية لقراءة: {filepath}"
except Exception as e:
return f"❌ خطأ: {str(e)}"
def write_file(filepath, content):
"""كتابة ملف"""
if not filepath or not filepath.strip():
return "⚠️ أدخل مسار الملف"
filepath = filepath.strip()
if not os.path.isabs(filepath):
filepath = os.path.join(os.getcwd(), filepath)
try:
os.makedirs(os.path.dirname(filepath), exist_ok=True)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content or "")
size = os.path.getsize(filepath)
return f"✅ تم حفظ الملف: {filepath} ({format_size(size)})"
except Exception as e:
return f"❌ خطأ في الحفظ: {str(e)}"
def delete_file(filepath):
"""حذف ملف أو مجلد"""
if not filepath or not filepath.strip():
return "⚠️ أدخل مسار الملف"
filepath = filepath.strip()
if not os.path.isabs(filepath):
filepath = os.path.join(os.getcwd(), filepath)
try:
if not os.path.exists(filepath):
return f"❌ غير موجود: {filepath}"
if os.path.isdir(filepath):
shutil.rmtree(filepath)
return f"✅ تم حذف المجلد: {filepath}"
else:
os.remove(filepath)
return f"✅ تم حذف الملف: {filepath}"
except Exception as e:
return f"❌ خطأ: {str(e)}"
def create_directory(dirpath):
"""إنشاء مجلد"""
if not dirpath or not dirpath.strip():
return "⚠️ أدخل مسار المجلد"
dirpath = dirpath.strip()
if not os.path.isabs(dirpath):
dirpath = os.path.join(os.getcwd(), dirpath)
try:
os.makedirs(dirpath, exist_ok=True)
return f"✅ تم إنشاء المجلد: {dirpath}"
except Exception as e:
return f"❌ خطأ: {str(e)}"
def upload_file(file):
"""رفع ملف"""
if file is None:
return "⚠️ اختر ملفاً للرفع", list_files()
try:
filename = os.path.basename(file.name) if hasattr(file, 'name') else "uploaded_file"
dest = os.path.join(os.getcwd(), filename)
if isinstance(file, str):
shutil.copy2(file, dest)
else:
shutil.copy2(file.name, dest)
size = os.path.getsize(dest)
return f"✅ تم رفع: {filename} ({format_size(size)})", list_files()
except Exception as e:
return f"❌ خطأ في الرفع: {str(e)}", list_files()
# ===== محرر الأكواد =====
def save_and_run(filepath, code):
"""حفظ وتشغيل ملف"""
if not filepath or not filepath.strip():
return "⚠️ أدخل اسم الملف", ""
filepath = filepath.strip()
if not os.path.isabs(filepath):
filepath = os.path.join(os.getcwd(), filepath)
# حفظ
save_result = write_file(filepath, code)
# تشغيل حسب نوع الملف
ext = filepath.rsplit('.', 1)[-1].lower() if '.' in filepath else ''
run_commands = {
'py': f'python3 "{filepath}"',
'js': f'node "{filepath}"',
'sh': f'bash "{filepath}"',
'bash': f'bash "{filepath}"',
}
if ext in run_commands:
run_result = execute_command(run_commands[ext])
return save_result, run_result
else:
return save_result, "ℹ️ تم الحفظ فقط (نوع الملف لا يدعم التشغيل المباشر)"
# ===== تثبيت الحزم =====
def install_package(package_name):
"""تثبيت حزمة بايثون"""
if not package_name or not package_name.strip():
return "⚠️ أدخل اسم الحزمة"
return execute_command(f"pip install {package_name.strip()}")
def system_info():
"""معلومات النظام"""
try:
mem = psutil.virtual_memory()
disk = psutil.disk_usage('/')
cpu_count = psutil.cpu_count()
boot_time = datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
info = f"""
╔══════════════════════════════════════════╗
║ 🖥️ معلومات النظام ║
╠══════════════════════════════════════════╣
║ ║
║ 🐍 Python: {sys.version.split()[0]:<28}║
║ 💻 OS: {os.uname().sysname} {os.uname().release[:20]:<20}║
║ 🏗️ Arch: {os.uname().machine:<28}║
║ 🕐 Boot: {boot_time:<28}║
║ ║
║ 🖥️ CPU Cores: {cpu_count:<25}║
║ 📊 CPU Usage: {psutil.cpu_percent():.1f}%{'':<23}║
║ ║
║ 💾 RAM Total: {format_size(mem.total):<25}║
║ 💾 RAM Used: {format_size(mem.used)} ({mem.percent}%){'':<14}║
║ 💾 RAM Free: {format_size(mem.available):<25}║
║ ║
║ 💿 Disk Total: {format_size(disk.total):<24}║
║ 💿 Disk Used: {format_size(disk.used)} ({disk.percent}%){'':<13}║
║ 💿 Disk Free: {format_size(disk.free):<24}║
║ ║
║ 📂 CWD: {os.getcwd()[:30]:<30}║
║ 👤 User: {os.environ.get('USER', 'N/A'):<29}║
║ ║
╚══════════════════════════════════════════╝
"""
return info
except Exception as e:
return f"❌ خطأ: {str(e)}"
# ===== الواجهة =====
CUSTOM_CSS = """
@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500&family=Tajawal:wght@400;500;700&display=swap');
* { font-family: 'Tajawal', sans-serif !important; }
.terminal-output textarea,
.code-editor textarea {
font-family: 'Fira Code', 'Courier New', monospace !important;
font-size: 13px !important;
line-height: 1.5 !important;
}
.terminal-output textarea {
background-color: #0d1117 !important;
color: #58a6ff !important;
border: 2px solid #30363d !important;
}
.header-banner {
text-align: center;
background: linear-gradient(135deg, #0d1117 0%, #161b22 50%, #0d1117 100%);
padding: 20px;
border-radius: 16px;
margin-bottom: 15px;
border: 1px solid #30363d;
}
.header-banner h1 {
color: #58a6ff;
font-size: 2.2em;
margin: 0;
}
.header-banner p {
color: #8b949e;
margin: 5px 0 0;
}
.status-bar {
background: #161b22;
color: #58a6ff;
padding: 8px 16px;
border-radius: 8px;
font-family: 'Fira Code', monospace !important;
font-size: 12px;
border: 1px solid #30363d;
}
footer { display: none !important; }
"""
with gr.Blocks(
css=CUSTOM_CSS,
title="🖥️ Cloud VPS Terminal",
theme=gr.themes.Base(
primary_hue="blue",
secondary_hue="purple",
neutral_hue="gray",
font=gr.themes.GoogleFont("Tajawal"),
)
) as app:
gr.HTML("""
""")
with gr.Tabs():
# ═══════════ تاب الطرفية ═══════════
with gr.TabItem("⚡ Terminal"):
gr.HTML('📍 Terminal | اكتب أي أمر Linux وشغّله
')
with gr.Row():
with gr.Column(scale=4):
cmd_input = gr.Textbox(
label="💻 الأمر",
placeholder="اكتب أمر Linux هنا... مثل: ls -la, pip install requests, python bot.py",
lines=1,
)
with gr.Column(scale=1):
work_dir = gr.Textbox(
label="📂 مجلد العمل",
value=WORKSPACE,
lines=1,
)
with gr.Row():
run_cmd_btn = gr.Button("▶️ تنفيذ", variant="primary", size="lg")
bg_run_btn = gr.Button("🔄 تشغيل في الخلفية", variant="secondary", size="lg")
sys_info_btn = gr.Button("ℹ️ معلومات النظام", size="lg")
terminal_output = gr.Textbox(
label="📺 المخرجات",
lines=25,
max_lines=50,
interactive=False,
elem_classes=["terminal-output"],
)
gr.HTML("⚡ أوامر سريعة:
")
with gr.Row():
gr.Button("📋 ls -la").click(fn=lambda: execute_command("ls -la"), outputs=[terminal_output])
gr.Button("📂 pwd").click(fn=lambda: execute_command("pwd"), outputs=[terminal_output])
gr.Button("💾 df -h").click(fn=lambda: execute_command("df -h"), outputs=[terminal_output])
gr.Button("🐍 pip list").click(fn=lambda: execute_command("pip list"), outputs=[terminal_output])
gr.Button("📡 curl ifconfig.me").click(fn=lambda: execute_command("curl -s ifconfig.me"), outputs=[terminal_output])
gr.Button("🔝 top (snapshot)").click(fn=lambda: execute_command("ps aux --sort=-%mem | head -20"), outputs=[terminal_output])
# ربط الأحداث
run_cmd_btn.click(fn=execute_command, inputs=[cmd_input, work_dir], outputs=[terminal_output])
cmd_input.submit(fn=execute_command, inputs=[cmd_input, work_dir], outputs=[terminal_output])
bg_run_btn.click(fn=run_background, inputs=[cmd_input, work_dir], outputs=[terminal_output])
sys_info_btn.click(fn=system_info, outputs=[terminal_output])
# ═══════════ تاب مدير الملفات ═══════════
with gr.TabItem("📁 File Manager"):
gr.HTML('📁 File Manager | إدارة كاملة للملفات والمجلدات
')
with gr.Row():
with gr.Column(scale=2):
browse_path = gr.Textbox(label="📂 المسار", value=WORKSPACE, lines=1)
browse_btn = gr.Button("🔍 استعراض", variant="primary")
file_list_output = gr.Textbox(
label="📋 محتويات المجلد",
lines=20,
interactive=False,
elem_classes=["terminal-output"],
)
with gr.Column(scale=2):
with gr.Tabs():
with gr.TabItem("📄 قراءة ملف"):
read_path = gr.Textbox(label="مسار الملف", lines=1)
read_btn = gr.Button("📖 قراءة", variant="primary")
file_content = gr.Textbox(label="المحتوى", lines=15, interactive=False)
with gr.TabItem("✏️ إنشاء/تعديل"):
new_file_path = gr.Textbox(label="مسار الملف", lines=1, placeholder="مثال: bot.py")
new_file_content = gr.Code(label="المحتوى", language="python", lines=12)
save_btn = gr.Button("💾 حفظ", variant="primary")
save_status = gr.Textbox(label="الحالة", lines=2, interactive=False)
with gr.TabItem("📁 مجلد جديد"):
new_dir_path = gr.Textbox(label="مسار المجلد", lines=1)
mkdir_btn = gr.Button("📁 إنشاء", variant="primary")
mkdir_status = gr.Textbox(label="الحالة", lines=2, interactive=False)
with gr.TabItem("🗑️ حذف"):
del_path = gr.Textbox(label="مسار الملف/المجلد", lines=1)
del_btn = gr.Button("🗑️ حذف", variant="stop")
del_status = gr.Textbox(label="الحالة", lines=2, interactive=False)
with gr.TabItem("📤 رفع ملف"):
upload_input = gr.File(label="اختر ملفاً", file_count="single")
upload_btn = gr.Button("📤 رفع", variant="primary")
upload_status = gr.Textbox(label="الحالة", lines=2, interactive=False)
# ربط أحداث مدير الملفات
browse_btn.click(fn=list_files, inputs=[browse_path], outputs=[file_list_output])
browse_path.submit(fn=list_files, inputs=[browse_path], outputs=[file_list_output])
read_btn.click(fn=read_file, inputs=[read_path], outputs=[file_content])
save_btn.click(fn=write_file, inputs=[new_file_path, new_file_content], outputs=[save_status])
mkdir_btn.click(fn=create_directory, inputs=[new_dir_path], outputs=[mkdir_status])
del_btn.click(fn=delete_file, inputs=[del_path], outputs=[del_status])
upload_btn.click(fn=upload_file, inputs=[upload_input], outputs=[upload_status, file_list_output])
# ═══════════ تاب محرر الأكواد ═══════════
with gr.TabItem("✏️ Code Editor"):
gr.HTML('✏️ Code Editor | كتابة وتشغيل الأكواد مباشرة
')
with gr.Row():
editor_filepath = gr.Textbox(
label="📄 اسم الملف",
value="script.py",
lines=1,
scale=2,
)
editor_lang = gr.Dropdown(
label="🌐 اللغة",
choices=["python", "javascript", "shell", "json", "yaml", "markdown", "html", "css"],
value="python",
scale=1,
)
with gr.Row():
load_file_btn = gr.Button("📂 تحميل من ملف", variant="secondary")
save_file_btn = gr.Button("💾 حفظ", variant="primary")
save_run_btn = gr.Button("▶️ حفظ وتشغيل", variant="primary")
code_editor = gr.Code(
label="✏️ الكود",
language="python",
lines=25,
value='# اكتب الكود هنا\nprint("مرحباً! 🐍")',
)
editor_output = gr.Textbox(
label="📤 المخرجات",
lines=12,
interactive=False,
elem_classes=["terminal-output"],
)
# قوالب جاهزة
gr.HTML("📦 قوالب جاهزة:
")
with gr.Row():
def template_telegram_bot():
return """# Telegram Bot Template
# pip install python-telegram-bot
import asyncio
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TOKEN = "YOUR_BOT_TOKEN_HERE"
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("مرحباً! أنا بوت تلجرام 🤖")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = update.message.text
await update.message.reply_text(f"قلت: {text}")
def main():
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
print("🤖 البوت يعمل...")
app.run_polling()
if __name__ == "__main__":
main()
""", "telegram_bot.py"
def template_flask_server():
return """# Flask Web Server
# pip install flask
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/')
def home():
return jsonify({"message": "مرحباً بالعالم! 🌍", "status": "running"})
@app.route('/api/hello/')
def hello(name):
return jsonify({"message": f"مرحباً {name}! 👋"})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
""", "server.py"
def template_discord_bot():
return """# Discord Bot Template
# pip install discord.py
import discord
from discord.ext import commands
TOKEN = "YOUR_DISCORD_TOKEN_HERE"
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f"🤖 Bot is ready: {bot.user}")
@bot.command()
async def hello(ctx):
await ctx.send(f"مرحباً {ctx.author.name}! 👋")
@bot.command()
async def ping(ctx):
await ctx.send(f"🏓 Pong! {round(bot.latency * 1000)}ms")
bot.run(TOKEN)
""", "discord_bot.py"
def template_scraper():
return """# Web Scraper Template
# pip install requests beautifulsoup4
import requests
from bs4 import BeautifulSoup
import json
def scrape_website(url):
print(f"🔍 جاري جلب: {url}")
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.string if soup.title else "N/A"
links = [a.get('href') for a in soup.find_all('a', href=True)]
print(f"📄 العنوان: {title}")
print(f"🔗 عدد الروابط: {len(links)}")
return {
'title': title,
'links_count': len(links),
'links': links[:10]
}
if __name__ == '__main__':
result = scrape_website("https://example.com")
print(json.dumps(result, indent=2, ensure_ascii=False))
""", "scraper.py"
tg_btn = gr.Button("🤖 بوت تلجرام")
flask_btn = gr.Button("🌐 Flask Server")
discord_btn = gr.Button("🎮 بوت ديسكورد")
scraper_btn = gr.Button("🔍 Web Scraper")
# ربط القوالب
tg_btn.click(fn=template_telegram_bot, outputs=[code_editor, editor_filepath])
flask_btn.click(fn=template_flask_server, outputs=[code_editor, editor_filepath])
discord_btn.click(fn=template_discord_bot, outputs=[code_editor, editor_filepath])
scraper_btn.click(fn=template_scraper, outputs=[code_editor, editor_filepath])
# ربط أحداث المحرر
def load_file_to_editor(filepath):
if not filepath:
return "⚠️ أدخل مسار الملف", ""
content = read_file(filepath)
if content.startswith("❌") or content.startswith("⚠️") or content.startswith("🔒"):
return content, ""
# إزالة السطر الأول (معلومات الملف)
lines = content.split('\n')
if lines and lines[0].startswith("📄"):
actual_content = '\n'.join(lines[2:]) # تجاوز السطر الأول والفاصل
return "✅ تم التحميل", actual_content
return "✅ تم التحميل", content
load_file_btn.click(
fn=load_file_to_editor,
inputs=[editor_filepath],
outputs=[editor_output, code_editor]
)
save_file_btn.click(
fn=write_file,
inputs=[editor_filepath, code_editor],
outputs=[editor_output]
)
save_run_btn.click(
fn=save_and_run,
inputs=[editor_filepath, code_editor],
outputs=[editor_output, editor_output]
)
# ═══════════ تاب إدارة العمليات ═══════════
with gr.TabItem("🔄 Processes"):
gr.HTML('🔄 Process Manager | إدارة العمليات الجارية
')
with gr.Row():
refresh_proc_btn = gr.Button("🔄 تحديث", variant="primary", size="lg")
list_all_btn = gr.Button("📋 كل عمليات النظام", size="lg")
processes_output = gr.Textbox(
label="📊 العمليات",
lines=20,
interactive=False,
elem_classes=["terminal-output"],
)
with gr.Row():
with gr.Column():
pid_input = gr.Textbox(label="🔢 رقم PID", lines=1)
with gr.Row():
stop_btn = gr.Button("⏹️ إيقاف", variant="stop")
log_btn = gr.Button("📄 عرض السجل", variant="secondary")
with gr.Column():
proc_action_output = gr.Textbox(
label="📋 النتيجة",
lines=10,
interactive=False,
elem_classes=["terminal-output"],
)
# ربط الأحداث
refresh_proc_btn.click(fn=list_processes, outputs=[processes_output])
list_all_btn.click(
fn=lambda: execute_command("ps aux --sort=-%mem | head -30"),
outputs=[processes_output]
)
stop_btn.click(fn=stop_process, inputs=[pid_input], outputs=[proc_action_output])
log_btn.click(fn=view_process_log, inputs=[pid_input], outputs=[proc_action_output])
# ═══════════ تاب الحزم ═══════════
with gr.TabItem("📦 Packages"):
gr.HTML('📦 Package Manager | تثبيت وإدارة الحزم
')
with gr.Row():
pkg_input = gr.Textbox(
label="📦 اسم الحزمة",
placeholder="مثال: requests أو flask أو python-telegram-bot",
lines=1,
scale=3,
)
install_btn = gr.Button("📥 تثبيت", variant="primary", scale=1, size="lg")
pkg_output = gr.Textbox(
label="📋 النتيجة",
lines=15,
interactive=False,
elem_classes=["terminal-output"],
)
gr.HTML("📦 حزم شائعة - اضغط للتثبيت:
")
with gr.Row():
gr.Button("🤖 python-telegram-bot").click(
fn=lambda: install_package("python-telegram-bot"), outputs=[pkg_output])
gr.Button("🌐 flask").click(
fn=lambda: install_package("flask"), outputs=[pkg_output])
gr.Button("📡 requests").click(
fn=lambda: install_package("requests"), outputs=[pkg_output])
gr.Button("🎮 discord.py").click(
fn=lambda: install_package("discord.py"), outputs=[pkg_output])
with gr.Row():
gr.Button("🗄️ sqlalchemy").click(
fn=lambda: install_package("sqlalchemy"), outputs=[pkg_output])
gr.Button("🔍 beautifulsoup4").click(
fn=lambda: install_package("beautifulsoup4"), outputs=[pkg_output])
gr.Button("📊 pandas").click(
fn=lambda: install_package("pandas"), outputs=[pkg_output])
gr.Button("🔧 aiohttp").click(
fn=lambda: install_package("aiohttp"), outputs=[pkg_output])
with gr.Row():
gr.Button("📋 عرض الحزم المثبتة").click(
fn=lambda: execute_command("pip list --format=columns"), outputs=[pkg_output])
gr.Button("🔄 تحديث pip").click(
fn=lambda: execute_command("pip install --upgrade pip"), outputs=[pkg_output])
install_btn.click(fn=install_package, inputs=[pkg_input], outputs=[pkg_output])
pkg_input.submit(fn=install_package, inputs=[pkg_input], outputs=[pkg_output])
gr.HTML("""
🖥️ Cloud VPS Terminal | ⚡ Powered by محمد علي
""")
if __name__ == "__main__":
app.launch(
server_name="0.0.0.0",
server_port=7860,
)