Spaces:
Runtime error
Runtime error
Update bot.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159import osimport asyncioimport sqlite3from pyrogram import Client, filters, errorsfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton# --- CONFIGURATION ---API_ID = int(os.environ.get("API_ID", 0))API_HASH = os.environ.get("API_HASH", "")BOT_TOKEN = os.environ.get("BOT_TOKEN", "")# --- DATABASE SETUP ---DB_PATH = "bot_data.db"def init_db():conn = sqlite3.connect(DB_PATH)cursor = conn.cursor()cursor.execute('''CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY, source_ids TEXT, dest_id INTEGER, order_pref TEXT)''')conn.commit()conn.close()def get_config():conn = sqlite3.connect(DB_PATH)cursor = conn.cursor()cursor.execute("SELECT source_ids, dest_id, order_pref FROM config WHERE id = 1")res = cursor.fetchone()conn.close()return resinit_db()# --- UI UTILS ---def generate_progress_bar(current, total):percentage = (current / total) * 100 if total > 0 else 0blocks = int(current / total * 15) if total > 0 else 0bar = "🔘" * blocks + "⚪" * (15 - blocks)return f"{bar} {percentage:.1f}%"# --- BOT CLIENT ---app = Client("forwarder_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)@app.on_message(filters.command("start"))async def start(client, message):boot_text = ("<code>[ ⚡ ] CLONE_OS TERMINAL v2.0</code>\n""<code>[ OK ] MOUNTING DATABASE...</code>\n""<code>[ OK ] ESTABLISHING CONNECTION...</code>\n\n""<b>SYSTEM ONLINE. SELECT A MODULE:</b>")buttons = InlineKeyboardMarkup([[InlineKeyboardButton("⚙️ CONFIGURE", callback_data="setup_info"),InlineKeyboardButton("▶️ EXECUTE CLONE", callback_data="start_clone")],[InlineKeyboardButton("🔍 SYS_STATUS", callback_data="check_status"),InlineKeyboardButton("🧹 PURGE_DB", callback_data="clear_db")]])await message.reply_text(boot_text, reply_markup=buttons)@app.on_callback_query()async def handle_callbacks(client, callback_query):data = callback_query.dataif data == "setup_info":await callback_query.message.edit_text("<code>[ REQUEST ]: INPUT_CONFIG</code>\n\n""Format: <code>SOURCES | DEST | ORDER</code>\n""Example: <code>-1001, -1002 | -1003 | old</code>\n\n""<i>Waiting for user input...</i>",reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 CANCEL", callback_data="back")]]))elif data == "check_status":conf = get_config()if not conf:await callback_query.answer("❌ NO CONFIGURATION FOUND", show_alert=True)else:status = ("<code>[ DASHBOARD ]</code>\n"f"📡 <b>SOURCES:</b> <code>{conf[0]}</code>\n"f"🎯 <b>DESTINATION:</b> <code>{conf[1]}</code>\n"f"📑 <b>ORDERING:</b> <code>{conf[2].upper()}</code>\n")await callback_query.message.edit_text(status, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 BACK", callback_data="back")]]))elif data == "start_clone":await start_forwarding(client, callback_query.message)elif data == "clear_db":conn = sqlite3.connect(DB_PATH)conn.cursor().execute("DELETE FROM config")conn.commit()conn.close()await callback_query.answer("🗑 DATABASE PURGED", show_alert=True)await start(client, callback_query.message)elif data == "back":await start(client, callback_query.message)@app.on_message(filters.regex(r"^-?\d+.*\|.*-?\d+.*\|.*"))async def handle_setup_input(client, message):try:parts = message.text.split("|")sources, dest, order = parts[0].strip(), int(parts[1].strip()), parts[2].strip().lower()conn = sqlite3.connect(DB_PATH)conn.cursor().execute("INSERT OR REPLACE INTO config (id, source_ids, dest_id, order_pref) VALUES (1, ?, ?, ?)",(sources, dest, order))conn.commit()conn.close()await message.reply_text("<code>[ SUCCESS ]: DATA_SYNC_COMPLETE</code>\nClick /start to run.")except Exception as e:await message.reply_text(f"<code>[ ERROR ]: {e}</code>")async def start_forwarding(client, message):conf = get_config()if not conf:return await message.edit_text("<code>[ FAILURE ]: RUN_SETUP_FIRST</code>")source_ids = [int(i.strip()) for i in conf[0].split(",")]dest_id = conf[1]reverse = True if conf[2] == "old" else Falseawait message.edit_text("<code>[ 🚀 ] INITIATING CLONE SEQUENCE...</code>")await asyncio.sleep(1)for s_id in source_ids:try:total_msgs = await client.get_chat_history_count(s_id)curr = 0async for msg in client.get_chat_history(s_id, reverse=reverse):if msg.service: continuetry:await msg.copy(dest_id)curr += 1if curr % 5 == 0 or curr == total_msgs:bar = generate_progress_bar(curr, total_msgs)ui = (f"<code>[ ACTIVE_PROCESS ]</code>\n"f"📡 <b>SOURCE:</b> <code>{s_id}</code>\n"f"📦 <b>FILES:</b> <code>{curr} / {total_msgs}</code>\n\n"f"<code>{bar}</code>")await message.edit_text(ui)await asyncio.sleep(1.2)except errors.FloodWait as e:await asyncio.sleep(e.value)except Exception:continueexcept Exception as e:await message.reply_text(f"<code>[ ERROR ]: CHAT_{s_id}_UNREACHABLE\n{e}</code>")await message.edit_text("<code>[ COMPLETED ]: ALL_TASKS_DONE</code>\n/start to return to menu.")print("Terminal Bot Started...")app.run()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import timeimport speedtestfrom telegram import Updatefrom telegram.ext import Application, CommandHandler, ContextTypes# ConfigurationTOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'async def ping(update: Update, context: ContextTypes.DEFAULT_TYPE):# 1. Calculate Bot Latencystart_time = time.time()message = await update.message.reply_text("⚡ Checking system speeds...")end_time = time.time()bot_latency = (end_time - start_time) * 1000try:# 2. Run Speedtestst = speedtest.Speedtest()st.get_best_server()# Perform testsdownload_speed = st.download() / 1_000_000 # Convert to Mbpsupload_speed = st.upload() / 1_000_000 # Convert to Mbpsserver_info = st.results.servernetwork_ping = st.results.ping# 3. Format the Responseresponse = ("🏓 **Ping Results**\n\n"f"⏱ **Bot Latency:** {bot_latency:.2f}ms\n"f"⬇️ **Download:** {download_speed:.2f} Mbps\n"f"⬆️ **Upload:** {upload_speed:.2f} Mbps\n"f"📡 **Ping:** {network_ping:.2f} ms\n"f"🌐 **Server:** {server_info['name']}")await message.edit_text(response, parse_mode='Markdown')except Exception as e:await message.edit_text(f"❌ Error fetching speeds: {e}")def main():# Build the applicationapplication = Application.builder().token(TOKEN).build()# Add the /ping command handlerapplication.add_handler(CommandHandler("ping", ping))print("Bot is running...")application.run_polling()if __name__ == '__main__':main()
bot.py+43-149