understanding commited on
Commit
55209e7
Β·
verified Β·
1 Parent(s): 1f3fd88

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +31 -46
bot.py CHANGED
@@ -7,7 +7,7 @@ import re
7
  import uuid
8
  from typing import Dict
9
 
10
- from aiogram import Bot, Dispatcher, types, F
11
  from aiogram.filters import CommandStart
12
  from aiogram.types import Message, FSInputFile
13
  from aiogram.enums import ParseMode
@@ -35,8 +35,7 @@ logger = logging.getLogger("bot")
35
  bot = Bot(
36
  token=config.BOT_TOKEN,
37
  default=DefaultBotProperties(
38
- parse_mode=ParseMode.HTML,
39
- link_preview_is_disabled=True # only here β€” do NOT pass again in send_message/reply
40
  )
41
  )
42
 
@@ -68,7 +67,7 @@ async def link_processor_worker(worker_id: int):
68
  if error:
69
  raise ValueError(error)
70
 
71
- local_filepath, thumb_path, download_error = await terabox.download_terabox_file(
72
  bot,
73
  batch_info["source_chat_id"],
74
  batch_info["status_message"].message_id,
@@ -80,9 +79,7 @@ async def link_processor_worker(worker_id: int):
80
 
81
  file_info = {
82
  'path': local_filepath,
83
- 'name': raw_filename,
84
- 'size': os.path.getsize(local_filepath),
85
- 'thumb': thumb_path
86
  }
87
 
88
  except Exception as e:
@@ -97,8 +94,10 @@ async def link_processor_worker(worker_id: int):
97
 
98
  processed, total = batch_info['processed_links'], batch_info['total_links']
99
  try:
100
- await batch_info["status_message"].edit_text(
101
- f"βš™οΈ Batch `{batch_id[:6]}` in progress... Processed {processed}/{total} links."
 
 
102
  )
103
  except TelegramBadRequest:
104
  pass
@@ -110,20 +109,8 @@ async def link_processor_worker(worker_id: int):
110
  TASK_QUEUE.task_done()
111
 
112
  async def send_file(chat_id: int, file_info: dict, caption: str) -> Message:
113
- file_path_or_id = FSInputFile(file_info['path'], filename=file_info['name'])
114
- filename = file_info.get('name')
115
-
116
- video_exts = ('.mp4', '.mkv', '.mov', '.avi', '.webm')
117
- audio_exts = ('.mp3', '.flac', '.ogg', '.wav')
118
-
119
- sent_message = None
120
- if filename.lower().endswith(video_exts):
121
- sent_message = await bot.send_video(chat_id, file_path_or_id, caption=caption, supports_streaming=True)
122
- elif filename.lower().endswith(audio_exts):
123
- sent_message = await bot.send_audio(chat_id, file_path_or_id, caption=caption)
124
- else:
125
- sent_message = await bot.send_document(chat_id, file_path_or_id, caption=caption)
126
-
127
  return sent_message
128
 
129
  async def handle_batch_completion(batch_id: str):
@@ -139,26 +126,19 @@ async def handle_batch_completion(batch_id: str):
139
  failed_links_text = "\n".join(
140
  [f"- {x['link']} β†’ {x['error']}" for x in batch['failed_links']]
141
  )
142
- await status_msg.edit_text(
143
- f"❌ Batch `{batch_id[:6]}` failed. No files could be processed.\nDetails:\n{failed_links_text}"
 
 
144
  )
145
  return
146
 
147
- await status_msg.edit_text(
148
- f"βœ… Batch `{batch_id[:6]}` downloaded. Preparing to send {len(successful_downloads)} files..."
 
 
149
  )
150
 
151
- if config.FORWARD_CHANNEL_ID:
152
- await bot.forward_message(
153
- config.FORWARD_CHANNEL_ID,
154
- batch["source_chat_id"],
155
- batch["source_message_id"]
156
- )
157
- for item in successful_downloads:
158
- caption = f"`{item.get('name')}`"
159
- await send_file(config.FORWARD_CHANNEL_ID, item, caption)
160
- await asyncio.sleep(1)
161
-
162
  for item in successful_downloads:
163
  caption = f"`{item.get('name')}`"
164
  await send_file(batch["source_chat_id"], item, caption)
@@ -167,19 +147,23 @@ async def handle_batch_completion(batch_id: str):
167
  if batch["failed_links"]:
168
  summary += f"\n❌ {len(batch['failed_links'])} links failed."
169
 
170
- await status_msg.edit_text(summary)
 
 
 
 
171
 
172
  except Exception as e:
173
  logger.error(f"Error during batch completion for {batch_id}: {e}", exc_info=True)
174
- await status_msg.edit_text(
175
- f"A critical error occurred while sending files for batch `{batch_id[:6]}`."
 
 
176
  )
177
  finally:
178
  for item in successful_downloads:
179
  if os.path.exists(item['path']):
180
  os.remove(item['path'])
181
- if item.get('thumb') and os.path.exists(item['thumb']):
182
- os.remove(item['thumb'])
183
 
184
  del BATCH_JOBS[batch_id]
185
 
@@ -190,8 +174,6 @@ async def start_handler(message: Message):
190
  "πŸ‘‹ <b>Welcome to the Terabox Downloader Bot!</b>\n\n"
191
  "πŸ“₯ Send me any valid Terabox link and I will fetch the file and send it to you.\n\n"
192
  f"πŸ“’ Please make sure you are a member of: @{config.FORCE_SUB_CHANNEL_USERNAME}\n\n"
193
- "πŸš€ Supports batch links.\n"
194
- "πŸ’Ύ Fast & lightweight.\n\n"
195
  "βœ… <i>Just send your link below ⬇️</i>"
196
  )
