Spaces:
Runtime error
Runtime error
Update bot.py
Browse files2 unmodified lines34567816 unmodified lines25262728293033 unmodified lines64656667686970717273747576777879808182838427 unmodified lines1121131141151161171186 unmodified lines12512612712812913013124 unmodified lines1561571581591601611621635 unmodified lines1691701711721731741752 unmodified linesimport loggingimport asyncioimport shutilfrom datetime import datetime, timezonefrom typing import Dict, Optionalfrom pyrogram import Client, filters16 unmodified linesBOT_TOKEN = os.environ.get("BOT_TOKEN", "")OWNER_ID = int(os.environ.get("OWNER_ID", 0))if not all([API_ID, API_HASH, BOT_TOKEN, OWNER_ID]):logger.critical("Critical environment variables missing! Exiting application.")sys.exit(1)33 unmodified linesasync def start_cmd(client: Client, message: Message):await message.reply_text("β‘ **Production-Grade Python Host System Engine Online.** β‘\n\n""Use operational commands below to securely provision workspace tasks.")@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]# Simple sanitization to prevent terminal injection flagsif 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,27 unmodified linesmsg = await message.reply_text(f"π Initializing isolated execution instance for `{filename}`...")try:# Production Fix: Run non-blocking using async subprocess, stripping env tokens for securityclean_env = os.environ.copy()clean_env.pop("BOT_TOKEN", None)clean_env.pop("API_HASH", None)6 unmodified lines)ACTIVE_RUNS[filename] = (proc, datetime.now(timezone.utc))# Schedule hard ceiling runtime watchdog taskasyncio.create_task(enforce_process_timeout(filename, proc, MAX_RUN_TIME))await msg.edit_text(f"β Instance running. Tracking ID context: `{filename}`. Watchdog active.")24 unmodified linesuptime = now - START_TIMEactive_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."# Calculate filesystem usage safety statustotal, used, free = shutil.disk_usage(".")status_msg = (5 unmodified lines)await message.reply_text(status_msg)# --- SYSTEM ENTRY FOR LIFECYCLE MANAGEMENT ---if __name__ == "__main__":logger.info("Booting production engine client context...")app.run()2 unmodified lines345678916 unmodified lines26272829303132333433 unmodified lines686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016127 unmodified lines1891901911921931946 unmodified lines20120220320420520624 unmodified lines2312322332342352365 unmodified lines2422432442452462472 unmodified linesimport loggingimport asyncioimport shutilimport globfrom datetime import datetime, timezonefrom typing import Dict, Optionalfrom pyrogram import Client, filters16 unmodified linesBOT_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 itselfBOT_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)33 unmodified linesasync 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 onetarget_msg = message.reply_to_message if message.reply_to_message else messageif 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 cleanif 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 directoryawait 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 locksif 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:passACTIVE_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 firstpreview_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 deletedawait asyncio.sleep(1.5)# 2. Execute deletion sequencedeleted_count = 0failed_count = 0for file_path in files_to_delete:try:os.remove(file_path)deleted_count += 1except Exception as e:logger.error(f"Failed to delete {file_path}: {e}")failed_count += 1result_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,27 unmodified linesmsg = 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)6 unmodified lines)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.")24 unmodified linesuptime = now - START_TIMEactive_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 = (5 unmodified lines)await message.reply_text(status_msg)if __name__ == "__main__":logger.info("Booting production engine client context...")app.run()
bot.py+80-8