Spaces:
Runtime error

Testingpot / bot.py
dpadhan's picture
Update bot.py
11c938f verified
Raw History Blame Contribute Delete
10.6 kB
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()