Spaces:
Runtime error

dpadhan commited on
Commit
18d7c57
Β·
verified Β·
1 Parent(s): 8bf5757

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +38 -25
bot.py CHANGED
@@ -2,13 +2,15 @@ import os
2
  import time
3
  import sqlite3
4
  import asyncio
5
- from pyromod import listen # Required for client.ask
6
- from pyrogram import Client, filters
7
- from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
8
  from flask import Flask
9
  from threading import Thread
10
 
11
- # --- Flask Server for Hugging Face "Keep Alive" ---
 
 
 
 
 
12
  web_app = Flask(__name__)
13
 
14
  @web_app.route('/')
@@ -16,15 +18,15 @@ def health_check():
16
  return "Bot is Running", 200
17
 
18
  def run_server():
19
- # Hugging Face looks for activity on port 7860
20
  web_app.run(host="0.0.0.0", port=7860)
21
 
22
- # --- Environment Variables ---
23
  API_ID = int(os.getenv("API_ID", 0))
24
  API_HASH = os.getenv("API_HASH")
25
  BOT_TOKEN = os.getenv("BOT_TOKEN")
26
 
27
- # --- Database Setup ---
28
  DB_PATH = "bot_data.db"
29
 
30
  def init_db():
@@ -61,18 +63,28 @@ app = Client(
61
  workers=20
62
  )
63
 
 
 
 
 
 
 
 
64
  @app.on_message(filters.document | filters.video | filters.audio)
65
  async def fast_process(client, message):
66
  user_id = message.from_user.id
67
 
68
- # 1. Conversation to get new name
69
- ask = await client.ask(message.chat.id, "πŸ“ Send the **New Name** with extension:")
70
- new_name = ask.text
 
 
 
71
 
72
- status = await message.reply("⚑ **Starting High-Speed Stream...**")
73
  start_time = time.time()
74
 
75
- # 2. Download (Handled in chunks by Pyrogram)
76
  try:
77
  path = await client.download_media(
78
  message,
@@ -108,12 +120,10 @@ async def fast_process(client, message):
108
  async def progress_callback(current, total, status_msg, start_time, mode):
109
  now = time.time()
110
  diff = now - start_time
111
- # Update every 4 seconds to avoid flood limits
112
  if round(diff % 4.00) == 0 or current == total:
113
  speed = current / diff if diff > 0 else 0
114
  eta = (total - current) / speed if speed > 0 else 0
115
 
116
- # Convert to MB
117
  curr_mb = current / (1024 * 1024)
118
  tot_mb = total / (1024 * 1024)
119
  speed_mb = speed / (1024 * 1024)
@@ -125,8 +135,7 @@ async def progress_callback(current, total, status_msg, start_time, mode):
125
  f"**Speed:** {speed_mb:.2f} MB/s\n"
126
  f"**ETA:** {int(eta)}s"
127
  )
128
- except:
129
- pass
130
 
131
  @app.on_message(filters.command("history"))
132
  async def show_history(client, message):
@@ -134,11 +143,12 @@ async def show_history(client, message):
134
  if not rows:
135
  return await message.reply("No history found.")
136
 
137
- text = "πŸ“‚ **Your File History:**\n\n"
138
  buttons = []
139
- for idx, (name, fid) in enumerate(rows[-10:]): # Show last 10
 
140
  text += f"{idx+1}. `{name}`\n"
141
- buttons.append([InlineKeyboardButton(f"Get {name[:20]}...", callback_data=f"get_{idx}")])
142
 
143
  await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))
144
 
@@ -146,15 +156,18 @@ async def show_history(client, message):
146
  async def send_from_history(client, query):
147
  idx = int(query.data.split("_")[1])
148
  rows = get_history(query.from_user.id)
149
- file_name, file_id = rows[idx]
150
-
151
- await client.send_document(query.message.chat.id, file_id, caption=f"Retrieved: {file_name}")
 
 
 
152
  await query.answer()
153
 
154
  if __name__ == "__main__":
155
- # Start the web server thread
156
  Thread(target=run_server, daemon=True).start()
