Spaces:
Runtime error

File size: 10,630 Bytes
674191a
cc560ef
 
674191a
cc560ef
11c938f
cc560ef
 
18d7c57
cc560ef
 
 
 
 
 
 
 
 
 
674191a
cc560ef
 
 
 
 
 
 
 
11c938f
 
 
cc560ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11c938f
 
 
 
 
 
18d7c57
 
11c938f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc560ef
 
 
 
674191a
cc560ef
 
 
674191a
cc560ef
d17ad3b
cc560ef
 
 
 
d17ad3b
cc560ef
 
 
 
 
 
 
 
d17ad3b
cc560ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d17ad3b
 
cc560ef
 
 
 
 
 
 
 
 
d17ad3b
674191a
cc560ef
 
 
 
 
 
 
d17ad3b
cc560ef
 
 
 
 
 
 
 
 
 
18d7c57
cc560ef
 
 
 
 
674191a
cc560ef
 
 
 
d17ad3b
cc560ef
 
 
 
 
 
 
 
 
 
 
 
 
 
d17ad3b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import os
import sys
import logging
import asyncio
import shutil
import glob
from datetime import datetime, timezone
from typing import Dict, Optional
from pyrogram import Client, filters
from pyrogram.types import Message

# --- STRUCTURED PRODUCTION LOGGING ---
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    handlers=[
        logging.StreamHandler(sys.stdout),
        logging.FileHandler("bot_production.log", encoding="utf-8")
    ]
)
logger = logging.getLogger("HostingBot")

# --- ENV CONFIGURATION & VALIDATION ---
API_ID = int(os.environ.get("API_ID", 0))
API_HASH = os.environ.get("API_HASH", "")
BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
OWNER_ID = int(os.environ.get("OWNER_ID", 0))

# Save the bot's own filename dynamically so it never deletes itself
BOT_SCRIPT_NAME = os.path.basename(__file__)

if not all([API_ID, API_HASH, BOT_TOKEN, OWNER_ID]):
    logger.critical("Critical environment variables missing! Exiting application.")
    sys.exit(1)

# --- TRACKING ENGINE ---
START_TIME = datetime.now(timezone.utc)
# Map structure: { filename: (asyncio.subprocess.Process, start_time) }
ACTIVE_RUNS: Dict[str, tuple] = {}
MAX_RUN_TIME = 3600  # Enforce hard timeout per user script (e.g., 1 hour)