197
  await message.reply(text)
@@ -217,7 +199,10 @@ async def message_handler(message: Message):
217
  return
218
 
219
  batch_id = str(uuid.uuid4())
220
- status_msg = await message.reply(f"βœ… Found {len(terabox_links)} links. Queued as batch `{batch_id[:6]}`.")
 
 
 
221
 
222
  BATCH_JOBS[batch_id] = {
223
  "total_links": len(terabox_links),
 
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
 
35
  bot = Bot(
36
  token=config.BOT_TOKEN,
37
  default=DefaultBotProperties(
38
+ parse_mode=ParseMode.HTML
 
39
  )
40
  )
41
 
 
67
  if error:
68
  raise ValueError(error)
69
 
70
+ local_filepath, _, download_error = await terabox.download_terabox_file(
71
  bot,
72
  batch_info["source_chat_id"],
73
  batch_info["status_message"].message_id,
 
79
 
80
  file_info = {
81
  'path': local_filepath,
82
+ 'name': raw_filename
 
 
83
  }
84
 
85
  except Exception as e:
 
94
 
95
  processed, total = batch_info['processed_links'], batch_info['total_links']
96
  try:
97
+ await bot.edit_message_text(
98
+ chat_id=batch_info["source_chat_id"],
99
+ message_id=batch_info["status_message"].message_id,
100
+ text=f"βš™οΈ Batch `{batch_id[:6]}` in progress... Processed {processed}/{total} links."
101
  )
102
  except TelegramBadRequest:
103
  pass
 
109
  TASK_QUEUE.task_done()
110
 
111
  async def send_file(chat_id: int, file_info: dict, caption: str) -> Message:
112
+ file_path = FSInputFile(file_info['path'], filename=file_info['name'])
113
+ sent_message = await bot.send_document(chat_id, file_path, caption=caption)
 
 
 
 
 
 
 
 
 
 
 
 
114
  return sent_message
115
 
116
  async def handle_batch_completion(batch_id: str):
 
126
  failed_links_text = "\n".join(
127
  [f"- {x['link']} β†’ {x['error']}" for x in batch['failed_links']]
128
  )
129
+ await bot.edit_message_text(
130
+ chat_id=batch["source_chat_id"],
131
+ message_id=status_msg.message_id,
132
+ text=f"❌ Batch `{batch_id[:6]}` failed. No files could be processed.\nDetails:\n{failed_links_text}"
133
  )
134
  return
135
 
136
+ await bot.edit_message_text(
137
+ chat_id=batch["source_chat_id"],
138
+ message_id=status_msg.message_id,
139
+ text=f"βœ… Batch `{batch_id[:6]}` downloaded. Preparing to send {len(successful_downloads)} files..."
140
  )
141
 
 
 
 
 
 
 
 
 
 
 
 
142
  for item in successful_downloads:
143
  caption = f"`{item.get('name')}`"
144
  await send_file(batch["source_chat_id"], item, caption)
 
147
  if batch["failed_links"]:
148
  summary += f"\n❌ {len(batch['failed_links'])} links failed."
149
 
150
+ await bot.edit_message_text(
151
+ chat_id=batch["source_chat_id"],
152
+ message_id=status_msg.message_id,
153
+ text=summary
154
+ )
155
 
156
  except Exception as e:
157
  logger.error(f"Error during batch completion for {batch_id}: {e}", exc_info=True)
158
+ await bot.edit_message_text(
159
+ chat_id=batch["source_chat_id"],
160
+ message_id=status_msg.message_id,
161
+ text=f"A critical error occurred while sending files for batch `{batch_id[:6]}`."
162
  )
163
  finally:
164
  for item in successful_downloads:
165
  if os.path.exists(item['path']):
166
  os.remove(item['path'])
 
 
167
 
168
  del BATCH_JOBS[batch_id]
169
 
 
174
  "πŸ‘‹ <b>Welcome to the Terabox Downloader Bot!</b>\n\n"
175
  "πŸ“₯ Send me any valid Terabox link and I will fetch the file and send it to you.\n\n"
176
  f"πŸ“’ Please make sure you are a member of: @{config.FORCE_SUB_CHANNEL_USERNAME}\n\n"
 
 
177
  "βœ… <i>Just send your link below ⬇️</i>"
178
  )
179
  await message.reply(text)
 
199
  return
200
 
201
  batch_id = str(uuid.uuid4())
202
+ status_msg = await bot.send_message(
203
+ chat_id=message.chat.id,
204
+ text=f"βœ… Found {len(terabox_links)} links. Queued as batch `{batch_id[:6]}`."
205
+ )
206
 
207
  BATCH_JOBS[batch_id] = {
208
  "total_links": len(terabox_links),