157
 
158
- # Run the bot
159
- print("Bot is booting...")
160
  app.run()
 
2
  import time
3
  import sqlite3
4
  import asyncio
 
 
 
5
  from flask import Flask
6
  from threading import Thread
7
 
8
+ # Import pyromod first to patch Pyrogram
9
+ from pyromod import listen
10
+ from pyrogram import Client, filters
11
+ from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
12
+
13
+ # --- Flask Server for Hugging Face ---
14
  web_app = Flask(__name__)
15
 
16
  @web_app.route('/')
 
18
  return "Bot is Running", 200
19
 
20
  def run_server():
21
+ # HF looks for port 7860
22
  web_app.run(host="0.0.0.0", port=7860)
23
 
24
+ # --- Config ---
25
  API_ID = int(os.getenv("API_ID", 0))
26
  API_HASH = os.getenv("API_HASH")
27
  BOT_TOKEN = os.getenv("BOT_TOKEN")
28
 
29
+ # --- Database ---
30
  DB_PATH = "bot_data.db"
31
 
32
  def init_db():
 
63
  workers=20
64
  )
65
 
66
+ @app.on_message(filters.command("start"))
67
+ async def start_handler(client, message):
68
+ await message.reply(
69
+ "πŸ‘‹ **Hi! I am a High-Speed Renamer Bot.**\n\n"
70
+ "Send me any file or video to start."
71
+ )
72
+
73
  @app.on_message(filters.document | filters.video | filters.audio)
74
  async def fast_process(client, message):
75
  user_id = message.from_user.id
76
 
77
+ # 1. Ask for name
78
+ try:
79
+ ask = await client.ask(message.chat.id, "πŸ“ Send the **New Name** with extension:", timeout=60)
80
+ new_name = ask.text
81
+ except Exception:
82
+ return await message.reply("❌ Timeout. Please send the file again.")
83
 
84
+ status = await message.reply("⚑ **Preparing to Stream...**")
85
  start_time = time.time()
86
 
87
+ # 2. Download
88
  try:
89
  path = await client.download_media(
90
  message,
 
120
  async def progress_callback(current, total, status_msg, start_time, mode):
121
  now = time.time()
122
  diff = now - start_time
 
123
  if round(diff % 4.00) == 0 or current == total:
124
  speed = current / diff if diff > 0 else 0
125
  eta = (total - current) / speed if speed > 0 else 0
126
 
 
127
  curr_mb = current / (1024 * 1024)
128
  tot_mb = total / (1024 * 1024)
129
  speed_mb = speed / (1024 * 1024)
 
135
  f"**Speed:** {speed_mb:.2f} MB/s\n"
136
  f"**ETA:** {int(eta)}s"
137
  )
138
+ except: pass
 
139
 
140
  @app.on_message(filters.command("history"))
141
  async def show_history(client, message):
 
143
  if not rows:
144
  return await message.reply("No history found.")
145
 
146
+ text = "πŸ“‚ **Your Recent Files:**\n\n"
147
  buttons = []
148
+ # Show only the last 10 items to avoid long messages
149
+ for idx, (name, fid) in enumerate(rows[-10:]):
150
  text += f"{idx+1}. `{name}`\n"
151
+ buttons.append([InlineKeyboardButton(f"Get {name[:20]}", callback_data=f"get_{idx}")])
152
 
153
  await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))
154
 
 
156
  async def send_from_history(client, query):
157
  idx = int(query.data.split("_")[1])
158
  rows = get_history(query.from_user.id)
159
+ # Be careful: indices in rows might change if new items are added
160
+ try:
161
+ file_name, file_id = rows[idx]
162
+ await client.send_document(query.message.chat.id, file_id, caption=f"Retrieved: {file_name}")
163
+ except:
164
+ await query.answer("File not found in history.")
165
  await query.answer()
166
 
167
  if __name__ == "__main__":
168
+ # Start Keep-Alive Thread
169
  Thread(target=run_server, daemon=True).start()
170
 
171
+ # Run Bot
172
+ print("Bot started...")
173
  app.run()