understanding commited on
Commit
4af79d6
Β·
verified Β·
1 Parent(s): 431014c

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +73 -39
bot.py CHANGED
@@ -5,6 +5,7 @@ import logging
5
  import os
6
  import re
7
  import uuid
 
8
  from typing import Dict
9
 
10
  from aiogram import Bot, Dispatcher, types, F
@@ -35,7 +36,8 @@ logger = logging.getLogger("bot")
35
  bot = Bot(
36
  token=config.BOT_TOKEN,
37
  default=DefaultBotProperties(
38
- parse_mode=ParseMode.HTML
 
39
  )
40
  )
41
 
@@ -58,6 +60,8 @@ async def link_processor_worker(worker_id: int):
58
  file_info = None
59
  error_msg = f"An unknown error occurred for link: {original_link}"
60
 
 
 
61
  try:
62
  short_id = await terabox.extract_terabox_short_id(original_link)
63
  if not short_id:
@@ -72,7 +76,10 @@ async def link_processor_worker(worker_id: int):
72
  if error:
73
  raise ValueError(error)
74
 
75
- local_filepath, download_error = await terabox.download_terabox_file(
 
 
 
76
  download_url,
77
  raw_filename
78
  )
@@ -85,6 +92,7 @@ async def link_processor_worker(worker_id: int):
85
  'name': raw_filename,
86
  'size': os.path.getsize(local_filepath),
87
  'short_id': short_id,
 
88
  }
89
 
90
  except Exception as e:
@@ -99,23 +107,31 @@ async def link_processor_worker(worker_id: int):
99
 
100
  processed, total = batch_info['processed_links'], batch_info['total_links']
101
 
 
 
 
 
 
102
  try:
103
- await batch_info["status_message"].edit_text(
104
- f"βš™οΈ Batch <code>{batch_id[:6]}</code> in progress...\nProcessed {processed}/{total} links.",
105
- disable_web_page_preview=True
 
 
 
 
 
106
  )
107
  except TelegramBadRequest:
108
  pass
109
 
110
- await asyncio.sleep(0.3) # prevent rate limit
111
-
112
  if processed == total:
113
  logger.info(f"Batch {batch_id[:6]} complete. Triggering final processing.")
114
  await handle_batch_completion(batch_id)
115
 
116
  TASK_QUEUE.task_done()
117
 
118
- async def send_and_cache_file(chat_id: int, file_info: dict, caption: str) -> Message:
119
  file_path_or_id = file_info.get('file_id') or FSInputFile(file_info['path'], filename=file_info['name'])
120
  media_type = file_info.get('type')
121
  filename = file_info.get('name') or file_info.get('filename')
@@ -125,13 +141,13 @@ async def send_and_cache_file(chat_id: int, file_info: dict, caption: str) -> Me
125
 
126
  sent_message = None
127
  if media_type == 'video' or filename.lower().endswith(video_exts):
128
- sent_message = await bot.send_video(chat_id, file_path_or_id, caption=caption, supports_streaming=True)
129
  media_type = 'video'
130
  elif media_type == 'audio' or filename.lower().endswith(audio_exts):
131
- sent_message = await bot.send_audio(chat_id, file_path_or_id, caption=caption)
132
  media_type = 'audio'
133
  else:
134
- sent_message = await bot.send_document(chat_id, file_path_or_id, caption=caption)
135
  media_type = 'document'
136
 
137
  if not file_info.get('cached') and sent_message:
@@ -140,14 +156,11 @@ async def send_and_cache_file(chat_id: int, file_info: dict, caption: str) -> Me
140
  file_info['short_id'], file_id_to_cache, filename, media_type, file_info['size']
141
  )
142
 
143
- return sent_message
144
-
145
  async def handle_batch_completion(batch_id: str):
146
  batch = BATCH_JOBS.get(batch_id)
147
  if not batch:
148
  return
149
 
150
- status_msg = batch["status_message"]
151
  successful_downloads = batch["successful_downloads"]
152
 
153
  try:
