Spaces:
Runtime error

dpadhan commited on
Commit
cc560ef
·
verified ·
1 Parent(s): 12582a7

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +155 -153
bot.py CHANGED
@@ -1,173 +1,175 @@
1
  import os
2
- import time
3
- import sqlite3
4
  import asyncio
5
- from flask import Flask
6
- from threading import Thread
7
-
8
- # Import pyromod first to patch Pyrogram
9
- from pyromod import listen
10
  from pyrogram import Client, filters
11
- from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
12
-
13
- # --- Flask Server for Hugging Face ---
14
- web_app = Flask(__name__)
15
-
16
- @web_app.route('/')
17
- def health_check():
18
- return "Bot is Running", 200
19
-
20
- def run_server():
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
- @app.on_message(filters.command("start"))
67
- async def start_handler(client, message):
68
- await message.reply(
69
- "👋 **Hi! I am a High-Speed Renamer Bot.**\n\n"
70
- "Send me any file or video to start."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  )
72
 
73
- @app.on_message(filters.document | filters.video | filters.audio)
74
- async def fast_process(client, message):
75
- user_id = message.from_user.id
 
76
 
77
- # 1. Ask for name
78
- try:
79
- ask = await client.ask(message.chat.id, "📝 Send the **New Name** with extension:", timeout=60)
80
- new_name = ask.text
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
- # 2. Download
 
88
  try:
89
- path = await client.download_media(
90
- message,
91
- file_name=new_name,
92
- progress=progress_callback,
93
- progress_args=(status, start_time, "Downloading")
94
  )
 
 
 
 
 
 
 
 
95
  except Exception as e:
96
- return await status.edit(f"❌ **Download Error:** {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
- # 3. Upload
99
- await status.edit("🚀 **Upload Starting...**")
100
- start_up = time.time()
101
  try:
102
- sent_file = await client.send_document(
103
- chat_id=message.chat.id,
104
- document=path,
105
- caption=f"✅ **Done:** `{new_name}`",
106
- progress=progress_callback,
107
- progress_args=(status, start_up, "Uploading")
 
 
 
 
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
- curr_mb = current / (1024 * 1024)
128
- tot_mb = total / (1024 * 1024)
129
- speed_mb = speed / (1024 * 1024)
 
 
 
 
 
130
 
131
- try:
132
- await status_msg.edit(
133
- f"🚀 **{mode}**\n"
134
- f"**Size:** {curr_mb:.2f}/{tot_mb:.2f} MB\n"
135
- f"**Speed:** {speed_mb:.2f} MB/s\n"
136
- f"**ETA:** {int(eta)}s"
137
- )
138
- except: pass
139
-
140
- @app.on_message(filters.command("history"))
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
- file_name, file_id = rows[idx]
162
- await client.send_document(query.message.chat.id, file_id, caption=f"Retrieved: {file_name}")
163
- except:
164
- await query.answer("File not found in history.")
165
- await query.answer()
166
 
167
- if __name__ == "__main__":
168
- # Start Keep-Alive Thread
169
- Thread(target=run_server, daemon=True).start()
 
170
 
171
- # Run Bot
172
- print("Bot started...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()