file / app.py
Kanhshsh's picture
Update app.py
7723ce0 verified
raw
history blame
4.62 kB
import gradio as gr
import subprocess
import asyncio
import threading
from queue import Queue, Empty
import os
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
BOT_TOKEN = os.environ.get("BOT_TOKEN") # Set it only via environment for safety
log_queue = Queue()
MAX_LOGS = 20000
terminal_logs = []
bot_logs = []
bot_app = None
bot_running = False
bot_thread = None
# --- Telegram Handler ---
async def bash_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
cmd = ' '.join(context.args)
if not cmd:
await update.message.reply_text("Usage: /bash <command>")
return
entry = f"[Bot] $ {cmd}"
log_queue.put(entry)
add_bot_log(entry)
try:
proc = await asyncio.create_subprocess_shell(cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)
stdout, _ = await proc.communicate()
output = stdout.decode().strip()
if len(output) > 4000:
output = output[:4000] + "\n...[truncated]"
except Exception as e:
output = f"Error: {e}"
result = f"$ {cmd}\n{output}"
log_queue.put(result)
add_bot_log(result)
await update.message.reply_text(result)
# --- Logging Functions ---
def add_terminal_log(entry):
terminal_logs.append(entry)
if len(terminal_logs) > MAX_LOGS:
del terminal_logs[0]
def add_bot_log(entry):
bot_logs.append(entry)
if len(bot_logs) > MAX_LOGS:
del bot_logs[0]
# --- Terminal ---
def live_terminal(cmd):
if not cmd.strip():
yield "$ "
return
yield f"$ {cmd}\n"
try:
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
for line in iter(proc.stdout.readline, ''):
line = line.strip()
log_queue.put(line)
add_terminal_log(line)
yield line + "\n"
proc.stdout.close()
proc.wait()
except Exception as e:
error = f"[Error] {e}"
log_queue.put(error)
add_terminal_log(error)
yield error + "\n"
yield "$ "
# --- Bot ---
def start_bot():
global bot_app, bot_running, bot_thread
if bot_running or not BOT_TOKEN:
log_queue.put("[Bot] Already running or token missing.")
return
async def run_bot():
global bot_app
bot_app = ApplicationBuilder().token(BOT_TOKEN).build()
bot_app.add_handler(CommandHandler("bash", bash_command))
log_queue.put("[Bot] Starting bot...")
await bot_app.run_polling()
def runner():
asyncio.run(run_bot())
bot_thread = threading.Thread(target=runner, daemon=True)
bot_thread.start()
bot_running = True
log_queue.put("[Bot] Bot started.")
def stop_bot():
global bot_app, bot_running
if not bot_running:
log_queue.put("[Bot] Bot not running.")
return
async def shutdown():
await bot_app.shutdown()
await bot_app.stop()
log_queue.put("[Bot] Bot stopped.")
asyncio.run(shutdown())
bot_running = False
# --- UI Log Updates ---
def update_terminal_logs():
return "\n".join(terminal_logs[-100:])
def update_bot_logs():
return "\n".join(bot_logs[-100:])
# --- Gradio UI ---
with gr.Blocks() as demo:
gr.Markdown("## πŸ–₯️ Terminal + πŸ€– Telegram Bot (Live Logs)")
with gr.Row():
terminal_output = gr.Textbox(label="πŸ“Ÿ Terminal Output", lines=20, interactive=False)
bot_output = gr.Textbox(label="πŸ€– Telegram Bot Logs", lines=20, interactive=False)
with gr.Row():
cmd_input = gr.Textbox(placeholder="Enter shell command", label="Command Input")
run_btn = gr.Button("▢️ Run Command")
with gr.Row():
start_btn = gr.Button("πŸš€ Start Telegram Bot")
stop_btn = gr.Button("πŸ›‘ Stop Telegram Bot")
run_btn.click(fn=live_terminal, inputs=cmd_input, outputs=terminal_output)
def handle_start():
start_bot()
return update_bot_logs()
def handle_stop():
stop_bot()
return update_bot_logs()
start_btn.click(fn=handle_start, outputs=bot_output)
stop_btn.click(fn=handle_stop, outputs=bot_output)
def auto_update_terminal():
while True:
import time; time.sleep(3)
yield update_terminal_logs()
def auto_update_bot():
while True:
import time; time.sleep(3)
yield update_bot_logs()
demo.load(fn=auto_update_terminal, outputs=terminal_output)
demo.load(fn=auto_update_bot, outputs=bot_output)
demo.launch()