@@ -155,15 +168,23 @@ async def handle_batch_completion(batch_id: str):
155
  failed_links_text = "\n".join(
156
  [f"- {x['link']} β†’ {x['error']}" for x in batch['failed_links']]
157
  )
158
- await status_msg.edit_text(
159
- f"❌ Batch <code>{batch_id[:6]}</code> failed. No files could be processed.\nDetails:\n{failed_links_text}",
160
- disable_web_page_preview=True
 
 
 
 
161
  )
162
  return
163
 
164
- await status_msg.edit_text(
165
- f"βœ… Batch <code>{batch_id[:6]}</code> downloaded. Preparing to send {len(successful_downloads)} files...",
166
- disable_web_page_preview=True
 
 
 
 
167
  )
168
 
169
  if config.FORWARD_CHANNEL_ID:
@@ -173,30 +194,38 @@ async def handle_batch_completion(batch_id: str):
173
  batch["source_message_id"]
174
  )
175
  for item in successful_downloads:
176
- caption = f"🎬 <code>{item.get('name') or item.get('filename')}</code>"
177
- await send_and_cache_file(config.FORWARD_CHANNEL_ID, item, caption)
178
  await asyncio.sleep(1)
179
 
180
  for item in successful_downloads:
181
- caption = f"🎬 <code>{item.get('name') or item.get('filename')}</code>"
182
- await send_and_cache_file(batch["source_chat_id"], item, caption)
183
 
184
- summary = f"βœ… Batch <code>{batch_id[:6]}</code> complete: {len(successful_downloads)} files sent."
185
  if batch["failed_links"]:
186
  summary += f"\n❌ {len(batch['failed_links'])} links failed."
187
 
188
- await status_msg.edit_text(summary, disable_web_page_preview=True)
 
 
 
 
189
 
190
  except Exception as e:
191
  logger.error(f"Error during batch completion for {batch_id}: {e}", exc_info=True)
192
- await status_msg.edit_text(
193
- f"❌ A critical error occurred while sending files for batch <code>{batch_id[:6]}</code>.",
194
- disable_web_page_preview=True
 
195
  )
196
  finally:
197
  for item in successful_downloads:
198
  if not item.get('cached') and os.path.exists(item['path']):
199
  os.remove(item['path'])
 
 
 
200
  del BATCH_JOBS[batch_id]
201
 
202
  # --- Handlers ---
@@ -204,14 +233,14 @@ async def handle_batch_completion(batch_id: str):
204
  async def start_handler(message: Message):
205
  text = (
206
  "πŸ‘‹ <b>Welcome to the Terabox Downloader Bot!</b>\n\n"
207
- "πŸ“₯ Send me any valid <b>Terabox</b> link(s), and I will fetch and send the files to you.\n\n"
208
- "βœ… Multi-link batch supported!\n"
209
- "πŸ’Ύ Cache enabled β†’ faster for repeat links.\n"
210
- "πŸ“’ Original message will be forwarded to: "
211
- f"<b>@{config.FORCE_SUB_CHANNEL_USERNAME}</b> (if configured).\n\n"
212
- "πŸš€ <i>Just send your link(s) below ⬇️</i>"
213
  )
214
- await message.answer(text, disable_web_page_preview=True)
215
 
216
  @dp.message(F.text | F.caption)
217
  async def message_handler(message: Message):
@@ -234,7 +263,11 @@ async def message_handler(message: Message):
234
  return
235
 
236
  batch_id = str(uuid.uuid4())
237
- status_msg = await message.answer(f"βœ… Found {len(terabox_links)} link(s). Queued as batch <code>{batch_id[:6]}</code>.", disable_web_page_preview=True)
 
 
 
 
238
 
239
  BATCH_JOBS[batch_id] = {
240
  "total_links": len(terabox_links),
@@ -244,8 +277,9 @@ async def message_handler(message: Message):
244
  "source_chat_id": message.chat.id,
245
  "source_user_id": message.from_user.id,
246
  "source_message_id": message.message_id,
247
- "status_message": status_msg,
248
- "lock": asyncio.Lock()
 
249
  }
250
 
251
  for link in terabox_links:
 
5
  import os
6
  import re
7
  import uuid
8
+ import time
9
  from typing import Dict
