Spaces:
Runtime error

dpadhan commited on
Commit
11c938f
Β·
verified Β·
1 Parent(s): 4a8764a

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +80 -8
bot.py CHANGED
@@ -3,6 +3,7 @@ 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
@@ -25,6 +26,9 @@ 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)
@@ -64,21 +68,94 @@ async def enforce_process_timeout(filename: str, process: asyncio.subprocess.Pro
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,
@@ -112,7 +189,6 @@ async def run_script(client: Client, message: Message):
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)
@@ -125,7 +201,6 @@ async def run_script(client: Client, message: Message):
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.")
@@ -156,8 +231,6 @@ async def system_status(client: Client, message: Message):
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 = (
@@ -169,7 +242,6 @@ async def system_status(client: Client, message: Message):
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()
 
3
  import logging
4
  import asyncio
5
  import shutil
6
+ import glob
7
  from datetime import datetime, timezone
8
  from typing import Dict, Optional
9
  from pyrogram import Client, filters
 
26
  BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
27
  OWNER_ID = int(os.environ.get("OWNER_ID", 0))
28
 
29
+ # Save the bot's own filename dynamically so it never deletes itself
30
+ BOT_SCRIPT_NAME = os.path.basename(__file__)
31
+
32
  if not all([API_ID, API_HASH, BOT_TOKEN, OWNER_ID]):
33
  logger.critical("Critical environment variables missing! Exiting application.")
34
  sys.exit(1)
 
68
  async def start_cmd(client: Client, message: Message):
69
  await message.reply_text(
70
  "⚑ **Production-Grade Python Host System Engine Online.** ⚑\n\n"
71
+ "**Available Commands:**\n"
72
+ "β€’ `/upload` - Send/reply to a `.py` file with this command to upload it.\n"
73
+ "β€’ `/run <filename.py>` - Run an uploaded script.\n"
74
+ "β€’ `/stop <filename.py>` - Stop a running script.\n"
75
+ "β€’ `/status` - Check resource usage and active tasks.\n"
76
+ "β€’ `/clear` - Preview and wipe generated/uploaded script files."
77
  )
78
 
79
+ @app.on_message(filters.command("upload") & owner_only)
80
+ async def upload_file(client: Client, message: Message):
81
+ # Check if the command is on a document message or replying to one
82
+ target_msg = message.reply_to_message if message.reply_to_message else message
83
+
84
+ if not target_msg.document:
85
+ return await message.reply_text("❌ **Error:** Please use `/upload` as a caption on a file document or reply to a file document.")
86
+
87
+ filename = target_msg.document.file_name
88
+
89
+ # Simple restriction to keep the environment clean
90
+ if not filename.endswith(".py"):
91
+ return await message.reply_text("❌ **Security Reject:** Only Python scripts (`.py`) can be uploaded to this engine workspace.")
92
+
93
+ status_msg = await message.reply_text(f"πŸ“₯ Downloading `{filename}` into workspace environment...")
94
+
95
+ try:
96
+ # Download the file directly to the current working directory
97
+ await target_msg.download(file_name=os.path.join(os.getcwd(), filename))
98
+ await status_msg.edit_text(f"βœ… File `{filename}` has been provisioned successfully. Ready to execute using `/run {filename}`.")
99
+ except Exception as e:
100
+ logger.exception("Failed to download file.")
101
+ await status_msg.edit_text(f"❌ **Upload Failed:** `{str(e)}`")
102
+
103
+ @app.on_message(filters.command("clear") & owner_only)
104
+ async def clear_workspace(client: Client, message: Message):
105
+ # Stop any active tasks first to prevent file locks
106
+ if ACTIVE_RUNS:
107
+ await message.reply_text("⚠️ **Notice:** Stopping all actively running process instances before wiping workspace...")
108
+ for filename, (proc, _) in list(ACTIVE_RUNS.items()):
109
+ try:
110
+ proc.terminate()
111
+ await proc.wait()
112
+ except Exception:
113
+ pass
114
+ ACTIVE_RUNS.clear()
115
+
116
+ # Gather files to delete: .py, .log, .txt files (ignoring the main bot script itself)
117
+ all_files = glob.glob("*.py") + glob.glob("*.log") + glob.glob("*.txt")
118
+ files_to_delete = [f for f in all_files if f != BOT_SCRIPT_NAME]
119
+
120
+ if not files_to_delete:
121
+ return await message.reply_text("✨ Workspace is already clear. No ephemeral data found.")
122
+
123
+ # 1. Send the file listing preview first
124
+ preview_list = "\n".join([f"β€’ `{f}`" for f in files_to_delete])
125
+ preview_msg = f"πŸ—‘οΈ **Purging Workspace Engine...**\n\n**The following files will be deleted permanently:**\n{preview_list}"
126
+ await message.reply_text(preview_msg)
127
+
128
+ # Minor artificial pause to let the user read what is being deleted
129
+ await asyncio.sleep(1.5)
130
+
131
+ # 2. Execute deletion sequence
132
+ deleted_count = 0
133
+ failed_count = 0
134
+
135
+ for file_path in files_to_delete:
136
+ try:
137
+ os.remove(file_path)
138
+ deleted_count += 1
139
+ except Exception as e:
140
+ logger.error(f"Failed to delete {file_path}: {e}")
141
+ failed_count += 1
142
+
143
+ result_text = f"βœ… **Purge Cycle Complete.**\nβ€’ Successfully deleted `{deleted_count}` files."
144
+ if failed_count > 0:
145
+ result_text += f"\nβ€’ ⚠️ Failed to delete `{failed_count}` locked system elements."
146
+
147
+ await message.reply_text(result_text)
148
+
149
  @app.on_message(filters.command("install") & owner_only)
150
  async def install_lib(client: Client, message: Message):
151
  if len(message.command) < 2:
152
  return await message.reply_text("❌ **Usage:** `/install <library_name>`")
153
 
154
  lib = message.command[1]
 
155
  if not lib.isalnum() and "_" not in lib and "-" not in lib:
156
  return await message.reply_text("❌ **Security Alert:** Invalid package schema structural characters.")
157
 
158
  msg = await message.reply_text(f"⏳ `pip`: Provisioning `{lib}` dynamic environments...")
 
159
  try:
160
  proc = await asyncio.create_subprocess_exec(
161
  sys.executable, "-m", "pip", "install", "--no-cache-dir", lib,
 
189
  msg = await message.reply_text(f"πŸš€ Initializing isolated execution instance for `{filename}`...")
190
 
191
  try:
 
192
  clean_env = os.environ.copy()
193
  clean_env.pop("BOT_TOKEN", None)
194
  clean_env.pop("API_HASH", None)
 
201
  )
202
 
203
  ACTIVE_RUNS[filename] = (proc, datetime.now(timezone.utc))
 
204
  asyncio.create_task(enforce_process_timeout(filename, proc, MAX_RUN_TIME))
205
 
206
  await msg.edit_text(f"βœ… Instance running. Tracking ID context: `{filename}`. Watchdog active.")
 
231
  uptime = now - START_TIME
232
 
233
  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."
 
 
234
  total, used, free = shutil.disk_usage(".")
235
 
236
  status_msg = (
 
242
  )
243
  await message.reply_text(status_msg)
244
 
 
245
  if __name__ == "__main__":
246
  logger.info("Booting production engine client context...")
247
  app.run()