Kanhshsh commited on
Commit
17ce298
Β·
verified Β·
1 Parent(s): 7723ce0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -87
app.py CHANGED
@@ -2,12 +2,13 @@ import gradio as gr
2
  import subprocess
3
  import asyncio
4
  import threading
5
- from queue import Queue, Empty
6
  import os
 
7
  from telegram import Update
8
  from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
9
 
10
- BOT_TOKEN = os.environ.get("BOT_TOKEN") # Set it only via environment for safety
11
 
12
  log_queue = Queue()
13
  MAX_LOGS = 20000
@@ -16,79 +17,82 @@ bot_logs = []
16
  bot_app = None
17
  bot_running = False
18
  bot_thread = None
 
19
 
20
- # --- Telegram Handler ---
21
- async def bash_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
22
- cmd = ' '.join(context.args)
23
- if not cmd:
24
- await update.message.reply_text("Usage: /bash <command>")
25
- return
26
-
27
- entry = f"[Bot] $ {cmd}"
28
- log_queue.put(entry)
29
- add_bot_log(entry)
30
-
31
- try:
32
- proc = await asyncio.create_subprocess_shell(cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)
33
- stdout, _ = await proc.communicate()
34
- output = stdout.decode().strip()
35
- if len(output) > 4000:
36
- output = output[:4000] + "\n...[truncated]"
37
- except Exception as e:
38
- output = f"Error: {e}"
39
-
40
- result = f"$ {cmd}\n{output}"
41
- log_queue.put(result)
42
- add_bot_log(result)
43
- await update.message.reply_text(result)
44
-
45
- # --- Logging Functions ---
46
  def add_terminal_log(entry):
47
  terminal_logs.append(entry)
48
  if len(terminal_logs) > MAX_LOGS:
49
- del terminal_logs[0]
50
 
51
  def add_bot_log(entry):
52
  bot_logs.append(entry)
53
  if len(bot_logs) > MAX_LOGS:
54
- del bot_logs[0]
55
-
56
- # --- Terminal ---
57
- def live_terminal(cmd):
58
- if not cmd.strip():
59
- yield "$ "
60
- return
61
- yield f"$ {cmd}\n"
62
-
63
- try:
64
- proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  for line in iter(proc.stdout.readline, ''):
66
  line = line.strip()
67
- log_queue.put(line)
68
- add_terminal_log(line)
69
- yield line + "\n"
70
  proc.stdout.close()
71
  proc.wait()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  except Exception as e:
73
- error = f"[Error] {e}"
74
- log_queue.put(error)
75
- add_terminal_log(error)
76
- yield error + "\n"
77
- yield "$ "
78
 
79
- # --- Bot ---
 
 
 
80
  def start_bot():
81
  global bot_app, bot_running, bot_thread
82
-
83
  if bot_running or not BOT_TOKEN:
84
- log_queue.put("[Bot] Already running or token missing.")
85
  return
86
 
87
  async def run_bot():
88
  global bot_app
89
  bot_app = ApplicationBuilder().token(BOT_TOKEN).build()
90
  bot_app.add_handler(CommandHandler("bash", bash_command))
91
- log_queue.put("[Bot] Starting bot...")
92
  await bot_app.run_polling()
93
 
94
  def runner():
@@ -97,69 +101,77 @@ def start_bot():
97
  bot_thread = threading.Thread(target=runner, daemon=True)
98
  bot_thread.start()
99
  bot_running = True
100
- log_queue.put("[Bot] Bot started.")
101
 
102
  def stop_bot():
103
  global bot_app, bot_running
104
  if not bot_running:
105
- log_queue.put("[Bot] Bot not running.")
106
  return
107
 
108
  async def shutdown():
109
  await bot_app.shutdown()
110
  await bot_app.stop()
111
- log_queue.put("[Bot] Bot stopped.")
112
 
113
  asyncio.run(shutdown())
114
  bot_running = False
115
 
116
- # --- UI Log Updates ---
117
  def update_terminal_logs():
118
  return "\n".join(terminal_logs[-100:])
119
 
120
  def update_bot_logs():
121
  return "\n".join(bot_logs[-100:])
122
 
 
 
 
 
 
 
 
 
 
123
  # --- Gradio UI ---
124
  with gr.Blocks() as demo:
