Spaces:
Runtime error
Runtime error
Update bot.py
Browse files12323456789567811121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162639101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616566676869706263646566676869737475707172737477787980818283848575767778798780818289909192938384858687888990919293949596969798991001011021031041051061071081091101111121139899100114102103104105106107115116117118119120121122123124125109110111112113114115116117118119120121122123124125126127128129127128129130131132133134135131132133134135136137138139140141142143144145146147148149150151152153154155156157158159136137138139140141142143144145146161162163164165147148149150151152167168169153154155156157171172158159160161162163164165166167168169170171172173174175import osimport timeimport sqlite3import sysimport loggingimport asynciofrom flask import Flaskfrom threading import Thread
# Import pyromod first to patch Pyrogramfrom pyromod import listen import shutilfrom datetime import datetime, timezonefrom typing import Dict, Optionalfrom pyrogram import Client, filtersfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
# --- Flask Server for Hugging Face ---web_app = Flask(__name__)
@web_app.route('/')def health_check(): return "Bot is Running", 200
def run_server(): # HF looks for port 7860 web_app.run(host="0.0.0.0", port=7860)
# --- Config ---API_ID = int(os.getenv("API_ID", 0))API_HASH = os.getenv("API_HASH")BOT_TOKEN = os.getenv("BOT_TOKEN")
# --- Database ---DB_PATH = "bot_data.db"
def init_db(): conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS history (user_id INTEGER, file_name TEXT, file_id TEXT)''') conn.commit() conn.close()
def add_to_history(user_id, name, fid): conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute("INSERT INTO history VALUES (?, ?, ?)", (user_id, name, fid)) conn.commit() conn.close()
def get_history(user_id): conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute("SELECT file_name, file_id FROM history WHERE user_id = ?", (user_id,)) rows = cursor.fetchall() conn.close() return rows
init_db()
# --- Bot Client ---app = Client( "FastRename", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN, workers=100 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))
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"))async def start_handler(client, message): await message.reply( "👋 **Hi! I am a High-Speed Renamer Bot.**\n\n" "Send me any file or video to start."
@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" "Use operational commands below to securely provision workspace tasks." )
@app.on_message(filters.document | filters.video | filters.audio)async def fast_process(client, message): user_id = message.from_user.id@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>`") # 1. Ask for name try: ask = await client.ask(message.chat.id, "📝 Send the **New Name** with extension:", timeout=60) new_name = ask.text except Exception: return await message.reply("❌ Timeout. Please send the file again.") status = await message.reply("⚡ **Preparing to Stream...**") start_time = time.time() lib = message.command[1] # Simple sanitization to prevent terminal injection flags if not lib.isalnum() and "_" not in lib and "-" not in lib: return await message.reply_text("❌ **Security Alert:** Invalid package schema structural characters.")
# 2. Download msg = await message.reply_text(f"⏳ `pip`: Provisioning `{lib}` dynamic environments...") try: path = await client.download_media( message, file_name=new_name, progress=progress_callback, progress_args=(status, start_time, "Downloading") 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: return await status.edit(f"❌ **Download Error:** {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}`...")
# 3. Upload await status.edit("🚀 **Upload Starting...**") start_up = time.time() try: sent_file = await client.send_document( chat_id=message.chat.id, document=path, caption=f"✅ **Done:** `{new_name}`", progress=progress_callback, progress_args=(status, start_up, "Uploading") # Production Fix: Run non-blocking using async subprocess, stripping env tokens for security 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 ) except Exception as e: return await status.edit(f"❌ **Upload Error:** {e}")
# 4. History & Cleanup file_obj = sent_file.document or sent_file.video or sent_file.audio add_to_history(user_id, new_name, file_obj.file_id)
if os.path.exists(path): os.remove(path) await status.delete()
async def progress_callback(current, total, status_msg, start_time, mode): now = time.time() diff = now - start_time if round(diff % 4.00) == 0 or current == total: speed = current / diff if diff > 0 else 0 eta = (total - current) / speed if speed > 0 else 0 curr_mb = current / (1024 * 1024) tot_mb = total / (1024 * 1024) speed_mb = speed / (1024 * 1024) ACTIVE_RUNS[filename] = (proc, datetime.now(timezone.utc)) # Schedule hard ceiling runtime watchdog task 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)}`")
try: await status_msg.edit( f"🚀 **{mode}**\n" f"**Size:** {curr_mb:.2f}/{tot_mb:.2f} MB\n" f"**Speed:** {speed_mb:.2f} MB/s\n" f"**ETA:** {int(eta)}s" ) except: pass
@app.on_message(filters.command("history"))async def show_history(client, message): rows = get_history(message.from_user.id) if not rows: return await message.reply("No history found.")
text = "📂 **Your Recent Files:**\n\n" buttons = [] # Show only the last 10 items to avoid long messages for idx, (name, fid) in enumerate(rows[-10:]): text += f"{idx+1}. `{name}`\n" buttons.append([InlineKeyboardButton(f"Get {name[:20]}", callback_data=f"get_{idx}")])
await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))
@app.on_callback_query(filters.regex(r"^get_"))async def send_from_history(client, query): idx = int(query.data.split("_")[1]) rows = get_history(query.from_user.id) # Be careful: indices in rows might change if new items are added@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: file_name, file_id = rows[idx] await client.send_document(query.message.chat.id, file_id, caption=f"Retrieved: {file_name}") except: await query.answer("File not found in history.") await query.answer() 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)}`")
if __name__ == "__main__": # Start Keep-Alive Thread Thread(target=run_server, daemon=True).start()@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 # Run Bot print("Bot started...") 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." # Calculate filesystem usage safety status 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)
# --- SYSTEM ENTRY FOR LIFECYCLE MANAGEMENT ---if __name__ == "__main__": logger.info("Booting production engine client context...") app.run()bot.py+155-153