10
 
11
  from aiogram import Bot, Dispatcher, types, F
 
36
  bot = Bot(
37
  token=config.BOT_TOKEN,
38
  default=DefaultBotProperties(
39
+ parse_mode=ParseMode.HTML,
40
+ link_preview_is_disabled=True
41
  )
42
  )
43
 
 
60
  file_info = None
61
  error_msg = f"An unknown error occurred for link: {original_link}"
62
 
63
+ start_time = time.time()
64
+
65
  try:
66
  short_id = await terabox.extract_terabox_short_id(original_link)
67
  if not short_id:
 
76
  if error:
77
  raise ValueError(error)
78
 
79
+ local_filepath, thumb_path, download_error = await terabox.download_terabox_file(
80
+ bot,
81
+ batch_info["source_chat_id"],
82
+ batch_info["status_message_id"],
83
  download_url,
84
  raw_filename
85
  )
 
92
  'name': raw_filename,
93
  'size': os.path.getsize(local_filepath),
94
  'short_id': short_id,
95
+ 'thumb': thumb_path
96
  }
97
 
98
  except Exception as e:
 
107
 
108
  processed, total = batch_info['processed_links'], batch_info['total_links']
109
 
110
+ elapsed = time.time() - batch_info['start_time']
111
+ avg_per_file = elapsed / processed if processed > 0 else 1
112
+ remaining = (total - processed) * avg_per_file
113
+ eta_text = f"~{int(remaining):d}s" if remaining > 1 else "<1s"
114
+
115
  try:
116
+ await bot.edit_message_text(
117
+ chat_id=batch_info["source_chat_id"],
118
+ message_id=batch_info["status_message_id"],
119
+ text=(
120
+ f"βš™οΈ <b>Batch</b> <code>{batch_id[:6]}</code> <b>Progress</b>: {processed}/{total} "
121
+ f"(ETA: {eta_text})\n\n"
122
+ f"Current link:\n<code>{original_link}</code>"
123
+ )
124
  )
125
  except TelegramBadRequest:
126
  pass
127
 
 
 
128
  if processed == total:
129
  logger.info(f"Batch {batch_id[:6]} complete. Triggering final processing.")
130
  await handle_batch_completion(batch_id)
131
 
132
  TASK_QUEUE.task_done()
133
 
134
+ async def send_and_cache_file(chat_id: int, file_info: dict, reply_to: int, caption: str):
135
  file_path_or_id = file_info.get('file_id') or FSInputFile(file_info['path'], filename=file_info['name'])
136
  media_type = file_info.get('type')
137
  filename = file_info.get('name') or file_info.get('filename')
 
141
 
142
  sent_message = None
143
  if media_type == 'video' or filename.lower().endswith(video_exts):
144
+ sent_message = await bot.send_video(chat_id, file_path_or_id, caption=caption, supports_streaming=True, reply_to_message_id=reply_to)
145
  media_type = 'video'
146
  elif media_type == 'audio' or filename.lower().endswith(audio_exts):
147
+ sent_message = await bot.send_audio(chat_id, file_path_or_id, caption=caption, reply_to_message_id=reply_to)
148
  media_type = 'audio'
149
  else:
150
+ sent_message = await bot.send_document(chat_id, file_path_or_id, caption=caption, reply_to_message_id=reply_to)
151
  media_type = 'document'
152
 
153
  if not file_info.get('cached') and sent_message:
 
156
  file_info['short_id'], file_id_to_cache, filename, media_type, file_info['size']
157
  )
158
 
 
 
159
  async def handle_batch_completion(batch_id: str):
160
  batch = BATCH_JOBS.get(batch_id)
161
  if not batch:
162
  return
163
 
 
164
  successful_downloads = batch["successful_downloads"]
165
 
166
  try:
 
168
  failed_links_text = "\n".join(
169
  [f"- {x['link']} β†’ {x['error']}" for x in batch['failed_links']]
170
  )
