Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import time
|
|
|
|
| 3 |
import base64
|
| 4 |
import hashlib
|
| 5 |
import shutil
|
|
@@ -27,6 +28,7 @@ OBFUSCATION_KEY = os.environ.get("OBFUSCATION_KEY", "change-me-to-a-secret-strin
|
|
| 27 |
DATASET_REPO = "Cxops/Bzxv"
|
| 28 |
MAX_FILE_SIZE_TG = 1900 * 1024 * 1024 # 1900 MB per Telegram part
|
| 29 |
MIN_FREE_DISK = 45 * 1024 * 1024 * 1024 # 45 GB
|
|
|
|
| 30 |
KEEPALIVE_INTERVAL = 300 # 5 minutes
|
| 31 |
DB_PATH = "bot_files.db"
|
| 32 |
|
|
@@ -88,7 +90,7 @@ def db_remove_all_user_files(user_id):
|
|
| 88 |
file_callback_map = {} # token -> enc_path
|
| 89 |
upload_prompt_map = {} # token -> list of (user_id, message_id, orig_filename)
|
| 90 |
|
| 91 |
-
# Album group storage: media_group_id -> dict
|
| 92 |
album_groups = {}
|
| 93 |
|
| 94 |
def make_token():
|
|
@@ -118,6 +120,7 @@ app = Client(
|
|
| 118 |
# --------------- ASYNC QUEUE & STATE ---------------
|
| 119 |
upload_queue = asyncio.Queue()
|
| 120 |
active_jobs = {}
|
|
|
|
| 121 |
|
| 122 |
# --------------- HELPERS ---------------
|
| 123 |
def cleanup(path: str):
|
|
@@ -143,6 +146,20 @@ def format_size(bytes_val):
|
|
| 143 |
def format_speed(bytes_per_sec):
|
| 144 |
return f"{format_size(bytes_per_sec)}/s"
|
| 145 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
async def send_progress_updater(job_id, status_msg, cancel_event, total_bytes):
|
| 147 |
"""Shows Telegram send progress every 3s."""
|
| 148 |
bytes_holder = [0]
|
|
@@ -464,10 +481,29 @@ async def upload_worker():
|
|
| 464 |
@app.on_message(filters.command("start"))
|
| 465 |
async def start_cmd(_, message):
|
| 466 |
await message.reply_text(
|
| 467 |
-
"Send me any file
|
| 468 |
-
"/files – list your uploaded files"
|
|
|
|
| 469 |
)
|
| 470 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 471 |
@app.on_message(filters.command("files"))
|
| 472 |
async def list_files_cmd(_, message):
|
| 473 |
user_id = message.from_user.id
|
|
@@ -630,13 +666,134 @@ async def upload_all_callback(_, query):
|
|
| 630 |
async def cancel_upload_prompt(_, query):
|
| 631 |
await query.message.delete()
|
| 632 |
|
| 633 |
-
# -----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 634 |
@app.on_message(
|
| 635 |
filters.document | filters.video | filters.audio | filters.photo |
|
| 636 |
filters.animation | filters.sticker | filters.video_note | filters.voice
|
| 637 |
)
|
| 638 |
async def on_file(_, message):
|
| 639 |
-
# Determine filename for every possible type
|
| 640 |
if message.document:
|
| 641 |
filename = message.document.file_name
|
| 642 |
elif message.video:
|
|
@@ -648,7 +805,6 @@ async def on_file(_, message):
|
|
| 648 |
elif message.animation:
|
| 649 |
filename = message.animation.file_name or f"{message.animation.file_unique_id}.mp4"
|
| 650 |
elif message.sticker:
|
| 651 |
-
# Stickers can be .webp, .tgs, .webm
|
| 652 |
if message.sticker.is_animated:
|
| 653 |
filename = f"{message.sticker.file_unique_id}.tgs"
|
| 654 |
elif message.sticker.is_video:
|
|
@@ -660,9 +816,8 @@ async def on_file(_, message):
|
|
| 660 |
elif message.voice:
|
| 661 |
filename = f"{message.voice.file_unique_id}.ogg"
|
| 662 |
else:
|
| 663 |
-
return
|
| 664 |
|
| 665 |
-
# Album grouping (for photos, videos, documents that belong to an album)
|
| 666 |
if message.media_group_id and (message.photo or message.video or message.document):
|
| 667 |
group_id = str(message.media_group_id)
|
| 668 |
chat_id = message.chat.id
|
|
|
|
| 1 |
import os
|
| 2 |
import time
|
| 3 |
+
import re
|
| 4 |
import base64
|
| 5 |
import hashlib
|
| 6 |
import shutil
|
|
|
|
| 28 |
DATASET_REPO = "Cxops/Bzxv"
|
| 29 |
MAX_FILE_SIZE_TG = 1900 * 1024 * 1024 # 1900 MB per Telegram part
|
| 30 |
MIN_FREE_DISK = 45 * 1024 * 1024 * 1024 # 45 GB
|
| 31 |
+
DATASET_MAX_SIZE = 8.7 * 1024 * 1024 * 1024 * 1024 # 8.7 TB
|
| 32 |
KEEPALIVE_INTERVAL = 300 # 5 minutes
|
| 33 |
DB_PATH = "bot_files.db"
|
| 34 |
|
|
|
|
| 90 |
file_callback_map = {} # token -> enc_path
|
| 91 |
upload_prompt_map = {} # token -> list of (user_id, message_id, orig_filename)
|
| 92 |
|
| 93 |
+
# Album group storage: media_group_id -> dict
|
| 94 |
album_groups = {}
|
| 95 |
|
| 96 |
def make_token():
|
|
|
|
| 120 |
# --------------- ASYNC QUEUE & STATE ---------------
|
| 121 |
upload_queue = asyncio.Queue()
|
| 122 |
active_jobs = {}
|
| 123 |
+
bot_start_time = time.time()
|
| 124 |
|
| 125 |
# --------------- HELPERS ---------------
|
| 126 |
def cleanup(path: str):
|
|
|
|
| 146 |
def format_speed(bytes_per_sec):
|
| 147 |
return f"{format_size(bytes_per_sec)}/s"
|
| 148 |
|
| 149 |
+
def get_memory_usage() -> str:
|
| 150 |
+
"""Return current process memory usage (RSS) as a human-readable string."""
|
| 151 |
+
try:
|
| 152 |
+
# Linux only
|
| 153 |
+
with open("/proc/self/status") as f:
|
| 154 |
+
for line in f:
|
| 155 |
+
if line.startswith("VmRSS:"):
|
| 156 |
+
# Value is in kB
|
| 157 |
+
kb = int(line.split()[1])
|
| 158 |
+
return format_size(kb * 1024)
|
| 159 |
+
except Exception:
|
| 160 |
+
pass
|
| 161 |
+
return "unknown"
|
| 162 |
+
|
| 163 |
async def send_progress_updater(job_id, status_msg, cancel_event, total_bytes):
|
| 164 |
"""Shows Telegram send progress every 3s."""
|
| 165 |
bytes_holder = [0]
|
|
|
|
| 481 |
@app.on_message(filters.command("start"))
|
| 482 |
async def start_cmd(_, message):
|
| 483 |
await message.reply_text(
|
| 484 |
+
"Send me any file or a Telegram message link to upload.\n"
|
| 485 |
+
"/files – list your uploaded files\n"
|
| 486 |
+
"/status – show disk, dataset & system status"
|
| 487 |
)
|
| 488 |
|
| 489 |
+
@app.on_message(filters.command("status"))
|
| 490 |
+
async def status_cmd(_, message):
|
| 491 |
+
free = get_free_disk()
|
| 492 |
+
disk_text = f"💾 Local disk: {format_size(free)} free (min {format_size(MIN_FREE_DISK)})"
|
| 493 |
+
|
| 494 |
+
try:
|
| 495 |
+
info = hf.dataset_info(repo_id=DATASET_REPO)
|
| 496 |
+
used = info.used_storage if info.used_storage else 0
|
| 497 |
+
except Exception:
|
| 498 |
+
used = 0
|
| 499 |
+
dataset_text = f"📦 Dataset: {format_size(used)} used of {format_size(DATASET_MAX_SIZE)}"
|
| 500 |
+
|
| 501 |
+
uptime_seconds = int(time.time() - bot_start_time)
|
| 502 |
+
uptime_text = f"⏱️ Uptime: {uptime_seconds//3600}h {(uptime_seconds%3600)//60}m {uptime_seconds%60}s"
|
| 503 |
+
mem_text = f"🧠 Memory: {get_memory_usage()}"
|
| 504 |
+
|
| 505 |
+
await message.reply_text(f"{disk_text}\n{dataset_text}\n{uptime_text}\n{mem_text}")
|
| 506 |
+
|
| 507 |
@app.on_message(filters.command("files"))
|
| 508 |
async def list_files_cmd(_, message):
|
| 509 |
user_id = message.from_user.id
|
|
|
|
| 666 |
async def cancel_upload_prompt(_, query):
|
| 667 |
await query.message.delete()
|
| 668 |
|
| 669 |
+
# ----------- MESSAGE LINK HANDLER -----------
|
| 670 |
+
@app.on_message(filters.text & ~filters.command(["start", "files", "status", "delete_all"]) & filters.regex(r'https?://t\.me/'))
|
| 671 |
+
async def on_message_link(client, message):
|
| 672 |
+
# Extract first valid t.me link
|
| 673 |
+
links = re.findall(r'(https?://t\.me/((?:c/)?[\w\d_]+)/(\d+))', message.text)
|
| 674 |
+
if not links:
|
| 675 |
+
return # shouldn't happen because of filter, but just in case
|
| 676 |
+
|
| 677 |
+
# Process the first link found
|
| 678 |
+
full_link, chat_str, msg_id_str = links[0]
|
| 679 |
+
msg_id = int(msg_id_str)
|
| 680 |
+
|
| 681 |
+
try:
|
| 682 |
+
if chat_str.startswith("c/"):
|
| 683 |
+
# Numeric chat id: t.me/c/123456789/1234
|
| 684 |
+
chat_id = int("-100" + chat_str[2:])
|
| 685 |
+
else:
|
| 686 |
+
chat_id = chat_str # username
|
| 687 |
+
|
| 688 |
+
# Fetch the message
|
| 689 |
+
msg = await app.get_messages(chat_id, msg_id)
|
| 690 |
+
except Exception as e:
|
| 691 |
+
await message.reply_text(f"❌ Could not access the message: {e}")
|
| 692 |
+
return
|
| 693 |
+
|
| 694 |
+
if not msg.media:
|
| 695 |
+
await message.reply_text("The linked message does not contain any downloadable file.")
|
| 696 |
+
return
|
| 697 |
+
|
| 698 |
+
# Determine the file name from the fetched message
|
| 699 |
+
if msg.document:
|
| 700 |
+
filename = msg.document.file_name
|
| 701 |
+
elif msg.video:
|
| 702 |
+
filename = msg.video.file_name or f"{msg.video.file_unique_id}.mp4"
|
| 703 |
+
elif msg.audio:
|
| 704 |
+
filename = msg.audio.file_name or f"{msg.audio.file_unique_id}.mp3"
|
| 705 |
+
elif msg.photo:
|
| 706 |
+
filename = f"{msg.photo.file_unique_id}.jpg"
|
| 707 |
+
elif msg.animation:
|
| 708 |
+
filename = msg.animation.file_name or f"{msg.animation.file_unique_id}.mp4"
|
| 709 |
+
elif msg.sticker:
|
| 710 |
+
if msg.sticker.is_animated:
|
| 711 |
+
filename = f"{msg.sticker.file_unique_id}.tgs"
|
| 712 |
+
elif msg.sticker.is_video:
|
| 713 |
+
filename = f"{msg.sticker.file_unique_id}.webm"
|
| 714 |
+
else:
|
| 715 |
+
filename = f"{msg.sticker.file_unique_id}.webp"
|
| 716 |
+
elif msg.video_note:
|
| 717 |
+
filename = f"{msg.video_note.file_unique_id}.mp4"
|
| 718 |
+
elif msg.voice:
|
| 719 |
+
filename = f"{msg.voice.file_unique_id}.ogg"
|
| 720 |
+
else:
|
| 721 |
+
filename = f"file_{msg_id}"
|
| 722 |
+
|
| 723 |
+
# We'll use the message object directly as the source for download.
|
| 724 |
+
# Important: The upload queue expects a Telegram message object from the user's chat,
|
| 725 |
+
# but here the message is from another chat. It still works because Pyrogram's download()
|
| 726 |
+
# works on any message object the bot can access. So we can pass it directly.
|
| 727 |
+
|
| 728 |
+
token = make_token()
|
| 729 |
+
# Store (user_id, message_id, filename) - but message_id is from the original chat.
|
| 730 |
+
# For the upload callback we need to retrieve the message by its original chat.
|
| 731 |
+
# To simplify, we can store the chat_id and msg_id as well.
|
| 732 |
+
# Let's modify the mapping to include chat_id: (user_id, chat_id_of_file, msg_id, filename)
|
| 733 |
+
# But the current upload_prompt_map structure expects messages from the same chat as the user.
|
| 734 |
+
# We'll extend the mapping to handle remote messages. We'll store:
|
| 735 |
+
# token -> (user_id, file_chat_id, msg_id, filename)
|
| 736 |
+
# We'll adjust upload_callback accordingly.
|
| 737 |
+
upload_prompt_map[token] = [(message.from_user.id, chat_id, msg_id, filename)]
|
| 738 |
+
|
| 739 |
+
kb = InlineKeyboardMarkup([
|
| 740 |
+
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{token}")],
|
| 741 |
+
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")]
|
| 742 |
+
])
|
| 743 |
+
await message.reply_text(
|
| 744 |
+
f"Found file `{filename}` in the linked message. Do you want to upload it?",
|
| 745 |
+
reply_markup=kb
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
+
# Override the upload callback to handle remote messages (those from message links)
|
| 749 |
+
# We'll modify the upload_callback function to check if the data tuple has 4 elements instead of 3
|
| 750 |
+
# and retrieve the message accordingly.
|
| 751 |
+
|
| 752 |
+
@app.on_callback_query(filters.regex("^upload:"))
|
| 753 |
+
async def upload_callback_v2(_, query):
|
| 754 |
+
token = query.data.replace("upload:", "")
|
| 755 |
+
data = upload_prompt_map.pop(token, None)
|
| 756 |
+
if not data:
|
| 757 |
+
return await query.answer("Upload prompt expired. Please send the file again.", show_alert=True)
|
| 758 |
+
|
| 759 |
+
chat_id = query.message.chat.id
|
| 760 |
+
for entry in data:
|
| 761 |
+
if len(entry) == 4:
|
| 762 |
+
# Remote message: (user_id, file_chat_id, msg_id, orig_filename)
|
| 763 |
+
user_id, file_chat_id, msg_id, orig_filename = entry
|
| 764 |
+
try:
|
| 765 |
+
file_msg = await app.get_messages(file_chat_id, msg_id)
|
| 766 |
+
except Exception:
|
| 767 |
+
await query.answer(f"Message for {orig_filename} missing.", show_alert=True)
|
| 768 |
+
continue
|
| 769 |
+
else:
|
| 770 |
+
# Local message: (user_id, msg_id, orig_filename)
|
| 771 |
+
user_id, msg_id, orig_filename = entry
|
| 772 |
+
try:
|
| 773 |
+
file_msg = await app.get_messages(chat_id, msg_id)
|
| 774 |
+
except Exception:
|
| 775 |
+
await query.answer(f"Message for {orig_filename} missing.", show_alert=True)
|
| 776 |
+
continue
|
| 777 |
+
|
| 778 |
+
if not file_msg:
|
| 779 |
+
await query.answer(f"File {orig_filename} no longer available.", show_alert=True)
|
| 780 |
+
continue
|
| 781 |
+
|
| 782 |
+
job_id = int(time.time() * 1000 + hash(orig_filename))
|
| 783 |
+
active_jobs[job_id] = {"status": "queued"}
|
| 784 |
+
await upload_queue.put((user_id, chat_id, file_msg, orig_filename, job_id))
|
| 785 |
+
|
| 786 |
+
await query.message.edit_text(
|
| 787 |
+
f"📦 {len(data)} file(s) added to queue.",
|
| 788 |
+
reply_markup=None
|
| 789 |
+
)
|
| 790 |
+
|
| 791 |
+
# ----------- RECEIVING ALL FILE TYPES (direct messages) -----------
|
| 792 |
@app.on_message(
|
| 793 |
filters.document | filters.video | filters.audio | filters.photo |
|
| 794 |
filters.animation | filters.sticker | filters.video_note | filters.voice
|
| 795 |
)
|
| 796 |
async def on_file(_, message):
|
|
|
|
| 797 |
if message.document:
|
| 798 |
filename = message.document.file_name
|
| 799 |
elif message.video:
|
|
|
|
| 805 |
elif message.animation:
|
| 806 |
filename = message.animation.file_name or f"{message.animation.file_unique_id}.mp4"
|
| 807 |
elif message.sticker:
|
|
|
|
| 808 |
if message.sticker.is_animated:
|
| 809 |
filename = f"{message.sticker.file_unique_id}.tgs"
|
| 810 |
elif message.sticker.is_video:
|
|
|
|
| 816 |
elif message.voice:
|
| 817 |
filename = f"{message.voice.file_unique_id}.ogg"
|
| 818 |
else:
|
| 819 |
+
return
|
| 820 |
|
|
|
|
| 821 |
if message.media_group_id and (message.photo or message.video or message.document):
|
| 822 |
group_id = str(message.media_group_id)
|
| 823 |
chat_id = message.chat.id
|