# --- CLIENT INIT ---
app = Client("py_manager_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)

# --- CUSTOM SECURITY FILTERS ---
def is_owner_filter(_, __, message: Message) -> bool:
    return bool(message.from_user and message.from_user.id == OWNER_ID)

owner_only = filters.create(is_owner_filter)

# --- CORE UTILITIES / EXECUTION SANDBOX ---
async def enforce_process_timeout(filename: str, process: asyncio.subprocess.Process, timeout: int):
    """Monitors running jobs and forces cancellation if limits are exceeded."""
    await asyncio.sleep(timeout)
    if process.returncode is None:
        try:
            logger.warning(f"Process {filename} exceeded runtime limit. Forcing termination.")
            process.terminate()
            await process.wait()
        except ProcessLookupError:
            pass
        finally:
            ACTIVE_RUNS.pop(filename, None)

# --- COMMAND HANDLERS ---

@app.on_message(filters.command("start") & owner_only)
async def start_cmd(client: Client, message: Message):
    await message.reply_text(
        "⚡ **Production-Grade Python Host System Engine Online.** ⚡\n\n"
        "**Available Commands:**\n"
        "• `/upload` - Send/reply to a `.py` file with this command to upload it.\n"
        "• `/run <filename.py>` - Run an uploaded script.\n"
        "• `/stop <filename.py>` - Stop a running script.\n"
        "• `/status` - Check resource usage and active tasks.\n"
        "• `/clear` - Preview and wipe generated/uploaded script files."
    )

@app.on_message(filters.command("upload") & owner_only)
async def upload_file(client: Client, message: Message):
    # Check if the command is on a document message or replying to one
    target_msg = message.reply_to_message if message.reply_to_message else message
    
    if not target_msg.document:
        return await message.reply_text("❌ **Error:** Please use `/upload` as a caption on a file document or reply to a file document.")
    
    filename = target_msg.document.file_name
    
    # Simple restriction to keep the environment clean
    if not filename.endswith(".py"):
        return await message.reply_text("❌ **Security Reject:** Only Python scripts (`.py`) can be uploaded to this engine workspace.")

    status_msg = await message.reply_text(f"📥 Downloading `{filename}` into workspace environment...")
    
    try:
        # Download the file directly to the current working directory
        await target_msg.download(file_name=os.path.join(os.getcwd(), filename))
        await status_msg.edit_text(f"✅ File `{filename}` has been provisioned successfully. Ready to execute using `/run {filename}`.")
    except Exception as e:
        logger.exception("Failed to download file.")
        await status_msg.edit_text(f"❌ **Upload Failed:** `{str(e)}`")

@app.on_message(filters.command("clear") & owner_only)
async def clear_workspace(client: Client, message: Message):
    # Stop any active tasks first to prevent file locks
    if ACTIVE_RUNS:
        await message.reply_text("⚠️ **Notice:** Stopping all actively running process instances before wiping workspace...")
        for filename, (proc, _) in list(ACTIVE_RUNS.items()):
            try:
                proc.terminate()
                await proc.wait()
            except Exception:
                pass
        ACTIVE_RUNS.clear()

    # Gather files to delete: .py, .log, .txt files (ignoring the main bot script itself)
    all_files = glob.glob("*.py") + glob.glob("*.log") + glob.glob("*.txt")
    files_to_delete = [f for f in all_files if f != BOT_SCRIPT_NAME]

    if not files_to_delete:
        return await message.reply_text("✨ Workspace is already clear. No ephemeral data found.")

    # 1. Send the file listing preview first
    preview_list = "\n".join([f"• `{f}`" for f in files_to_delete])
    preview_msg = f"🗑️ **Purging Workspace Engine...**\n\n**The following files will be deleted permanently:**\n{preview_list}"
    await message.reply_text(preview_msg)
    
    # Minor artificial pause to let the user read what is being deleted
    await asyncio.sleep(1.5)

    # 2. Execute deletion sequence
    deleted_count = 0
    failed_count = 0
    
    for file_path in files_to_delete:
        try:
            os.remove(file_path)
            deleted_count += 1
        except Exception as e:
            logger.error(f"Failed to delete {file_path}: {e}")
            failed_count += 1

    result_text = f"✅ **Purge Cycle Complete.**\n• Successfully deleted `{deleted_count}` files."
    if failed_count > 0:
        result_text += f"\n• ⚠️ Failed to delete `{failed_count}` locked system elements."
        
    await message.reply_text(result_text)

@app.on_message(filters.command("install") & owner_only)
async def install_lib(client: Client, message: Message):
    if len(message.command) < 2:
        return await message.reply_text("❌ **Usage:** `/install <library_name>`")
    
    lib = message.command[1]
    if not lib.isalnum() and "_" not in lib and "-" not in lib:
        return await message.reply_text("❌ **Security Alert:** Invalid package schema structural characters.")

    msg = await message.reply_text(f"⏳ `pip`: Provisioning `{lib}` dynamic environments...")
    try:
        proc = await asyncio.create_subprocess_exec(
            sys.executable, "-m", "pip", "install", "--no-cache-dir", lib,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE
        )
        stdout, stderr = await proc.communicate()

        if proc.returncode == 0:
            await msg.edit_text(f"✅ Successfully installed package environment: `{lib}`.")
        else:
            error_log = stderr.decode().strip() or stdout.decode().strip()
            logger.error(f"Installation failed for {lib}: {error_log}")
            await msg.edit_text(f"❌ **Pip Engine failure context:**\n`{error_log[:300]}`")
    except Exception as e:
        logger.exception("Exception hit during pip installation invocation")
        await msg.edit_text(f"❌ **System Execution Failure:** `{str(e)}`")

@app.on_message(filters.command("run") & owner_only)
async def run_script(client: Client, message: Message):
    if len(message.command) < 2:
        return await message.reply_text("❌ **Usage:** `/run <filename.py>`")
        
    filename = message.command[1]
    if not os.path.exists(filename):
        return await message.reply_text(f"❌ Reference target file `{filename}` does not exist in context.")

    if filename in ACTIVE_RUNS:
        return await message.reply_text(f"⚠️ Target context instance `{filename}` is already actively executing.")

    msg = await message.reply_text(f"🚀 Initializing isolated execution instance for `{filename}`...")

    try:
        clean_env = os.environ.copy()
        clean_env.pop("BOT_TOKEN", None)
        clean_env.pop("API_HASH", None)

        proc = await asyncio.create_subprocess_exec(
            sys.executable, filename,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
            env=clean_env
        )
        
        ACTIVE_RUNS[filename] = (proc, datetime.now(timezone.utc))
        asyncio.create_task(enforce_process_timeout(filename, proc, MAX_RUN_TIME))
        
        await msg.edit_text(f"✅ Instance running. Tracking ID context: `{filename}`. Watchdog active.")
    except Exception as e:
        logger.exception("Failed to initialize script engine runtime.")
        await msg.edit_text(f"❌ **Runtime Dispatch Error:** `{str(e)}`")

@app.on_message(filters.command("stop") & owner_only)
async def stop_script(client: Client, message: Message):
    if len(message.command) < 2:
        return await message.reply_text("❌ **Usage:** `/stop <filename.py>`")

    filename = message.command[1]
    if filename not in ACTIVE_RUNS:
        return await message.reply_text(f"❌ Active workspace process context not found for `{filename}`.")

    proc, _ = ACTIVE_RUNS.pop(filename)
    try:
        proc.terminate()
        await proc.wait()
        await message.reply_text(f"🛑 Cleanly terminated process context instance: `{filename}`.")
    except Exception as e:
        await message.reply_text(f"❌ **Error while killing process context:** `{str(e)}`")

@app.on_message(filters.command("status") & owner_only)
async def system_status(client: Client, message: Message):
    now = datetime.now(timezone.utc)
    uptime = now - START_TIME
    
    active_jobs_str = "\n".join([f"• `{k}` (Running for: {str(now - v[1]).split('.')[0]})" for k, v in ACTIVE_RUNS.items()]) or "No active execution instances."
    total, used, free = shutil.disk_usage(".")
    
    status_msg = (
        f"📊 **System Production Analytics Engine**\n"
        f"‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾\n"
        f"⏱️ **Core Engine Uptime:** `{str(uptime).split('.')[0]}`\n"
        f"💽 **Disk Allocation:** Used {used // (2**20)}MB / {total // (2**20)}MB ({free // (2**20)}MB Free)\n\n"
        f"⚡ **Active Sandboxes Runtime ({len(ACTIVE_RUNS)}):**\n{active_jobs_str}"
    )
    await message.reply_text(status_msg)

if __name__ == "__main__":
    logger.info("Booting production engine client context...")
    app.run()