171
+ await bot.edit_message_text(
172
+ chat_id=batch["source_chat_id"],
173
+ message_id=batch["status_message_id"],
174
+ text=(
175
+ f"❌ <b>Batch</b> <code>{batch_id[:6]}</code> failed. No files could be processed.\n\n"
176
+ f"<b>Details</b>:\n{failed_links_text}"
177
+ )
178
  )
179
  return
180
 
181
+ await bot.edit_message_text(
182
+ chat_id=batch["source_chat_id"],
183
+ message_id=batch["status_message_id"],
184
+ text=(
185
+ f"βœ… <b>Batch</b> <code>{batch_id[:6]}</code> downloaded.\n"
186
+ f"Sending {len(successful_downloads)} files..."
187
+ )
188
  )
189
 
190
  if config.FORWARD_CHANNEL_ID:
 
194
  batch["source_message_id"]
195
  )
196
  for item in successful_downloads:
197
+ caption = f"`{item.get('name') or item.get('filename')}`"
198
+ await send_and_cache_file(config.FORWARD_CHANNEL_ID, item, batch["source_message_id"], caption)
199
  await asyncio.sleep(1)
200
 
201
  for item in successful_downloads:
202
+ caption = f"`{item.get('name') or item.get('filename')}`"
203
+ await send_and_cache_file(batch["source_chat_id"], item, batch["source_message_id"], caption)
204
 
205
+ summary = f"βœ… <b>Batch</b> <code>{batch_id[:6]}</code> complete: {len(successful_downloads)} files sent."
206
  if batch["failed_links"]:
207
  summary += f"\n❌ {len(batch['failed_links'])} links failed."
208
 
209
+ await bot.edit_message_text(
210
+ chat_id=batch["source_chat_id"],
211
+ message_id=batch["status_message_id"],
212
+ text=summary
213
+ )
214
 
215
  except Exception as e:
216
  logger.error(f"Error during batch completion for {batch_id}: {e}", exc_info=True)
217
+ await bot.edit_message_text(
218
+ chat_id=batch["source_chat_id"],
219
+ message_id=batch["status_message_id"],
220
+ text=f"A critical error occurred while sending files for batch <code>{batch_id[:6]}</code>."
221
  )
222
  finally:
223
  for item in successful_downloads:
224
  if not item.get('cached') and os.path.exists(item['path']):
225
  os.remove(item['path'])
226
+ if item.get('thumb') and os.path.exists(item['thumb']):
227
+ os.remove(item['thumb'])
228
+
229
  del BATCH_JOBS[batch_id]
230
 
231
  # --- Handlers ---
 
233
  async def start_handler(message: Message):
234
  text = (
235
  "πŸ‘‹ <b>Welcome to the Terabox Downloader Bot!</b>\n\n"
236
+ "πŸ“₯ Send me any valid Terabox link(s) and I will fetch the files and send them to you.\n\n"
237
+ f"πŸ“’ Make sure you are a member of @{config.FORCE_SUB_CHANNEL_USERNAME}\n\n"
238
+ "πŸš€ Supports multiple links per message.\n"
239
+ "πŸ’Ύ Auto-cache enabled.\n"
240
+ "πŸ”„ Forwarding original message to channel enabled.\n\n"
241
+ "βœ… <i>Just send your links below ⬇️</i>"
242
  )
243
+ await message.reply(text, reply_to_message_id=message.message_id)
244
 
245
  @dp.message(F.text | F.caption)
246
  async def message_handler(message: Message):
 
263
  return
264
 
265
  batch_id = str(uuid.uuid4())
266
+
267
+ status_msg = await message.reply(
268
+ f"βœ… <b>Found</b> {len(terabox_links)} links. <b>Queued</b> as batch <code>{batch_id[:6]}</code>.",
269
+ reply_to_message_id=message.message_id
270
+ )
271
 
272
  BATCH_JOBS[batch_id] = {
273
  "total_links": len(terabox_links),
 
277
  "source_chat_id": message.chat.id,
278
  "source_user_id": message.from_user.id,
279
  "source_message_id": message.message_id,
280
+ "status_message_id": status_msg.message_id,
281
+ "lock": asyncio.Lock(),
282
+ "start_time": time.time()
283
  }
284
 
285
  for link in terabox_links: