understanding commited on
Commit
2751d3a
Β·
verified Β·
1 Parent(s): 44de040

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +38 -63
bot.py CHANGED
@@ -1,3 +1,5 @@
 
 
1
  import asyncio
2
  import logging
3
  import os
@@ -34,7 +36,7 @@ bot = Bot(
34
  token=config.BOT_TOKEN,
35
  default=DefaultBotProperties(
36
  parse_mode=ParseMode.HTML,
37
- link_preview_is_disabled=True
38
  )
39
  )
40
 
@@ -62,33 +64,26 @@ async def link_processor_worker(worker_id: int):
62
  if not short_id:
63
  raise ValueError("Invalid Terabox link format.")
64
 
65
- cached_file = await db_utils.get_cached_file(short_id)
66
- if cached_file:
67
- logger.info(f"Cache hit for {short_id}. Reusing file_id.")
68
- file_info = {'cached': True, 'short_id': short_id, **cached_file}
69
- else:
70
- download_url, raw_filename, error = await terabox.get_final_url_and_filename(original_link)
71
- if error:
72
- raise ValueError(error)
73
-
74
- local_filepath, thumb_path, download_error = await terabox.download_terabox_file(
75
- bot,
76
- batch_info["source_chat_id"],
77
- batch_info["status_message"].message_id,
78
- download_url,
79
- raw_filename
80
- )
81
- if download_error:
82
- raise ValueError(download_error)
83
-
84
- file_info = {
85
- 'cached': False,
86
- 'path': local_filepath,
87
- 'name': raw_filename,
88
- 'size': os.path.getsize(local_filepath),
89
- 'short_id': short_id,
90
- 'thumb': thumb_path
91
- }
92
 
93
  except Exception as e:
94
  error_msg = str(e)
@@ -114,30 +109,20 @@ async def link_processor_worker(worker_id: int):
114
 
115
  TASK_QUEUE.task_done()
116
 
117
- async def send_and_cache_file(chat_id: int, file_info: dict, caption: str) -> Message:
118
- file_path_or_id = file_info.get('file_id') or FSInputFile(file_info['path'], filename=file_info['name'])
119
- media_type = file_info.get('type')
120
- filename = file_info.get('name') or file_info.get('filename')
121
 
122
  video_exts = ('.mp4', '.mkv', '.mov', '.avi', '.webm')
123
  audio_exts = ('.mp3', '.flac', '.ogg', '.wav')
124
 
125
  sent_message = None
126
- if media_type == 'video' or filename.lower().endswith(video_exts):
127
  sent_message = await bot.send_video(chat_id, file_path_or_id, caption=caption, supports_streaming=True)
128
- media_type = 'video'
129
- elif media_type == 'audio' or filename.lower().endswith(audio_exts):
130
  sent_message = await bot.send_audio(chat_id, file_path_or_id, caption=caption)
131
- media_type = 'audio'
132
  else:
133
  sent_message = await bot.send_document(chat_id, file_path_or_id, caption=caption)
134
- media_type = 'document'
135
-
136
- if not file_info.get('cached') and sent_message:
137
- file_id_to_cache = getattr(sent_message, media_type).file_id
138
- await db_utils.add_to_cache(
139
- file_info['short_id'], file_id_to_cache, filename, media_type, file_info['size']
140
- )
141
 
142
  return sent_message
143
 
@@ -170,13 +155,13 @@ async def handle_batch_completion(batch_id: str):
170
  batch["source_message_id"]
171
  )
172
  for item in successful_downloads:
173
- caption = f"`{item.get('name') or item.get('filename')}`"
174
- await send_and_cache_file(config.FORWARD_CHANNEL_ID, item, caption)
175
  await asyncio.sleep(1)
176
 
177
  for item in successful_downloads:
178
- caption = f"`{item.get('name') or item.get('filename')}`"
179
- await send_and_cache_file(batch["source_chat_id"], item, caption)
180
 
181
  summary = f"βœ… Batch `{batch_id[:6]}` complete: {len(successful_downloads)} files sent."