125
- gr.Markdown("## πŸ–₯️ Terminal + πŸ€– Telegram Bot (Live Logs)")
126
-
127
- with gr.Row():
128
- terminal_output = gr.Textbox(label="πŸ“Ÿ Terminal Output", lines=20, interactive=False)
129
- bot_output = gr.Textbox(label="πŸ€– Telegram Bot Logs", lines=20, interactive=False)
130
-
131
- with gr.Row():
132
- cmd_input = gr.Textbox(placeholder="Enter shell command", label="Command Input")
133
- run_btn = gr.Button("▢️ Run Command")
134
 
135
- with gr.Row():
136
- start_btn = gr.Button("πŸš€ Start Telegram Bot")
137
- stop_btn = gr.Button("πŸ›‘ Stop Telegram Bot")
 
 
138
 
139
- run_btn.click(fn=live_terminal, inputs=cmd_input, outputs=terminal_output)
 
140
 
141
- def handle_start():
142
- start_bot()
143
- return update_bot_logs()
144
 
145
- def handle_stop():
146
- stop_bot()
147
- return update_bot_logs()
 
 
 
 
148
 
149
- start_btn.click(fn=handle_start, outputs=bot_output)
150
- stop_btn.click(fn=handle_stop, outputs=bot_output)
 
 
 
151
 
152
- def auto_update_terminal():
153
- while True:
154
- import time; time.sleep(3)
155
- yield update_terminal_logs()
156
 
157
- def auto_update_bot():
158
- while True:
159
- import time; time.sleep(3)
160
- yield update_bot_logs()
161
 
162
- demo.load(fn=auto_update_terminal, outputs=terminal_output)
163
- demo.load(fn=auto_update_bot, outputs=bot_output)
164
 
 
165
  demo.launch()
 
2
  import subprocess
3
  import asyncio
4
  import threading
5
+ from queue import Queue
6
  import os
7
+ import shlex
8
  from telegram import Update
9
  from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
10
 
11
+ BOT_TOKEN = os.environ.get("BOT_TOKEN")
12
 
13
  log_queue = Queue()
14
  MAX_LOGS = 20000
 
17
  bot_app = None
18
  bot_running = False
19
  bot_thread = None
20
+ current_dir = os.getcwd()
21
 
22
+ # --- Logging ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def add_terminal_log(entry):
24
  terminal_logs.append(entry)
25
  if len(terminal_logs) > MAX_LOGS:
26
+ terminal_logs.pop(0)
27
 
28
  def add_bot_log(entry):
29
  bot_logs.append(entry)
30
  if len(bot_logs) > MAX_LOGS:
