understanding commited on
Commit
138515e
Β·
verified Β·
1 Parent(s): 4af79d6

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +27 -57
bot.py CHANGED
@@ -5,10 +5,9 @@ import logging
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
12
  from aiogram.filters import CommandStart
13
  from aiogram.types import Message, FSInputFile
14
  from aiogram.enums import ParseMode
@@ -60,8 +59,6 @@ async def link_processor_worker(worker_id: int):
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:
@@ -79,7 +76,7 @@ async def link_processor_worker(worker_id: int):
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
  )
@@ -106,21 +103,10 @@ async def link_processor_worker(worker_id: int):
106
  batch_info["failed_links"].append({"link": original_link, "error": error_msg})
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
@@ -131,7 +117,7 @@ async def link_processor_worker(worker_id: int):
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,13 +127,13 @@ async def send_and_cache_file(chat_id: int, file_info: dict, reply_to: int, capt
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,11 +142,14 @@ async def send_and_cache_file(chat_id: int, file_info: dict, reply_to: int, capt
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,23 +157,13 @@ async def handle_batch_completion(batch_id: str):
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:
@@ -195,29 +174,23 @@ async def handle_batch_completion(batch_id: str):
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:
@@ -235,12 +208,12 @@ async def start_handler(message: Message):
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,10 +236,8 @@ 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] = {
@@ -277,9 +248,8 @@ async def message_handler(message: Message):
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:
 
5
  import os
6
  import re
7
  import uuid
 
8
  from typing import Dict
9
 
10
+ from aiogram import Bot, Dispatcher, F
11
  from aiogram.filters import CommandStart
12
  from aiogram.types import Message, FSInputFile
13
  from aiogram.enums import ParseMode
 
59
  file_info = None
60
  error_msg = f"An unknown error occurred for link: {original_link}"
61
 
 
 
62
  try:
63
  short_id = await terabox.extract_terabox_short_id(original_link)
64
  if not short_id:
 
76
  local_filepath, thumb_path, download_error = await terabox.download_terabox_file(
77
  bot,
78
  batch_info["source_chat_id"],
79
+ batch_info["status_message"].message_id,
80
  download_url,
81
  raw_filename
82
  )
 
103
  batch_info["failed_links"].append({"link": original_link, "error": error_msg})
104
 
105
  processed, total = batch_info['processed_links'], batch_info['total_links']
 
 
 
 
 
 
106
  try:
107
+ await batch_info["status_message"].edit_text(
108
+ f"βš™οΈ Batch <code>{batch_id[:6]}</code> in progress...\n"
109
+ f"Processed <b>{processed}</b>/<b>{total}</b> links."
 
 
 
 
 
110
  )
111
  except TelegramBadRequest:
112
  pass
 
117
 
118
  TASK_QUEUE.task_done()
119
 
120
+ async def send_and_cache_file(chat_id: int, file_info: dict, caption: str) -> Message:
121
  file_path_or_id = file_info.get('file_id') or FSInputFile(file_info['path'], filename=file_info['name'])
122
  media_type = file_info.get('type')
123
  filename = file_info.get('name') or file_info.get('filename')
 
127
 
128
  sent_message = None
129
  if media_type == 'video' or filename.lower().endswith(video_exts):
130
+ sent_message = await bot.send_video(chat_id, file_path_or_id, caption=caption, supports_streaming=True)
131
  media_type = 'video'
132
  elif media_type == 'audio' or filename.lower().endswith(audio_exts):
133
+ sent_message = await bot.send_audio(chat_id, file_path_or_id, caption=caption)
134
  media_type = 'audio'
135
  else:
136
+ sent_message = await bot.send_document(chat_id, file_path_or_id, caption=caption)
137
  media_type = 'document'
138
 
139
  if not file_info.get('cached') and sent_message:
 
142
  file_info['short_id'], file_id_to_cache, filename, media_type, file_info['size']
143
  )
144
 
145
+ return sent_message
146
+
147
  async def handle_batch_completion(batch_id: str):
148
  batch = BATCH_JOBS.get(batch_id)
149
  if not batch:
150
  return
151
 
152
+ status_msg = batch["status_message"]
153
  successful_downloads = batch["successful_downloads"]
154
 
155
  try:
 
157
  failed_links_text = "\n".join(
158
  [f"- {x['link']} β†’ {x['error']}" for x in batch['failed_links']]
159
  )
160
+ await status_msg.edit_text(
161
+ f"❌ Batch <code>{batch_id[:6]}</code> failed.\nNo files could be processed.\n\n<b>Details:</b>\n{failed_links_text}"
 
 
 
 
 
162
  )
163
  return
164
 
165
+ await status_msg.edit_text(
166
+ f"βœ… Batch <code>{batch_id[:6]}</code> downloaded.\nPreparing to send <b>{len(successful_downloads)}</b> files..."
 
 
 
 
 
167
  )
168
 
169
  if config.FORWARD_CHANNEL_ID:
 
174
  )
175
  for item in successful_downloads:
176
  caption = f"`{item.get('name') or item.get('filename')}`"
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"`{item.get('name') or item.get('filename')}`"
182
+ await send_and_cache_file(batch["source_chat_id"], item, caption)
183
 
184
+ summary = f"βœ… Batch <code>{batch_id[:6]}</code> complete: <b>{len(successful_downloads)}</b> 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)
 
 
 
 
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"❌ Critical error occurred while sending files for batch <code>{batch_id[:6]}</code>."
 
 
194
  )
195
  finally:
196
  for item in successful_downloads:
 
208
  "πŸ‘‹ <b>Welcome to the Terabox Downloader Bot!</b>\n\n"
209
  "πŸ“₯ Send me any valid Terabox link(s) and I will fetch the files and send them to you.\n\n"
210
  f"πŸ“’ Make sure you are a member of @{config.FORCE_SUB_CHANNEL_USERNAME}\n\n"
211
+ "πŸš€ Supports multiple links per message (batch mode).\n"
212
  "πŸ’Ύ Auto-cache enabled.\n"
213
  "πŸ”„ Forwarding original message to channel enabled.\n\n"
214
  "βœ… <i>Just send your links below ⬇️</i>"
215
  )
216
+ await message.reply(text)
217
 
218
  @dp.message(F.text | F.caption)
219
  async def message_handler(message: Message):
 
236
  return
237
 
238
  batch_id = str(uuid.uuid4())
 
239
  status_msg = await message.reply(
240
+ f"βœ… <b>Found</b> {len(terabox_links)} links.\n<b>Queued</b> as batch <code>{batch_id[:6]}</code>."
 
241
  )
242
 
243
  BATCH_JOBS[batch_id] = {
 
248
  "source_chat_id": message.chat.id,
249
  "source_user_id": message.from_user.id,
250
  "source_message_id": message.message_id,
251
+ "status_message": status_msg,
252
+ "lock": asyncio.Lock()
 
253
  }
254
 
255
  for link in terabox_links: