Update bot.py
Browse files
bot.py
CHANGED
|
@@ -117,6 +117,33 @@ def parse_repo_url(url: str):
|
|
| 117 |
return None, None
|
| 118 |
return match.group("owner"), match.group("repo")
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
async def fetch_latest_release(owner: str, repo: str):
|
| 121 |
"""Fetches the latest release chronologically by creation or publication date."""
|
| 122 |
url = f"{GITHUB_API}/repos/{owner}/{repo}/releases"
|
|
@@ -280,6 +307,116 @@ def split_file(source_path: str, base_name: str, parts_dir: str):
|
|
| 280 |
yield chunk_path, part_num, total_parts
|
| 281 |
part_num += 1
|
| 282 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
# ---------- Message / Callback handlers ----------
|
| 284 |
def is_authorized(chat_id: int) -> bool:
|
| 285 |
if not ALLOWED_USERS:
|
|
@@ -293,13 +430,23 @@ async def handle_message(message: dict):
|
|
| 293 |
return
|
| 294 |
|
| 295 |
text = message.get("text", "").strip()
|
| 296 |
-
|
| 297 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
elif text.startswith("/watch"):
|
| 299 |
await handle_watch(chat_id, text)
|
| 300 |
else:
|
| 301 |
await send_message(chat_id,
|
| 302 |
-
"Send me a GitHub release URL (e.g., https://github.com/owner/repo) and I'll let you choose an asset.\n"
|
|
|
|
| 303 |
"Or use /watch <repo_url> to get notified of new releases."
|
| 304 |
)
|
| 305 |
|
|
@@ -351,123 +498,11 @@ async def handle_callback(callback: dict):
|
|
| 351 |
|
| 352 |
if data.startswith("dl:"):
|
| 353 |
url = data[3:]
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
original_filename = unquote(raw_filename)
|
| 359 |
-
# Ensure ZIP files downloaded from the API have their proper extension
|
| 360 |
-
if ("zipball" in url or "tarball" in url) and not original_filename.endswith(".zip"):
|
| 361 |
-
original_filename = f"{original_filename}.zip"
|
| 362 |
-
except:
|
| 363 |
-
original_filename = "asset.tmp"
|
| 364 |
-
|
| 365 |
-
logger.info(f"⬇️ Requested asset: {original_filename}")
|
| 366 |
-
|
| 367 |
-
# Status message
|
| 368 |
-
status_msg = await send_message(chat_id, "⏳ Downloading file from GitHub...")
|
| 369 |
-
status_message_id = status_msg.get("result", {}).get("message_id") if status_msg.get("ok") else None
|
| 370 |
-
|
| 371 |
-
# Download original asset
|
| 372 |
-
tmp = tempfile.NamedTemporaryFile(delete=False, suffix="_" + original_filename)
|
| 373 |
-
tmp_path = tmp.name
|
| 374 |
-
try:
|
| 375 |
-
await download_file(url, tmp_path)
|
| 376 |
-
file_size = os.path.getsize(tmp_path)
|
| 377 |
-
size_mb = file_size / (1024 * 1024)
|
| 378 |
-
logger.info(f"✅ Downloaded: {size_mb:.2f} MB")
|
| 379 |
-
|
| 380 |
-
# Compress if not already compressed
|
| 381 |
-
need_compress = not is_compressed(original_filename)
|
| 382 |
-
if need_compress:
|
| 383 |
-
zip_filename = original_filename + ".zip"
|
| 384 |
-
# Create a temporary ZIP file
|
| 385 |
-
zip_tmp = tempfile.NamedTemporaryFile(delete=False, suffix="_" + zip_filename)
|
| 386 |
-
zip_path = zip_tmp.name
|
| 387 |
-
zip_tmp.close()
|
| 388 |
-
compress_to_zip(tmp_path, original_filename, zip_path)
|
| 389 |
-
os.unlink(tmp_path) # remove the original
|
| 390 |
-
tmp_path = zip_path
|
| 391 |
-
upload_filename = zip_filename
|
| 392 |
-
caption_prefix = f"📦 File compressed to ZIP for delivery.\nOriginal: `{original_filename}`"
|
| 393 |
-
else:
|
| 394 |
-
upload_filename = original_filename
|
| 395 |
-
caption_prefix = "Here you go!"
|
| 396 |
-
|
| 397 |
-
upload_size = os.path.getsize(tmp_path)
|
| 398 |
-
upload_size_mb = upload_size / (1024 * 1024)
|
| 399 |
-
|
| 400 |
-
# Decision: split or send directly
|
| 401 |
-
if upload_size > CHUNK_SIZE:
|
| 402 |
-
# Split the (possibly compressed) file
|
| 403 |
-
await send_message(chat_id, f"📦 File is {upload_size_mb:.2f} MB – splitting into parts...")
|
| 404 |
-
if status_message_id:
|
| 405 |
-
await bale_request("deleteMessage", {"chat_id": chat_id, "message_id": status_message_id})
|
| 406 |
-
|
| 407 |
-
with tempfile.TemporaryDirectory() as parts_dir:
|
| 408 |
-
total_parts = math.ceil(upload_size / CHUNK_SIZE)
|
| 409 |
-
parts_sent = 0
|
| 410 |
-
for chunk_path, part_num, total in split_file(tmp_path, upload_filename, parts_dir):
|
| 411 |
-
# Safe base name for the command
|
| 412 |
-
combine_base = upload_filename if upload_filename else original_filename
|
| 413 |
-
|
| 414 |
-
caption = (
|
| 415 |
-
f"📦 Part {part_num}/{total} of `{combine_base}`\n"
|
| 416 |
-
f"Original file: `{original_filename}`\n\n"
|
| 417 |
-
"After downloading all parts:\n"
|
| 418 |
-
f"1. Open **Command Prompt (cmd)** in the folder with the parts.\n"
|
| 419 |
-
f"2. Run:\n"
|
| 420 |
-
f" `copy /b {combine_base}.part* {combine_base}`\n"
|
| 421 |
-
f" (Linux/Mac: `cat {combine_base}.part* > {combine_base}`)\n"
|
| 422 |
-
"3. Extract the combined file to get the original asset."
|
| 423 |
-
)
|
| 424 |
-
result = await send_document_file(chat_id, chunk_path,
|
| 425 |
-
caption=caption,
|
| 426 |
-
display_filename=os.path.basename(chunk_path))
|
| 427 |
-
if not result.get("ok"):
|
| 428 |
-
await send_message(chat_id, f"❌ Failed to send part {part_num}. Error: {result.get('description')}")
|
| 429 |
-
break
|
| 430 |
-
parts_sent += 1
|
| 431 |
-
|
| 432 |
-
if parts_sent == total_parts:
|
| 433 |
-
await answer_callback(callback_id, "All parts sent.")
|
| 434 |
-
elif parts_sent > 0:
|
| 435 |
-
await answer_callback(callback_id, f"Only {parts_sent}/{total_parts} parts sent.")
|
| 436 |
-
else:
|
| 437 |
-
await answer_callback(callback_id, "Failed to send any part.")
|
| 438 |
-
|
| 439 |
-
else:
|
| 440 |
-
# Small enough – send directly
|
| 441 |
-
if status_message_id:
|
| 442 |
-
await bale_request("editMessageText", {
|
| 443 |
-
"chat_id": chat_id,
|
| 444 |
-
"message_id": status_message_id,
|
| 445 |
-
"text": f"📥 Downloaded {upload_size_mb:.2f} MB – uploading to Bale..."
|
| 446 |
-
})
|
| 447 |
-
else:
|
| 448 |
-
await send_message(chat_id, f"📥 Downloaded {upload_size_mb:.2f} MB – uploading to Bale...")
|
| 449 |
-
|
| 450 |
-
result = await send_document_file(chat_id, tmp_path,
|
| 451 |
-
caption=caption_prefix,
|
| 452 |
-
display_filename=upload_filename)
|
| 453 |
-
if result.get("ok"):
|
| 454 |
-
if status_message_id:
|
| 455 |
-
await bale_request("deleteMessage", {"chat_id": chat_id, "message_id": status_message_id})
|
| 456 |
-
await answer_callback(callback_id, "Sent!")
|
| 457 |
-
else:
|
| 458 |
-
raw_error = result.get("description", str(result))
|
| 459 |
-
await send_message(chat_id, f"❌ Upload failed. Bale response:\n{raw_error}")
|
| 460 |
-
await answer_callback(callback_id, "Failed to send.")
|
| 461 |
-
|
| 462 |
-
except Exception as e:
|
| 463 |
-
logger.error(f"❌ Download/Upload error: {e}", exc_info=True)
|
| 464 |
-
await send_message(chat_id, f"❌ Error: {e}")
|
| 465 |
await answer_callback(callback_id, "Failed.")
|
| 466 |
-
finally:
|
| 467 |
-
try:
|
| 468 |
-
os.unlink(tmp_path)
|
| 469 |
-
except Exception:
|
| 470 |
-
pass
|
| 471 |
else:
|
| 472 |
await answer_callback(callback_id, "Unknown action.")
|
| 473 |
|
|
|
|
| 117 |
return None, None
|
| 118 |
return match.group("owner"), match.group("repo")
|
| 119 |
|
| 120 |
+
def convert_github_url_to_direct(url: str) -> str:
|
| 121 |
+
"""
|
| 122 |
+
Identifies if a URL is a direct file or source code release asset.
|
| 123 |
+
Converts browser blob/raw paths to direct, downloadable raw usercontent links.
|
| 124 |
+
"""
|
| 125 |
+
# Already a direct raw link
|
| 126 |
+
if "raw.githubusercontent.com" in url:
|
| 127 |
+
return url
|
| 128 |
+
|
| 129 |
+
# Release download file (github.com/owner/repo/releases/download/tag/filename)
|
| 130 |
+
if "/releases/download/" in url:
|
| 131 |
+
return url
|
| 132 |
+
|
| 133 |
+
# Source archive archive file (github.com/owner/repo/archive/...)
|
| 134 |
+
if "/archive/" in url:
|
| 135 |
+
return url
|
| 136 |
+
|
| 137 |
+
# Browser blob link (github.com/owner/repo/blob/branch/path) -> convert to raw usercontent
|
| 138 |
+
if "/blob/" in url:
|
| 139 |
+
return url.replace("github.com", "raw.githubusercontent.com").replace("/blob/", "/")
|
| 140 |
+
|
| 141 |
+
# Browser raw link (github.com/owner/repo/raw/branch/path) -> convert to raw usercontent
|
| 142 |
+
if "/raw/" in url:
|
| 143 |
+
return url.replace("github.com", "raw.githubusercontent.com").replace("/raw/", "/")
|
| 144 |
+
|
| 145 |
+
return None
|
| 146 |
+
|
| 147 |
async def fetch_latest_release(owner: str, repo: str):
|
| 148 |
"""Fetches the latest release chronologically by creation or publication date."""
|
| 149 |
url = f"{GITHUB_API}/repos/{owner}/{repo}/releases"
|
|
|
|
| 307 |
yield chunk_path, part_num, total_parts
|
| 308 |
part_num += 1
|
| 309 |
|
| 310 |
+
# ---------- File Processing Engine ----------
|
| 311 |
+
async def download_and_send_file(chat_id: int, url: str, status_msg_id_to_edit: int = None) -> bool:
|
| 312 |
+
"""Downloads a file from url, compresses it if needed, splits if large, and uploads to Bale."""
|
| 313 |
+
try:
|
| 314 |
+
raw_filename = url.split("/")[-1].split("?")[0]
|
| 315 |
+
original_filename = unquote(raw_filename)
|
| 316 |
+
# Ensure ZIP files downloaded from the API have their proper extension
|
| 317 |
+
if ("zipball" in url or "tarball" in url or "/archive/" in url) and not original_filename.endswith(".zip"):
|
| 318 |
+
original_filename = f"{original_filename}.zip"
|
| 319 |
+
except:
|
| 320 |
+
original_filename = "asset.tmp"
|
| 321 |
+
|
| 322 |
+
logger.info(f"⬇️ Processing download: {original_filename} from {url}")
|
| 323 |
+
|
| 324 |
+
status_message_id = status_msg_id_to_edit
|
| 325 |
+
if not status_message_id:
|
| 326 |
+
status_msg = await send_message(chat_id, "⏳ Downloading file...")
|
| 327 |
+
status_message_id = status_msg.get("result", {}).get("message_id") if status_msg.get("ok") else None
|
| 328 |
+
|
| 329 |
+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix="_" + original_filename)
|
| 330 |
+
tmp_path = tmp.name
|
| 331 |
+
try:
|
| 332 |
+
await download_file(url, tmp_path)
|
| 333 |
+
file_size = os.path.getsize(tmp_path)
|
| 334 |
+
size_mb = file_size / (1024 * 1024)
|
| 335 |
+
logger.info(f"✅ Downloaded: {size_mb:.2f} MB")
|
| 336 |
+
|
| 337 |
+
# Compress if not already compressed
|
| 338 |
+
need_compress = not is_compressed(original_filename)
|
| 339 |
+
if need_compress:
|
| 340 |
+
zip_filename = original_filename + ".zip"
|
| 341 |
+
zip_tmp = tempfile.NamedTemporaryFile(delete=False, suffix="_" + zip_filename)
|
| 342 |
+
zip_path = zip_tmp.name
|
| 343 |
+
zip_tmp.close()
|
| 344 |
+
compress_to_zip(tmp_path, original_filename, zip_path)
|
| 345 |
+
os.unlink(tmp_path) # remove the original
|
| 346 |
+
tmp_path = zip_path
|
| 347 |
+
upload_filename = zip_filename
|
| 348 |
+
caption_prefix = f"📦 File compressed to ZIP for delivery.\nOriginal: `{original_filename}`"
|
| 349 |
+
else:
|
| 350 |
+
upload_filename = original_filename
|
| 351 |
+
caption_prefix = "Here you go!"
|
| 352 |
+
|
| 353 |
+
upload_size = os.path.getsize(tmp_path)
|
| 354 |
+
upload_size_mb = upload_size / (1024 * 1024)
|
| 355 |
+
|
| 356 |
+
# Decision: split or send directly
|
| 357 |
+
if upload_size > CHUNK_SIZE:
|
| 358 |
+
await send_message(chat_id, f"📦 File is {upload_size_mb:.2f} MB – splitting into parts...")
|
| 359 |
+
if status_message_id:
|
| 360 |
+
await bale_request("deleteMessage", {"chat_id": chat_id, "message_id": status_message_id})
|
| 361 |
+
|
| 362 |
+
with tempfile.TemporaryDirectory() as parts_dir:
|
| 363 |
+
total_parts = math.ceil(upload_size / CHUNK_SIZE)
|
| 364 |
+
parts_sent = 0
|
| 365 |
+
for chunk_path, part_num, total in split_file(tmp_path, upload_filename, parts_dir):
|
| 366 |
+
combine_base = upload_filename if upload_filename else original_filename
|
| 367 |
+
|
| 368 |
+
caption = (
|
| 369 |
+
f"📦 Part {part_num}/{total} of `{combine_base}`\n"
|
| 370 |
+
f"Original file: `{original_filename}`\n\n"
|
| 371 |
+
"After downloading all parts:\n"
|
| 372 |
+
f"1. Open **Command Prompt (cmd)** in the folder with the parts.\n"
|
| 373 |
+
f"2. Run:\n"
|
| 374 |
+
f" `copy /b {combine_base}.part* {combine_base}`\n"
|
| 375 |
+
f" (Linux/Mac: `cat {combine_base}.part* > {combine_base}`)\n"
|
| 376 |
+
"3. Extract the combined file to get the original asset."
|
| 377 |
+
)
|
| 378 |
+
result = await send_document_file(chat_id, chunk_path,
|
| 379 |
+
caption=caption,
|
| 380 |
+
display_filename=os.path.basename(chunk_path))
|
| 381 |
+
if not result.get("ok"):
|
| 382 |
+
await send_message(chat_id, f"❌ Failed to send part {part_num}. Error: {result.get('description')}")
|
| 383 |
+
break
|
| 384 |
+
parts_sent += 1
|
| 385 |
+
return parts_sent == total_parts
|
| 386 |
+
|
| 387 |
+
else:
|
| 388 |
+
# Small enough – send directly
|
| 389 |
+
if status_message_id:
|
| 390 |
+
await bale_request("editMessageText", {
|
| 391 |
+
"chat_id": chat_id,
|
| 392 |
+
"message_id": status_message_id,
|
| 393 |
+
"text": f"📥 Downloaded {upload_size_mb:.2f} MB – uploading to Bale..."
|
| 394 |
+
})
|
| 395 |
+
else:
|
| 396 |
+
await send_message(chat_id, f"📥 Downloaded {upload_size_mb:.2f} MB – uploading to Bale...")
|
| 397 |
+
|
| 398 |
+
result = await send_document_file(chat_id, tmp_path,
|
| 399 |
+
caption=caption_prefix,
|
| 400 |
+
display_filename=upload_filename)
|
| 401 |
+
if result.get("ok"):
|
| 402 |
+
if status_message_id:
|
| 403 |
+
await bale_request("deleteMessage", {"chat_id": chat_id, "message_id": status_message_id})
|
| 404 |
+
return True
|
| 405 |
+
else:
|
| 406 |
+
raw_error = result.get("description", str(result))
|
| 407 |
+
await send_message(chat_id, f"❌ Upload failed. Bale response:\n{raw_error}")
|
| 408 |
+
return False
|
| 409 |
+
|
| 410 |
+
except Exception as e:
|
| 411 |
+
logger.error(f"❌ Download/Upload error: {e}", exc_info=True)
|
| 412 |
+
await send_message(chat_id, f"❌ Error: {e}")
|
| 413 |
+
return False
|
| 414 |
+
finally:
|
| 415 |
+
try:
|
| 416 |
+
os.unlink(tmp_path)
|
| 417 |
+
except Exception:
|
| 418 |
+
pass
|
| 419 |
+
|
| 420 |
# ---------- Message / Callback handlers ----------
|
| 421 |
def is_authorized(chat_id: int) -> bool:
|
| 422 |
if not ALLOWED_USERS:
|
|
|
|
| 430 |
return
|
| 431 |
|
| 432 |
text = message.get("text", "").strip()
|
| 433 |
+
|
| 434 |
+
# Identify if a user sent a GitHub link (either a repository page, raw link, or blob link)
|
| 435 |
+
if ("github.com/" in text or "raw.githubusercontent.com" in text) and not text.startswith("/"):
|
| 436 |
+
direct_url = convert_github_url_to_direct(text)
|
| 437 |
+
if direct_url:
|
| 438 |
+
logger.info(f"🎯 Direct link detected: {direct_url}. Bypassing menu.")
|
| 439 |
+
await download_and_send_file(chat_id, direct_url)
|
| 440 |
+
else:
|
| 441 |
+
# Standard on-demand release selection menu flow
|
| 442 |
+
await handle_on_demand(chat_id, text)
|
| 443 |
+
|
| 444 |
elif text.startswith("/watch"):
|
| 445 |
await handle_watch(chat_id, text)
|
| 446 |
else:
|
| 447 |
await send_message(chat_id,
|
| 448 |
+
"Send me a GitHub repository or release page URL (e.g., https://github.com/owner/repo) and I'll let you choose an asset.\n\n"
|
| 449 |
+
"Or send a direct link to a release asset, source archive, or single file from a repo, and I will download it directly.\n\n"
|
| 450 |
"Or use /watch <repo_url> to get notified of new releases."
|
| 451 |
)
|
| 452 |
|
|
|
|
| 498 |
|
| 499 |
if data.startswith("dl:"):
|
| 500 |
url = data[3:]
|
| 501 |
+
success = await download_and_send_file(chat_id, url)
|
| 502 |
+
if success:
|
| 503 |
+
await answer_callback(callback_id, "Sent!")
|
| 504 |
+
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 505 |
await answer_callback(callback_id, "Failed.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 506 |
else:
|
| 507 |
await answer_callback(callback_id, "Unknown action.")
|
| 508 |
|