file / app.py
Kanhshsh's picture
Update app.py
479d580 verified
raw
history blame
4.17 kB
import gradio as gr
import subprocess
import asyncio
import threading
from queue import Queue, Empty
import os
import time
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
BOT_TOKEN = os.environ.get("BOT_TOKEN", "7510817339:AAHFZoFzPkUO_-nAwfh9bjY_qHsWMprM2PI")
bot_app = None
bot_thread = None
bot_running = False
log_queue = Queue()
telegram_cmd_logs = []
# --- Telegram Bot Handlers ---
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
log_queue.put(f"[Telegram] Received command: {cmd}")
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 running command: {e}"
await update.message.reply_text(f"$ {cmd}\n{output}")
telegram_cmd_logs.append(f"$ {cmd}\n{output}")
if len(telegram_cmd_logs) > 50:
telegram_cmd_logs.pop(0)
def start_bot():
global bot_app, bot_running, bot_thread
if bot_running:
log_queue.put("[Bot] Already running.")
return
async def run_bot():
global bot_app, bot_running
bot_app = ApplicationBuilder().token(BOT_TOKEN).build()
bot_app.add_handler(CommandHandler("bash", bash_command))
bot_running = True
log_queue.put("[Bot] Bot started.")
await bot_app.run_polling()
loop = asyncio.new_event_loop()
def runner():
asyncio.set_event_loop(loop)
loop.run_until_complete(run_bot())
bot_thread = threading.Thread(target=runner, daemon=True)
bot_thread.start()
def stop_bot():
global bot_app, bot_running
if not bot_running:
log_queue.put("[Bot] Bot is 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
# --- Terminal Execution ---
def live_terminal(cmd):
if not cmd.strip():
yield "$ "
return
yield f"$ {cmd}\n"
process = subprocess.Popen(
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
)
for line in iter(process.stdout.readline, ''):
yield line
process.stdout.close()
process.wait()
yield "$ "
def run_terminal(cmd):
return live_terminal(cmd)
# --- Log Update Function ---
def update_log_box():
logs = []
try:
while True:
log = log_queue.get_nowait()
logs.append(log)
except Empty:
pass
logs.extend(telegram_cmd_logs[-20:])
return "\n".join(logs[-20:])
# --- Gradio UI ---
with gr.Blocks() as demo:
gr.Markdown("## 🖥️ Live Terminal + Telegram Bot Interface")
with gr.Row():
terminal_output = gr.Textbox(value="$ ", label="Live Terminal", lines=20, interactive=False)
cmd_input = gr.Textbox(placeholder="Type command here", label="Command Input")
with gr.Row():
start_btn = gr.Button("▶️ Start Telegram Bot")
stop_btn = gr.Button("⏹️ Stop Telegram Bot")
log_output = gr.Textbox(value="", label="📜 Bot & Telegram Logs", lines=15, interactive=False)
cmd_input.submit(run_terminal, inputs=cmd_input, outputs=terminal_output)
def start_click():
start_bot()
return update_log_box()
def stop_click():
stop_bot()
return update_log_box()
start_btn.click(start_click, outputs=log_output)
stop_btn.click(stop_click, outputs=log_output)
def background_log_updater():
while True:
time.sleep(3)
yield update_log_box()
demo.load(None, outputs=log_output, every=None).then(
background_log_updater, outputs=log_output
)
demo.launch()