Spaces:
Runtime error
Runtime error
Update bot.py
Browse files1 unmodified line2345678910111213141 unmodified line16171819202122232425262728293030 unmodified lines61626364656667686970717273747576777829 unmodified lines1081091101111121131141151161171181195 unmodified lines1251261271281291301311321 unmodified line1341351361371381391401411421431441 unmodified line1461471481491501511521531541551561571581591601 unmodified lineimport timeimport sqlite3import asynciofrom pyromod import listen # Required for client.askfrom pyrogram import Client, filtersfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButtonfrom flask import Flaskfrom threading import Thread# --- Flask Server for Hugging Face "Keep Alive" ---web_app = Flask(__name__)@web_app.route('/')1 unmodified linereturn "Bot is Running", 200def run_server():# Hugging Face looks for activity on port 7860web_app.run(host="0.0.0.0", port=7860)# --- Environment Variables ---API_ID = int(os.getenv("API_ID", 0))API_HASH = os.getenv("API_HASH")BOT_TOKEN = os.getenv("BOT_TOKEN")# --- Database Setup ---DB_PATH = "bot_data.db"def init_db():30 unmodified linesworkers=20)@app.on_message(filters.document | filters.video | filters.audio)async def fast_process(client, message):user_id = message.from_user.id# 1. Conversation to get new nameask = await client.ask(message.chat.id, "π Send the **New Name** with extension:")new_name = ask.textstatus = await message.reply("β‘ **Starting High-Speed Stream...**")start_time = time.time()# 2. Download (Handled in chunks by Pyrogram)try:path = await client.download_media(message,29 unmodified linesasync def progress_callback(current, total, status_msg, start_time, mode):now = time.time()diff = now - start_time# Update every 4 seconds to avoid flood limitsif round(diff % 4.00) == 0 or current == total:speed = current / diff if diff > 0 else 0eta = (total - current) / speed if speed > 0 else 0# Convert to MBcurr_mb = current / (1024 * 1024)tot_mb = total / (1024 * 1024)speed_mb = speed / (1024 * 1024)5 unmodified linesf"**Speed:** {speed_mb:.2f} MB/s\n"f"**ETA:** {int(eta)}s")except:pass@app.on_message(filters.command("history"))async def show_history(client, message):1 unmodified lineif not rows:return await message.reply("No history found.")text = "π **Your File History:**\n\n"buttons = []for idx, (name, fid) in enumerate(rows[-10:]): # Show last 10text += f"{idx+1}. `{name}`\n"buttons.append([InlineKeyboardButton(f"Get {name[:20]}...", callback_data=f"get_{idx}")])await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))1 unmodified lineasync def send_from_history(client, query):idx = int(query.data.split("_")[1])rows = get_history(query.from_user.id)file_name, file_id = rows[idx]await client.send_document(query.message.chat.id, file_id, caption=f"Retrieved: {file_name}")await query.answer()if __name__ == "__main__":# Start the web server threadThread(target=run_server, daemon=True).start()# Run the botprint("Bot is booting...")app.run()1 unmodified line23456789101112131415161 unmodified line18192021222324252627282930313230 unmodified lines6364656667686970717273747576777879808182838485868788899029 unmodified lines1201211221231241251261271281295 unmodified lines1351361371381391401411 unmodified line1431441451461471481491501511521531541 unmodified line1561571581591601611621631641651661671681691701711721731 unmodified lineimport timeimport sqlite3import asynciofrom flask import Flaskfrom threading import Thread# Import pyromod first to patch Pyrogramfrom pyromod import listenfrom pyrogram import Client, filtersfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton# --- Flask Server for Hugging Face ---web_app = Flask(__name__)@web_app.route('/')1 unmodified linereturn "Bot is Running", 200def run_server():# HF looks for port 7860web_app.run(host="0.0.0.0", port=7860)# --- Config ---API_ID = int(os.getenv("API_ID", 0))API_HASH = os.getenv("API_HASH")BOT_TOKEN = os.getenv("BOT_TOKEN")# --- Database ---DB_PATH = "bot_data.db"def init_db():30 unmodified linesworkers=20)@app.on_message(filters.command("start"))async def start_handler(client, message):await message.reply("π **Hi! I am a High-Speed Renamer Bot.**\n\n""Send me any file or video to start.")@app.on_message(filters.document | filters.video | filters.audio)async def fast_process(client, message):user_id = message.from_user.id# 1. Ask for nametry:ask = await client.ask(message.chat.id, "π Send the **New Name** with extension:", timeout=60)new_name = ask.textexcept Exception:return await message.reply("β Timeout. Please send the file again.")status = await message.reply("β‘ **Preparing to Stream...**")start_time = time.time()# 2. Downloadtry:path = await client.download_media(message,29 unmodified linesasync def progress_callback(current, total, status_msg, start_time, mode):now = time.time()diff = now - start_timeif round(diff % 4.00) == 0 or current == total:speed = current / diff if diff > 0 else 0eta = (total - current) / speed if speed > 0 else 0curr_mb = current / (1024 * 1024)tot_mb = total / (1024 * 1024)speed_mb = speed / (1024 * 1024)5 unmodified linesf"**Speed:** {speed_mb:.2f} MB/s\n"f"**ETA:** {int(eta)}s")except: pass@app.on_message(filters.command("history"))async def show_history(client, message):1 unmodified lineif not rows:return await message.reply("No history found.")text = "π **Your Recent Files:**\n\n"buttons = []# Show only the last 10 items to avoid long messagesfor idx, (name, fid) in enumerate(rows[-10:]):text += f"{idx+1}. `{name}`\n"buttons.append([InlineKeyboardButton(f"Get {name[:20]}", callback_data=f"get_{idx}")])await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))1 unmodified lineasync def send_from_history(client, query):idx = int(query.data.split("_")[1])rows = get_history(query.from_user.id)# Be careful: indices in rows might change if new items are addedtry:file_name, file_id = rows[idx]await client.send_document(query.message.chat.id, file_id, caption=f"Retrieved: {file_name}")except:await query.answer("File not found in history.")await query.answer()if __name__ == "__main__":# Start Keep-Alive ThreadThread(target=run_server, daemon=True).start()# Run Botprint("Bot started...")app.run()
bot.py+38-25