31
+ bot_logs.pop(0)
32
+
33
+ # --- Command Execution ---
34
+ def execute_command(cmd):
35
+ global current_dir
36
+ output = []
37
+ add_terminal_log(f"$ {cmd}")
38
+ if cmd.strip().startswith("cd"):
39
+ parts = shlex.split(cmd)
40
+ if len(parts) > 1:
41
+ new_path = os.path.join(current_dir, parts[1])
42
+ if os.path.isdir(new_path):
43
+ current_dir = os.path.abspath(new_path)
44
+ msg = f"Changed directory to {current_dir}"
45
+ output.append(msg)
46
+ add_terminal_log(msg)
47
+ else:
48
+ msg = f"Directory not found: {new_path}"
49
+ output.append(msg)
50
+ add_terminal_log(msg)
51
+ else:
52
+ msg = "Usage: cd <path>"
53
+ output.append(msg)
54
+ add_terminal_log(msg)
55
+ else:
56
+ proc = subprocess.Popen(cmd, cwd=current_dir, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
57
  for line in iter(proc.stdout.readline, ''):
58
  line = line.strip()
59
+ if line:
60
+ output.append(line)
61
+ add_terminal_log(line)
62
  proc.stdout.close()
63
  proc.wait()
64
+ return "\n".join(output)
65
+
66
+ # --- Telegram Bot Handlers ---
67
+ async def bash_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
68
+ cmd = ' '.join(context.args)
69
+ if not cmd:
70
+ await update.message.reply_text("Usage: /bash <command>")
71
+ return
72
+
73
+ prefix = f"[Bot] $ {cmd}"
74
+ add_bot_log(prefix)
75
+
76
+ try:
77
+ result = execute_command(cmd)
78
  except Exception as e:
79
+ result = f"Error: {e}"
 
 
 
 
80
 
81
+ add_bot_log(result)
82
+ await update.message.reply_text(f"$ {cmd}\n{result}")
83
+
84
+ # --- Bot Start/Stop Logic ---
85
  def start_bot():
86
  global bot_app, bot_running, bot_thread
 
87
  if bot_running or not BOT_TOKEN:
88
+ add_bot_log("[Bot] Already running or token missing.")
89
  return
90
 
91
  async def run_bot():
92
  global bot_app
93
  bot_app = ApplicationBuilder().token(BOT_TOKEN).build()
94
  bot_app.add_handler(CommandHandler("bash", bash_command))
95
+ add_bot_log("[Bot] Starting bot...")
96
  await bot_app.run_polling()
97
 
98
  def runner():
 
101
  bot_thread = threading.Thread(target=runner, daemon=True)
102
  bot_thread.start()
103
  bot_running = True
104
+ add_bot_log("[Bot] Bot started.")
105
 
106
  def stop_bot():
107
  global bot_app, bot_running
108
  if not bot_running:
109
+ add_bot_log("[Bot] Bot not running.")
110
  return
111
 
112
  async def shutdown():
113
  await bot_app.shutdown()
114
  await bot_app.stop()
115
+ add_bot_log("[Bot] Bot stopped.")
116
 
117
  asyncio.run(shutdown())
118
  bot_running = False
119
 
120
+ # --- UI Update Functions ---
121
  def update_terminal_logs():
122
  return "\n".join(terminal_logs[-100:])
123
 
124
  def update_bot_logs():
125
  return "\n".join(bot_logs[-100:])
126
 
127
+ def live_terminal(cmd):
128
+ result = [f"$ {cmd}"]
129
+ try:
130
+ result.append(execute_command(cmd))
131
+ except Exception as e:
132
+ result.append(f"[Error] {e}")
133
+ result.append(f"$ {current_dir} >")
134
+ return "\n".join(result)
135
+
136
  # --- Gradio UI ---
137
  with gr.Blocks() as demo:
138
+ with gr.Tab("πŸ’» Terminal"):
139
+ gr.Markdown("## πŸ–₯️ Interactive Terminal")
 
 
 
 
 
 
 
140
 
141
+ with gr.Row():
142
+ terminal_output = gr.Textbox(label="πŸ“Ÿ Terminal Output", lines=20, interactive=False)
143
+ with gr.Row():
144
+ cmd_input = gr.Textbox(placeholder="Enter shell command", label="Command Input")
145
+ run_btn = gr.Button("▢️ Run Command")
146
 
147
+ run_btn.click(fn=live_terminal, inputs=cmd_input, outputs=terminal_output)
148
+ demo.load(fn=lambda: update_terminal_logs(), outputs=terminal_output, every=3)
149
 
150
+ with gr.Tab("πŸ€– Telegram Bot"):
151
+ gr.Markdown("## πŸ€– Telegram Bot Controls")
 
152
 
153
+ with gr.Row():
154
+ bot_output = gr.Textbox(label="πŸ€– Telegram Bot Logs", lines=20, interactive=False)
155
+ with gr.Row():
156
+ token_box = gr.Textbox(label="Bot Token", placeholder="Enter Telegram Bot Token")
157
+ with gr.Row():
158
+ start_btn = gr.Button("πŸš€ Start Telegram Bot")
159
+ stop_btn = gr.Button("πŸ›‘ Stop Telegram Bot")
160
 
161
+ def set_token_and_start(token):
162
+ global BOT_TOKEN
163
+ BOT_TOKEN = token
164
+ start_bot()
165
+ return update_bot_logs()
166
 
167
+ start_btn.click(fn=set_token_and_start, inputs=token_box, outputs=bot_output)
 
 
 
168
 
169
+ def handle_stop():
170
+ stop_bot()
171
+ return update_bot_logs()
 
172
 
173
+ stop_btn.click(fn=handle_stop, outputs=bot_output)
174
+ demo.load(fn=lambda: update_bot_logs(), outputs=bot_output, every=3)
175
 
176
+ # --- Launch the App ---
177
  demo.launch()