Spaces:
Runtime error
Runtime error
Update bot.py
Browse files1 unmodified line2345678934 unmodified lines444546474849505152535455565758596061626364656667686970717273747576777879808182838485861 unmodified line8889909192939495969798991001011021031041053 unmodified lines1091101111121131141151161171186 unmodified lines1251261271281 unmodified lineimport timeimport sqlite3import asynciofrom pyrogram import Client, filtersfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton# --- Environment Variables ---API_ID = int(os.getenv("API_ID", 0))34 unmodified linesapi_id=API_ID,api_hash=API_HASH,bot_token=BOT_TOKEN,workers=20 # Increase workers for parallel chunk handling)@app.on_message(filters.document | filters.video)async def fast_process(client, message):user_id = message.from_user.id# Fast prompt for 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()# Downloadpath = await client.download_media(message,file_name=new_name,progress=progress_callback,progress_args=(status, start_time, "Downloading"))# Uploadstart_up = time.time()sent_file = await client.send_document(chat_id=message.chat.id,document=path,caption=f"β **Done:** `{new_name}`",progress=progress_callback,progress_args=(status, start_up, "Uploading"))# Store in SQLitenew_fid = sent_file.document.file_id if sent_file.document else sent_file.video.file_idadd_to_history(user_id, new_name, new_fid)# Instant Cleanupif os.path.exists(path):os.remove(path)await status.delete()1 unmodified lineasync def progress_callback(current, total, status_msg, start_time, mode):now = time.time()diff = now - start_timeif round(diff % 3.00) == 0 or current == total:speed = current / diff if diff > 0 else 0eta = (total - current) / speed if speed > 0 else 0try:await status_msg.edit(f"π **{mode}**\n"f"**Size:** {current/1024/1024:.2f}/{total/1024/1024:.2f} MB\n"f"**Speed:** {speed/1024/1024:.2f} MB/s\n"f"**ETA:** {int(eta)}s")except: pass@app.on_message(filters.command("history"))async def show_history(client, message):3 unmodified linestext = "π **Your File History:**\n\n"buttons = []for idx, (name, fid) in enumerate(rows):# We use the index in callback_data to retrieve the fidtext += f"{idx+1}. `{name}`\n"buttons.append([InlineKeyboardButton(f"Get {name}", callback_data=f"get_{idx}")])await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))6 unmodified linesawait client.send_document(query.message.chat.id, file_id, caption=f"Retrieved: {file_name}")await query.answer()app.run()1 unmodified line23456789101112131415161718192021222334 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061 unmodified line1081091101111121131141151161171181191201211221231241251261271281291301311323 unmodified lines1361371381391401411421431446 unmodified lines1511521531541551561571581591601 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('/')def health_check():return "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))34 unmodified linesapi_id=API_ID,api_hash=API_HASH,bot_token=BOT_TOKEN,workers=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,file_name=new_name,progress=progress_callback,progress_args=(status, start_time, "Downloading"))except Exception as e:return await status.edit(f"β **Download Error:** {e}")# 3. Uploadawait status.edit("π **Upload Starting...**")start_up = time.time()try:sent_file = await client.send_document(chat_id=message.chat.id,document=path,caption=f"β **Done:** `{new_name}`",progress=progress_callback,progress_args=(status, start_up, "Uploading"))except Exception as e:return await status.edit(f"β **Upload Error:** {e}")# 4. History & Cleanupfile_obj = sent_file.document or sent_file.video or sent_file.audioadd_to_history(user_id, new_name, file_obj.file_id)if os.path.exists(path):os.remove(path)await status.delete()1 unmodified lineasync 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)try:await status_msg.edit(f"π **{mode}**\n"f"**Size:** {curr_mb:.2f}/{tot_mb:.2f} MB\n"f"**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):3 unmodified linestext = "π **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))6 unmodified linesawait 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()
bot.py+65-33