Spaces:
Running
Running
import os | |
import gradio as gr | |
import logging | |
from multiprocessing import Process | |
from pyrogram import Client, filters | |
from io import StringIO | |
from time import sleep | |
# ---------- FIXED CONFIG ---------- | |
API_ID = int(os.environ.get("API_ID", "6")) | |
API_HASH = os.environ.get("API_HASH", "eb06d4abfb49dc3eeb1aeb98ae0f581e") | |
BOT_TOKEN = os.environ.get("BOT_TOKEN", "7510817339:AAHFZoFzPkUO_-nAwfh9bjY_qHsWMprM2PI") | |
# ---------- LOGGING ---------- | |
log_stream = StringIO() | |
logging.basicConfig(stream=log_stream, level=logging.INFO, format="%(asctime)s - %(message)s") | |
logger = logging.getLogger() | |
# ---------- BOT FUNCTION ---------- | |
def run_bot(): | |
app = Client("my_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN) | |
async def start_cmd(client, message): | |
await message.reply("hi") | |
logger.info(f"Replied to /start from user ID: {message.from_user.id}") | |
logger.info("Bot started.") | |
app.run() | |
logger.info("Bot stopped.") | |
# ---------- PROCESS CONTROL ---------- | |
bot_process = None | |
def start_bot(): | |
global bot_process | |
if bot_process and bot_process.is_alive(): | |
return "Bot is already running." | |
bot_process = Process(target=run_bot) | |
bot_process.start() | |
sleep(2) | |
return "β Bot started." | |
def stop_bot(): | |
global bot_process | |
if bot_process and bot_process.is_alive(): | |
bot_process.terminate() | |
bot_process.join() | |
logger.info("Bot manually stopped.") | |
return "π Bot stopped." | |
return "Bot is not running." | |
def get_logs(): | |
return log_stream.getvalue()[-20000:] | |
# ---------- GRADIO UI ---------- | |
with gr.Blocks() as ui: | |
gr.Markdown("## π€ Telegram Bot Control Panel") | |
start_btn = gr.Button("π Start Bot") | |
stop_btn = gr.Button("π Stop Bot") | |
refresh_btn = gr.Button("π Refresh Logs") | |
logs_box = gr.Textbox(label="π Bot Logs", lines=25) | |
start_btn.click(fn=start_bot, outputs=logs_box) | |
stop_btn.click(fn=stop_bot, outputs=logs_box) | |
refresh_btn.click(fn=get_logs, outputs=logs_box) | |
if __name__ == "__main__": | |
ui.launch() | |