182
  if batch["failed_links"]:
@@ -191,7 +176,7 @@ async def handle_batch_completion(batch_id: str):
191
  )
192
  finally:
193
  for item in successful_downloads:
194
- if not item.get('cached') and os.path.exists(item['path']):
195
  os.remove(item['path'])
196
  if item.get('thumb') and os.path.exists(item['thumb']):
197
  os.remove(item['thumb'])
@@ -205,16 +190,11 @@ async def start_handler(message: Message):
205
  "πŸ‘‹ <b>Welcome to the Terabox Downloader Bot!</b>\n\n"
206
  "πŸ“₯ Send me any valid Terabox link and I will fetch the file and send it to you.\n\n"
207
  f"πŸ“’ Please make sure you are a member of: @{config.FORCE_SUB_CHANNEL_USERNAME}\n\n"
208
- "πŸš€ Supports batch links & auto-caching.\n"
209
  "πŸ’Ύ Fast & lightweight.\n\n"
210
  "βœ… <i>Just send your link below ⬇️</i>"
211
  )
212
- await bot.send_message(
213
- chat_id=message.chat.id,
214
- text=text,
215
- parse_mode=ParseMode.HTML,
216
- disable_web_page_preview=True
217
- )
218
 
219
  @dp.message(F.text | F.caption)
220
  async def message_handler(message: Message):
@@ -227,7 +207,7 @@ async def message_handler(message: Message):
227
  message.from_user.first_name
228
  )
229
 
230
- links = list(set(re.findall(r'https?://[^\s<>\"\']+', message.text or message.caption or "")))
231
  terabox_links = [link for link in links if any(domain in link for domain in [
232
  "terabox.com", "teraboxapp.com", "terasharelink.com", "1024tera.com",
233
  "freeterabox.com", "4funbox.com", "box-links.com"
@@ -237,12 +217,7 @@ async def message_handler(message: Message):
237
  return
238
 
239
  batch_id = str(uuid.uuid4())
240
- status_msg = await bot.send_message(
241
- chat_id=message.chat.id,
242
- text=f"βœ… Found {len(terabox_links)} links. Queued as batch `{batch_id[:6]}`.",
243
- parse_mode=ParseMode.HTML,
244
- disable_web_page_preview=True
245
- )
246
 
247
  BATCH_JOBS[batch_id] = {
248
  "total_links": len(terabox_links),
@@ -270,4 +245,4 @@ def start_bot():
270
  dp.startup.register(on_startup)
271
  dp.message.register(message_handler)
272
  dp.message.register(start_handler, CommandStart())
273
- return dp, bot
 
1
+ # bot.py
2
+
3
  import asyncio
4
  import logging
5
  import os
 
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
 
 
64
  if not short_id:
65
  raise ValueError("Invalid Terabox link format.")
66
 
67
+ download_url, raw_filename, error = await terabox.get_final_url_and_filename(original_link)
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,
75
+ download_url,
76
+ raw_filename
77
+ )
78
+ if download_error:
79
+ raise ValueError(download_error)
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:
89
  error_msg = str(e)
 
109
 
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
 
 
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)
165
 
166
  summary = f"βœ… Batch `{batch_id[:6]}` complete: {len(successful_downloads)} files sent."
167
  if batch["failed_links"]:
 
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'])
 
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)
 
 
 
 
 
198
 
199
  @dp.message(F.text | F.caption)
200
  async def message_handler(message: Message):
 
207
  message.from_user.first_name
208
  )
209
 
210
+ links = list(set(re.findall(r'https?://[^\s<>"\']+', message.text or message.caption or "")))
211
  terabox_links = [link for link in links if any(domain in link for domain in [
212
  "terabox.com", "teraboxapp.com", "terasharelink.com", "1024tera.com",
213
  "freeterabox.com", "4funbox.com", "box-links.com"
 
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),
 
245
  dp.startup.register(on_startup)
246
  dp.message.register(message_handler)
247
  dp.message.register(start_handler, CommandStart())
248
+ return dp, bot