Spaces:
Runtime error
Runtime error
Update bot.py
Browse files
bot.py
CHANGED
|
@@ -1,173 +1,175 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
import asyncio
|
| 5 |
-
|
| 6 |
-
from
|
| 7 |
-
|
| 8 |
-
# Import pyromod first to patch Pyrogram
|
| 9 |
-
from pyromod import listen
|
| 10 |
from pyrogram import Client, filters
|
| 11 |
-
from pyrogram.types import
|
| 12 |
-
|
| 13 |
-
# ---
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
# HF looks for port 7860
|
| 22 |
-
web_app.run(host="0.0.0.0", port=7860)
|
| 23 |
-
|
| 24 |
-
# --- Config ---
|
| 25 |
-
API_ID = int(os.getenv("API_ID", 0))
|
| 26 |
-
API_HASH = os.getenv("API_HASH")
|
| 27 |
-
BOT_TOKEN = os.getenv("BOT_TOKEN")
|
| 28 |
-
|
| 29 |
-
# --- Database ---
|
| 30 |
-
DB_PATH = "bot_data.db"
|
| 31 |
-
|
| 32 |
-
def init_db():
|
| 33 |
-
conn = sqlite3.connect(DB_PATH)
|
| 34 |
-
cursor = conn.cursor()
|
| 35 |
-
cursor.execute('''CREATE TABLE IF NOT EXISTS history
|
| 36 |
-
(user_id INTEGER, file_name TEXT, file_id TEXT)''')
|
| 37 |
-
conn.commit()
|
| 38 |
-
conn.close()
|
| 39 |
-
|
| 40 |
-
def add_to_history(user_id, name, fid):
|
| 41 |
-
conn = sqlite3.connect(DB_PATH)
|
| 42 |
-
cursor = conn.cursor()
|
| 43 |
-
cursor.execute("INSERT INTO history VALUES (?, ?, ?)", (user_id, name, fid))
|
| 44 |
-
conn.commit()
|
| 45 |
-
conn.close()
|
| 46 |
-
|
| 47 |
-
def get_history(user_id):
|
| 48 |
-
conn = sqlite3.connect(DB_PATH)
|
| 49 |
-
cursor = conn.cursor()
|
| 50 |
-
cursor.execute("SELECT file_name, file_id FROM history WHERE user_id = ?", (user_id,))
|
| 51 |
-
rows = cursor.fetchall()
|
| 52 |
-
conn.close()
|
| 53 |
-
return rows
|
| 54 |
-
|
| 55 |
-
init_db()
|
| 56 |
-
|
| 57 |
-
# --- Bot Client ---
|
| 58 |
-
app = Client(
|
| 59 |
-
"FastRename",
|
| 60 |
-
api_id=API_ID,
|
| 61 |
-
api_hash=API_HASH,
|
| 62 |
-
bot_token=BOT_TOKEN,
|
| 63 |
-
workers=100
|
| 64 |
)
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
)
|
| 72 |
|
| 73 |
-
@app.on_message(filters.
|
| 74 |
-
async def
|
| 75 |
-
|
|
|
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
except Exception:
|
| 82 |
-
return await message.reply("❌ Timeout. Please send the file again.")
|
| 83 |
-
|
| 84 |
-
status = await message.reply("⚡ **Preparing to Stream...**")
|
| 85 |
-
start_time = time.time()
|
| 86 |
|
| 87 |
-
|
|
|
|
| 88 |
try:
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
progress_args=(status, start_time, "Downloading")
|
| 94 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
except Exception as e:
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
-
# 3. Upload
|
| 99 |
-
await status.edit("🚀 **Upload Starting...**")
|
| 100 |
-
start_up = time.time()
|
| 101 |
try:
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
)
|
| 109 |
-
except Exception as e:
|
| 110 |
-
return await status.edit(f"❌ **Upload Error:** {e}")
|
| 111 |
-
|
| 112 |
-
# 4. History & Cleanup
|
| 113 |
-
file_obj = sent_file.document or sent_file.video or sent_file.audio
|
| 114 |
-
add_to_history(user_id, new_name, file_obj.file_id)
|
| 115 |
-
|
| 116 |
-
if os.path.exists(path):
|
| 117 |
-
os.remove(path)
|
| 118 |
-
await status.delete()
|
| 119 |
-
|
| 120 |
-
async def progress_callback(current, total, status_msg, start_time, mode):
|
| 121 |
-
now = time.time()
|
| 122 |
-
diff = now - start_time
|
| 123 |
-
if round(diff % 4.00) == 0 or current == total:
|
| 124 |
-
speed = current / diff if diff > 0 else 0
|
| 125 |
-
eta = (total - current) / speed if speed > 0 else 0
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
async def show_history(client, message):
|
| 142 |
-
rows = get_history(message.from_user.id)
|
| 143 |
-
if not rows:
|
| 144 |
-
return await message.reply("No history found.")
|
| 145 |
-
|
| 146 |
-
text = "📂 **Your Recent Files:**\n\n"
|
| 147 |
-
buttons = []
|
| 148 |
-
# Show only the last 10 items to avoid long messages
|
| 149 |
-
for idx, (name, fid) in enumerate(rows[-10:]):
|
| 150 |
-
text += f"{idx+1}. `{name}`\n"
|
| 151 |
-
buttons.append([InlineKeyboardButton(f"Get {name[:20]}", callback_data=f"get_{idx}")])
|
| 152 |
-
|
| 153 |
-
await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))
|
| 154 |
-
|
| 155 |
-
@app.on_callback_query(filters.regex(r"^get_"))
|
| 156 |
-
async def send_from_history(client, query):
|
| 157 |
-
idx = int(query.data.split("_")[1])
|
| 158 |
-
rows = get_history(query.from_user.id)
|
| 159 |
-
# Be careful: indices in rows might change if new items are added
|
| 160 |
try:
|
| 161 |
-
|
| 162 |
-
await
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
| 170 |
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
app.run()
|
|
|
|
| 1 |
import os
|
| 2 |
+
import sys
|
| 3 |
+
import logging
|
| 4 |
import asyncio
|
| 5 |
+
import shutil
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
from typing import Dict, Optional
|
|
|
|
|
|
|
| 8 |
from pyrogram import Client, filters
|
| 9 |
+
from pyrogram.types import Message
|
| 10 |
+
|
| 11 |
+
# --- STRUCTURED PRODUCTION LOGGING ---
|
| 12 |
+
logging.basicConfig(
|
| 13 |
+
level=logging.INFO,
|
| 14 |
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
| 15 |
+
handlers=[
|
| 16 |
+
logging.StreamHandler(sys.stdout),
|
| 17 |
+
logging.FileHandler("bot_production.log", encoding="utf-8")
|
| 18 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
)
|
| 20 |
+
logger = logging.getLogger("HostingBot")
|
| 21 |
+
|
| 22 |
+
# --- ENV CONFIGURATION & VALIDATION ---
|
| 23 |
+
API_ID = int(os.environ.get("API_ID", 0))
|
| 24 |
+
API_HASH = os.environ.get("API_HASH", "")
|
| 25 |
+
BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
|
| 26 |
+
OWNER_ID = int(os.environ.get("OWNER_ID", 0))
|
| 27 |
+
|
| 28 |
+
if not all([API_ID, API_HASH, BOT_TOKEN, OWNER_ID]):
|
| 29 |
+
logger.critical("Critical environment variables missing! Exiting application.")
|
| 30 |
+
sys.exit(1)
|
| 31 |
+
|
| 32 |
+
# --- TRACKING ENGINE ---
|
| 33 |
+
START_TIME = datetime.now(timezone.utc)
|
| 34 |
+
# Map structure: { filename: (asyncio.subprocess.Process, start_time) }
|
| 35 |
+
ACTIVE_RUNS: Dict[str, tuple] = {}
|
| 36 |
+
MAX_RUN_TIME = 3600 # Enforce hard timeout per user script (e.g., 1 hour)
|
| 37 |
+
|
| 38 |
+
# --- CLIENT INIT ---
|
| 39 |
+
app = Client("py_manager_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
|
| 40 |
+
|
| 41 |
+
# --- CUSTOM SECURITY FILTERS ---
|
| 42 |
+
def is_owner_filter(_, __, message: Message) -> bool:
|
| 43 |
+
return bool(message.from_user and message.from_user.id == OWNER_ID)
|
| 44 |
+
|
| 45 |
+
owner_only = filters.create(is_owner_filter)
|
| 46 |
+
|
| 47 |
+
# --- CORE UTILITIES / EXECUTION SANDBOX ---
|
| 48 |
+
async def enforce_process_timeout(filename: str, process: asyncio.subprocess.Process, timeout: int):
|
| 49 |
+
"""Monitors running jobs and forces cancellation if limits are exceeded."""
|
| 50 |
+
await asyncio.sleep(timeout)
|
| 51 |
+
if process.returncode is None:
|
| 52 |
+
try:
|
| 53 |
+
logger.warning(f"Process {filename} exceeded runtime limit. Forcing termination.")
|
| 54 |
+
process.terminate()
|
| 55 |
+
await process.wait()
|
| 56 |
+
except ProcessLookupError:
|
| 57 |
+
pass
|
| 58 |
+
finally:
|
| 59 |
+
ACTIVE_RUNS.pop(filename, None)
|
| 60 |
+
|
| 61 |
+
# --- COMMAND HANDLERS ---
|
| 62 |
+
|
| 63 |
+
@app.on_message(filters.command("start") & owner_only)
|
| 64 |
+
async def start_cmd(client: Client, message: Message):
|
| 65 |
+
await message.reply_text(
|
| 66 |
+
"⚡ **Production-Grade Python Host System Engine Online.** ⚡\n\n"
|
| 67 |
+
"Use operational commands below to securely provision workspace tasks."
|
| 68 |
)
|
| 69 |
|
| 70 |
+
@app.on_message(filters.command("install") & owner_only)
|
| 71 |
+
async def install_lib(client: Client, message: Message):
|
| 72 |
+
if len(message.command) < 2:
|
| 73 |
+
return await message.reply_text("❌ **Usage:** `/install <library_name>`")
|
| 74 |
|
| 75 |
+
lib = message.command[1]
|
| 76 |
+
# Simple sanitization to prevent terminal injection flags
|
| 77 |
+
if not lib.isalnum() and "_" not in lib and "-" not in lib:
|
| 78 |
+
return await message.reply_text("❌ **Security Alert:** Invalid package schema structural characters.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
msg = await message.reply_text(f"⏳ `pip`: Provisioning `{lib}` dynamic environments...")
|
| 81 |
+
|
| 82 |
try:
|
| 83 |
+
proc = await asyncio.create_subprocess_exec(
|
| 84 |
+
sys.executable, "-m", "pip", "install", "--no-cache-dir", lib,
|
| 85 |
+
stdout=asyncio.subprocess.PIPE,
|
| 86 |
+
stderr=asyncio.subprocess.PIPE
|
|
|
|
| 87 |
)
|
| 88 |
+
stdout, stderr = await proc.communicate()
|
| 89 |
+
|
| 90 |
+
if proc.returncode == 0:
|
| 91 |
+
await msg.edit_text(f"✅ Successfully installed package environment: `{lib}`.")
|
| 92 |
+
else:
|
| 93 |
+
error_log = stderr.decode().strip() or stdout.decode().strip()
|
| 94 |
+
logger.error(f"Installation failed for {lib}: {error_log}")
|
| 95 |
+
await msg.edit_text(f"❌ **Pip Engine failure context:**\n`{error_log[:300]}`")
|
| 96 |
except Exception as e:
|
| 97 |
+
logger.exception("Exception hit during pip installation invocation")
|
| 98 |
+
await msg.edit_text(f"❌ **System Execution Failure:** `{str(e)}`")
|
| 99 |
+
|
| 100 |
+
@app.on_message(filters.command("run") & owner_only)
|
| 101 |
+
async def run_script(client: Client, message: Message):
|
| 102 |
+
if len(message.command) < 2:
|
| 103 |
+
return await message.reply_text("❌ **Usage:** `/run <filename.py>`")
|
| 104 |
+
|
| 105 |
+
filename = message.command[1]
|
| 106 |
+
if not os.path.exists(filename):
|
| 107 |
+
return await message.reply_text(f"❌ Reference target file `{filename}` does not exist in context.")
|
| 108 |
+
|
| 109 |
+
if filename in ACTIVE_RUNS:
|
| 110 |
+
return await message.reply_text(f"⚠️ Target context instance `{filename}` is already actively executing.")
|
| 111 |
+
|
| 112 |
+
msg = await message.reply_text(f"🚀 Initializing isolated execution instance for `{filename}`...")
|
| 113 |
|
|
|
|
|
|
|
|
|
|
| 114 |
try:
|
| 115 |
+
# Production Fix: Run non-blocking using async subprocess, stripping env tokens for security
|
| 116 |
+
clean_env = os.environ.copy()
|
| 117 |
+
clean_env.pop("BOT_TOKEN", None)
|
| 118 |
+
clean_env.pop("API_HASH", None)
|
| 119 |
+
|
| 120 |
+
proc = await asyncio.create_subprocess_exec(
|
| 121 |
+
sys.executable, filename,
|
| 122 |
+
stdout=asyncio.subprocess.PIPE,
|
| 123 |
+
stderr=asyncio.subprocess.PIPE,
|
| 124 |
+
env=clean_env
|
| 125 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
+
ACTIVE_RUNS[filename] = (proc, datetime.now(timezone.utc))
|
| 128 |
+
# Schedule hard ceiling runtime watchdog task
|
| 129 |
+
asyncio.create_task(enforce_process_timeout(filename, proc, MAX_RUN_TIME))
|
| 130 |
+
|
| 131 |
+
await msg.edit_text(f"✅ Instance running. Tracking ID context: `{filename}`. Watchdog active.")
|
| 132 |
+
except Exception as e:
|
| 133 |
+
logger.exception("Failed to initialize script engine runtime.")
|
| 134 |
+
await msg.edit_text(f"❌ **Runtime Dispatch Error:** `{str(e)}`")
|
| 135 |
|
| 136 |
+
@app.on_message(filters.command("stop") & owner_only)
|
| 137 |
+
async def stop_script(client: Client, message: Message):
|
| 138 |
+
if len(message.command) < 2:
|
| 139 |
+
return await message.reply_text("❌ **Usage:** `/stop <filename.py>`")
|
| 140 |
+
|
| 141 |
+
filename = message.command[1]
|
| 142 |
+
if filename not in ACTIVE_RUNS:
|
| 143 |
+
return await message.reply_text(f"❌ Active workspace process context not found for `{filename}`.")
|
| 144 |
+
|
| 145 |
+
proc, _ = ACTIVE_RUNS.pop(filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
try:
|
| 147 |
+
proc.terminate()
|
| 148 |
+
await proc.wait()
|
| 149 |
+
await message.reply_text(f"🛑 Cleanly terminated process context instance: `{filename}`.")
|
| 150 |
+
except Exception as e:
|
| 151 |
+
await message.reply_text(f"❌ **Error while killing process context:** `{str(e)}`")
|
| 152 |
|
| 153 |
+
@app.on_message(filters.command("status") & owner_only)
|
| 154 |
+
async def system_status(client: Client, message: Message):
|
| 155 |
+
now = datetime.now(timezone.utc)
|
| 156 |
+
uptime = now - START_TIME
|
| 157 |
|
| 158 |
+
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."
|
| 159 |
+
|
| 160 |
+
# Calculate filesystem usage safety status
|
| 161 |
+
total, used, free = shutil.disk_usage(".")
|
| 162 |
+
|
| 163 |
+
status_msg = (
|
| 164 |
+
f"📊 **System Production Analytics Engine**\n"
|
| 165 |
+
f"‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾\n"
|
| 166 |
+
f"⏱️ **Core Engine Uptime:** `{str(uptime).split('.')[0]}`\n"
|
| 167 |
+
f"💽 **Disk Allocation:** Used {used // (2**20)}MB / {total // (2**20)}MB ({free // (2**20)}MB Free)\n\n"
|
| 168 |
+
f"⚡ **Active Sandboxes Runtime ({len(ACTIVE_RUNS)}):**\n{active_jobs_str}"
|
| 169 |
+
)
|
| 170 |
+
await message.reply_text(status_msg)
|
| 171 |
+
|
| 172 |
+
# --- SYSTEM ENTRY FOR LIFECYCLE MANAGEMENT ---
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
logger.info("Booting production engine client context...")
|
| 175 |
app.run()
|