nvd commited on
Update main.py
Browse files
main.py
CHANGED
|
@@ -3,6 +3,7 @@ import asyncio
|
|
| 3 |
import tempfile
|
| 4 |
import zipfile
|
| 5 |
import httpx
|
|
|
|
| 6 |
from telethon import TelegramClient, events
|
| 7 |
from telethon.sessions import StringSession
|
| 8 |
from fastapi import FastAPI
|
|
@@ -26,29 +27,51 @@ TARGET_CHANNELS = list(set(env_channels + ["iu39f"]))
|
|
| 26 |
|
| 27 |
CHUNK_SIZE = 19 * 1024 * 1024 # 19 MB
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
# --- 2. TELEGRAM CLIENT ---
|
| 30 |
tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
|
| 31 |
|
| 32 |
-
# --- 3. BALE HELPERS (
|
| 33 |
-
|
|
|
|
| 34 |
if not BALE_BOT_TOKEN:
|
| 35 |
return False
|
| 36 |
url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
|
| 37 |
payload = {"chat_id": BALE_CHAT_ID, "text": text}
|
| 38 |
if parse_mode:
|
| 39 |
payload["parse_mode"] = parse_mode
|
| 40 |
-
|
|
|
|
| 41 |
try:
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
except Exception as e:
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
| 49 |
return False
|
|
|
|
|
|
|
| 50 |
|
| 51 |
-
async def send_media_to_bale(file_path, caption, media_type, parse_mode=None):
|
| 52 |
if not BALE_BOT_TOKEN:
|
| 53 |
return False
|
| 54 |
|
|
@@ -71,23 +94,36 @@ async def send_media_to_bale(file_path, caption, media_type, parse_mode=None):
|
|
| 71 |
data["parse_mode"] = parse_mode
|
| 72 |
|
| 73 |
field_name = media_type if media_type in endpoint_map else "document"
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
async def send_log_to_bale(message):
|
| 93 |
if not BALE_BOT_TOKEN or not BALE_LOG_CHAT_ID:
|
|
@@ -100,8 +136,17 @@ async def send_log_to_bale(message):
|
|
| 100 |
except Exception:
|
| 101 |
pass
|
| 102 |
|
| 103 |
-
# --- 4.
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
if not message.media:
|
| 106 |
return None
|
| 107 |
try:
|
|
@@ -130,25 +175,22 @@ async def download_media(message):
|
|
| 130 |
elif message.video_note:
|
| 131 |
suffix = ".mp4"
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
return path
|
| 137 |
except Exception as e:
|
| 138 |
await send_log_to_bale(f"Media download error: {e}")
|
| 139 |
return None
|
| 140 |
|
| 141 |
-
def
|
| 142 |
-
if zip_path is None:
|
| 143 |
-
zip_path = file_path + ".zip"
|
| 144 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 145 |
zf.write(file_path, arcname=os.path.basename(file_path))
|
| 146 |
return zip_path
|
| 147 |
|
| 148 |
-
async def zip_file(file_path, zip_path
|
| 149 |
-
return await asyncio.to_thread(
|
| 150 |
|
| 151 |
-
def
|
| 152 |
chunk_paths = []
|
| 153 |
base = file_path + ".part"
|
| 154 |
with open(file_path, "rb") as f:
|
|
@@ -165,7 +207,7 @@ def _split_file_sync(file_path, chunk_size=CHUNK_SIZE):
|
|
| 165 |
return chunk_paths
|
| 166 |
|
| 167 |
async def split_file(file_path, chunk_size=CHUNK_SIZE):
|
| 168 |
-
return await asyncio.to_thread(
|
| 169 |
|
| 170 |
def detect_media_type(event):
|
| 171 |
if event.photo:
|
|
@@ -185,10 +227,8 @@ def detect_media_type(event):
|
|
| 185 |
return None
|
| 186 |
|
| 187 |
def get_media_size(event):
|
| 188 |
-
"""Return the file size in bytes from the message object, or None."""
|
| 189 |
try:
|
| 190 |
if event.photo:
|
| 191 |
-
# photos have a list of sizes, largest is last
|
| 192 |
return event.photo.sizes[-1].size
|
| 193 |
if event.video:
|
| 194 |
return event.video.size
|
|
@@ -199,7 +239,6 @@ def get_media_size(event):
|
|
| 199 |
if event.video_note:
|
| 200 |
return event.video_note.size
|
| 201 |
if event.sticker:
|
| 202 |
-
# sticker is a Document
|
| 203 |
return event.sticker.size if hasattr(event.sticker, 'size') else None
|
| 204 |
if event.document:
|
| 205 |
return event.document.size
|
|
@@ -223,15 +262,14 @@ def build_caption(event, username):
|
|
| 223 |
parts.append(f'<a href="{msg_link}">📎 Open in Telegram</a>')
|
| 224 |
return "\n\n".join(parts)
|
| 225 |
|
| 226 |
-
async def handle_large_document(event, media_path, final_caption):
|
| 227 |
-
"""Zip and chunk any large file, then send all parts with captions."""
|
| 228 |
file_size = os.path.getsize(media_path) if os.path.exists(media_path) else 0
|
| 229 |
await send_log_to_bale(
|
| 230 |
-
f"Processing large file: {os.path.basename(media_path)}, "
|
| 231 |
-
f"size={file_size/(1024*1024):.1f} MB"
|
| 232 |
)
|
| 233 |
|
| 234 |
-
zip_path =
|
|
|
|
| 235 |
zip_size = os.path.getsize(zip_path)
|
| 236 |
|
| 237 |
if zip_size > CHUNK_SIZE:
|
|
@@ -242,20 +280,12 @@ async def handle_large_document(event, media_path, final_caption):
|
|
| 242 |
chunk_size_mb = os.path.getsize(chunk_path) / (1024 * 1024)
|
| 243 |
part_caption = f"{final_caption}\n📦 Part {idx}/{total}"
|
| 244 |
|
| 245 |
-
# Try HTML, fallback to plain text
|
| 246 |
success = await send_media_to_bale(chunk_path, part_caption, "document", parse_mode="HTML")
|
| 247 |
if not success:
|
| 248 |
-
|
| 249 |
-
await asyncio.sleep(2)
|
| 250 |
success = await send_media_to_bale(chunk_path, part_caption, "document", parse_mode=None)
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
os.unlink(chunk_path)
|
| 254 |
-
except Exception:
|
| 255 |
-
pass
|
| 256 |
-
|
| 257 |
-
if not success:
|
| 258 |
-
await send_log_to_bale(f"❌ Chunk {idx}/{total} FAILED")
|
| 259 |
else:
|
| 260 |
await send_log_to_bale(f"✅ Chunk {idx}/{total} sent ({chunk_size_mb:.1f} MB)")
|
| 261 |
await asyncio.sleep(1.5)
|
|
@@ -263,17 +293,7 @@ async def handle_large_document(event, media_path, final_caption):
|
|
| 263 |
await send_log_to_bale(f"ZIP size {zip_size/(1024*1024):.1f} MB, sending whole")
|
| 264 |
await send_media_to_bale(zip_path, final_caption, "document", parse_mode="HTML")
|
| 265 |
|
| 266 |
-
|
| 267 |
-
try:
|
| 268 |
-
os.unlink(media_path)
|
| 269 |
-
except Exception:
|
| 270 |
-
pass
|
| 271 |
-
try:
|
| 272 |
-
os.unlink(zip_path)
|
| 273 |
-
except Exception:
|
| 274 |
-
pass
|
| 275 |
-
|
| 276 |
-
# --- 6. TELEGRAM EVENT HANDLER (updated) ---
|
| 277 |
@tg_client.on(events.NewMessage)
|
| 278 |
async def handler(event):
|
| 279 |
if not event.is_channel:
|
|
@@ -289,33 +309,34 @@ async def handler(event):
|
|
| 289 |
caption_body = build_caption(event, username)
|
| 290 |
final_caption = header + caption_body
|
| 291 |
|
| 292 |
-
# Check if any media is attached and its size
|
| 293 |
media_type = detect_media_type(event)
|
| 294 |
-
if media_type:
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
# Too large for direct sending → download, zip, split, send
|
| 298 |
-
await send_log_to_bale(
|
| 299 |
-
f"Large {media_type} from @{username}: {media_size/(1024*1024):.1f} MB"
|
| 300 |
-
)
|
| 301 |
-
media_path = await download_media(event)
|
| 302 |
-
if media_path:
|
| 303 |
-
await handle_large_document(event, media_path, final_caption)
|
| 304 |
-
return # done with this message
|
| 305 |
-
|
| 306 |
-
# Small media (or size unknown): send directly
|
| 307 |
-
media_path = await download_media(event)
|
| 308 |
-
if media_path:
|
| 309 |
-
success = await send_media_to_bale(media_path, final_caption, media_type, parse_mode="HTML")
|
| 310 |
-
if not success:
|
| 311 |
-
await send_media_to_bale(media_path, final_caption, media_type)
|
| 312 |
-
os.unlink(media_path)
|
| 313 |
return
|
| 314 |
|
| 315 |
-
#
|
| 316 |
-
|
| 317 |
-
if
|
| 318 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
|
| 320 |
except Exception as e:
|
| 321 |
await send_log_to_bale(f"Handler Error (@{username if 'username' in dir() else '?'}): {e}")
|
|
|
|
| 3 |
import tempfile
|
| 4 |
import zipfile
|
| 5 |
import httpx
|
| 6 |
+
import shutil
|
| 7 |
from telethon import TelegramClient, events
|
| 8 |
from telethon.sessions import StringSession
|
| 9 |
from fastapi import FastAPI
|
|
|
|
| 27 |
|
| 28 |
CHUNK_SIZE = 19 * 1024 * 1024 # 19 MB
|
| 29 |
|
| 30 |
+
# Limit concurrent large file processing to avoid tmpfs overflow
|
| 31 |
+
LARGE_FILE_SEMAPHORE = asyncio.Semaphore(2)
|
| 32 |
+
|
| 33 |
+
# Limit concurrent Bale API calls to avoid rate limits
|
| 34 |
+
BALE_API_SEMAPHORE = asyncio.Semaphore(3)
|
| 35 |
+
|
| 36 |
# --- 2. TELEGRAM CLIENT ---
|
| 37 |
tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
|
| 38 |
|
| 39 |
+
# --- 3. BALE HELPERS (with retries) ---
|
| 40 |
+
|
| 41 |
+
async def send_text_to_bale(text, parse_mode=None, retries=3):
|
| 42 |
if not BALE_BOT_TOKEN:
|
| 43 |
return False
|
| 44 |
url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
|
| 45 |
payload = {"chat_id": BALE_CHAT_ID, "text": text}
|
| 46 |
if parse_mode:
|
| 47 |
payload["parse_mode"] = parse_mode
|
| 48 |
+
|
| 49 |
+
for attempt in range(1, retries + 1):
|
| 50 |
try:
|
| 51 |
+
async with BALE_API_SEMAPHORE:
|
| 52 |
+
async with httpx.AsyncClient() as client:
|
| 53 |
+
resp = await client.post(url, json=payload, timeout=10)
|
| 54 |
+
if resp.status_code == 200:
|
| 55 |
+
return True
|
| 56 |
+
else:
|
| 57 |
+
if attempt < retries:
|
| 58 |
+
await asyncio.sleep(2 ** (attempt - 1)) # 1,2,4 sec
|
| 59 |
+
continue
|
| 60 |
+
await send_log_to_bale(
|
| 61 |
+
f"send_text_to_bale failed after {retries} attempts: "
|
| 62 |
+
f"{resp.status_code} {resp.text[:200]}"
|
| 63 |
+
)
|
| 64 |
+
return False
|
| 65 |
except Exception as e:
|
| 66 |
+
if attempt < retries:
|
| 67 |
+
await asyncio.sleep(2 ** (attempt - 1))
|
| 68 |
+
continue
|
| 69 |
+
await send_log_to_bale(f"send_text_to_bale exception after {retries} attempts: {e}")
|
| 70 |
return False
|
| 71 |
+
return False
|
| 72 |
+
|
| 73 |
|
| 74 |
+
async def send_media_to_bale(file_path, caption, media_type, parse_mode=None, retries=3):
|
| 75 |
if not BALE_BOT_TOKEN:
|
| 76 |
return False
|
| 77 |
|
|
|
|
| 94 |
data["parse_mode"] = parse_mode
|
| 95 |
|
| 96 |
field_name = media_type if media_type in endpoint_map else "document"
|
| 97 |
+
|
| 98 |
+
for attempt in range(1, retries + 1):
|
| 99 |
+
try:
|
| 100 |
+
with open(file_path, "rb") as f:
|
| 101 |
+
files = {field_name: f}
|
| 102 |
+
async with BALE_API_SEMAPHORE:
|
| 103 |
+
async with httpx.AsyncClient() as client:
|
| 104 |
+
resp = await client.post(url, data=data, files=files, timeout=30)
|
| 105 |
+
if resp.status_code == 200:
|
| 106 |
+
return True
|
| 107 |
+
else:
|
| 108 |
+
if attempt < retries:
|
| 109 |
+
await asyncio.sleep(2 ** (attempt - 1))
|
| 110 |
+
continue
|
| 111 |
+
await send_log_to_bale(
|
| 112 |
+
f"send_media_to_bale failed after {retries} attempts ({media_type}): "
|
| 113 |
+
f"{resp.status_code} {resp.text[:300]}\nFile: {os.path.basename(file_path)}"
|
| 114 |
+
)
|
| 115 |
+
return False
|
| 116 |
+
except Exception as e:
|
| 117 |
+
if attempt < retries:
|
| 118 |
+
await asyncio.sleep(2 ** (attempt - 1))
|
| 119 |
+
continue
|
| 120 |
+
await send_log_to_bale(
|
| 121 |
+
f"send_media_to_bale exception after {retries} attempts ({media_type}): {e}\n"
|
| 122 |
+
f"File: {os.path.basename(file_path)}"
|
| 123 |
+
)
|
| 124 |
+
return False
|
| 125 |
+
return False
|
| 126 |
+
|
| 127 |
|
| 128 |
async def send_log_to_bale(message):
|
| 129 |
if not BALE_BOT_TOKEN or not BALE_LOG_CHAT_ID:
|
|
|
|
| 136 |
except Exception:
|
| 137 |
pass
|
| 138 |
|
| 139 |
+
# --- 4. SAFE TEMP DIRECTORY HELPERS ---
|
| 140 |
+
def create_temp_dir():
|
| 141 |
+
return tempfile.mkdtemp(prefix="tg2bale_")
|
| 142 |
+
|
| 143 |
+
def cleanup_temp_dir(temp_dir):
|
| 144 |
+
try:
|
| 145 |
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 146 |
+
except Exception:
|
| 147 |
+
pass
|
| 148 |
+
|
| 149 |
+
async def download_media(message, temp_dir):
|
| 150 |
if not message.media:
|
| 151 |
return None
|
| 152 |
try:
|
|
|
|
| 175 |
elif message.video_note:
|
| 176 |
suffix = ".mp4"
|
| 177 |
|
| 178 |
+
file_path = os.path.join(temp_dir, f"media{suffix}")
|
| 179 |
+
await message.download_media(file=file_path)
|
| 180 |
+
return file_path
|
|
|
|
| 181 |
except Exception as e:
|
| 182 |
await send_log_to_bale(f"Media download error: {e}")
|
| 183 |
return None
|
| 184 |
|
| 185 |
+
def zip_file_sync(file_path, zip_path):
|
|
|
|
|
|
|
| 186 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 187 |
zf.write(file_path, arcname=os.path.basename(file_path))
|
| 188 |
return zip_path
|
| 189 |
|
| 190 |
+
async def zip_file(file_path, zip_path):
|
| 191 |
+
return await asyncio.to_thread(zip_file_sync, file_path, zip_path)
|
| 192 |
|
| 193 |
+
def split_file_sync(file_path, chunk_size=CHUNK_SIZE):
|
| 194 |
chunk_paths = []
|
| 195 |
base = file_path + ".part"
|
| 196 |
with open(file_path, "rb") as f:
|
|
|
|
| 207 |
return chunk_paths
|
| 208 |
|
| 209 |
async def split_file(file_path, chunk_size=CHUNK_SIZE):
|
| 210 |
+
return await asyncio.to_thread(split_file_sync, file_path, chunk_size)
|
| 211 |
|
| 212 |
def detect_media_type(event):
|
| 213 |
if event.photo:
|
|
|
|
| 227 |
return None
|
| 228 |
|
| 229 |
def get_media_size(event):
|
|
|
|
| 230 |
try:
|
| 231 |
if event.photo:
|
|
|
|
| 232 |
return event.photo.sizes[-1].size
|
| 233 |
if event.video:
|
| 234 |
return event.video.size
|
|
|
|
| 239 |
if event.video_note:
|
| 240 |
return event.video_note.size
|
| 241 |
if event.sticker:
|
|
|
|
| 242 |
return event.sticker.size if hasattr(event.sticker, 'size') else None
|
| 243 |
if event.document:
|
| 244 |
return event.document.size
|
|
|
|
| 262 |
parts.append(f'<a href="{msg_link}">📎 Open in Telegram</a>')
|
| 263 |
return "\n\n".join(parts)
|
| 264 |
|
| 265 |
+
async def handle_large_document(event, media_path, final_caption, temp_dir):
|
|
|
|
| 266 |
file_size = os.path.getsize(media_path) if os.path.exists(media_path) else 0
|
| 267 |
await send_log_to_bale(
|
| 268 |
+
f"Processing large file: {os.path.basename(media_path)}, size={file_size/(1024*1024):.1f} MB"
|
|
|
|
| 269 |
)
|
| 270 |
|
| 271 |
+
zip_path = os.path.join(temp_dir, "media.zip")
|
| 272 |
+
await zip_file(media_path, zip_path)
|
| 273 |
zip_size = os.path.getsize(zip_path)
|
| 274 |
|
| 275 |
if zip_size > CHUNK_SIZE:
|
|
|
|
| 280 |
chunk_size_mb = os.path.getsize(chunk_path) / (1024 * 1024)
|
| 281 |
part_caption = f"{final_caption}\n📦 Part {idx}/{total}"
|
| 282 |
|
|
|
|
| 283 |
success = await send_media_to_bale(chunk_path, part_caption, "document", parse_mode="HTML")
|
| 284 |
if not success:
|
| 285 |
+
# Already retried inside send_media_to_bale; if still fails, try plain text
|
|
|
|
| 286 |
success = await send_media_to_bale(chunk_path, part_caption, "document", parse_mode=None)
|
| 287 |
+
if not success:
|
| 288 |
+
await send_log_to_bale(f"❌ Chunk {idx}/{total} FAILED permanently")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
else:
|
| 290 |
await send_log_to_bale(f"✅ Chunk {idx}/{total} sent ({chunk_size_mb:.1f} MB)")
|
| 291 |
await asyncio.sleep(1.5)
|
|
|
|
| 293 |
await send_log_to_bale(f"ZIP size {zip_size/(1024*1024):.1f} MB, sending whole")
|
| 294 |
await send_media_to_bale(zip_path, final_caption, "document", parse_mode="HTML")
|
| 295 |
|
| 296 |
+
# --- 6. TELEGRAM EVENT HANDLER ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
@tg_client.on(events.NewMessage)
|
| 298 |
async def handler(event):
|
| 299 |
if not event.is_channel:
|
|
|
|
| 309 |
caption_body = build_caption(event, username)
|
| 310 |
final_caption = header + caption_body
|
| 311 |
|
|
|
|
| 312 |
media_type = detect_media_type(event)
|
| 313 |
+
if not media_type:
|
| 314 |
+
# Plain text
|
| 315 |
+
await send_text_to_bale(final_caption, parse_mode="HTML")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
return
|
| 317 |
|
| 318 |
+
# Media message (small or large)
|
| 319 |
+
media_size = get_media_size(event)
|
| 320 |
+
if media_size and media_size > CHUNK_SIZE:
|
| 321 |
+
async with LARGE_FILE_SEMAPHORE:
|
| 322 |
+
temp_dir = create_temp_dir()
|
| 323 |
+
try:
|
| 324 |
+
await send_log_to_bale(f"Large {media_type} from @{username}: {media_size/(1024*1024):.1f} MB")
|
| 325 |
+
media_path = await download_media(event, temp_dir)
|
| 326 |
+
if media_path:
|
| 327 |
+
await handle_large_document(event, media_path, final_caption, temp_dir)
|
| 328 |
+
finally:
|
| 329 |
+
cleanup_temp_dir(temp_dir)
|
| 330 |
+
return
|
| 331 |
+
|
| 332 |
+
# Small media
|
| 333 |
+
temp_dir = create_temp_dir()
|
| 334 |
+
try:
|
| 335 |
+
media_path = await download_media(event, temp_dir)
|
| 336 |
+
if media_path:
|
| 337 |
+
await send_media_to_bale(media_path, final_caption, media_type, parse_mode="HTML")
|
| 338 |
+
finally:
|
| 339 |
+
cleanup_temp_dir(temp_dir)
|
| 340 |
|
| 341 |
except Exception as e:
|
| 342 |
await send_log_to_bale(f"Handler Error (@{username if 'username' in dir() else '?'}): {e}")
|