Cxops commited on
Commit
47294fe
·
verified ·
1 Parent(s): af2a226

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -734
app.py CHANGED
@@ -1,745 +1,22 @@
1
  import os
2
- import sys
3
- import json
4
- import math
5
- import time
6
- import base64
7
- import shutil
8
- import asyncio
9
  import logging
10
- import tempfile
11
- from typing import Dict, Optional
12
-
13
- import aiohttp
14
- from aiohttp import web
15
- from cryptography.fernet import Fernet
16
- from cryptography.hazmat.primitives import hashes
17
- from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
18
- from cryptography.hazmat.backends import default_backend
19
-
20
  from pyrogram import Client, filters
21
- from pyrogram.types import (
22
- Message,
23
- CallbackQuery,
24
- InlineKeyboardMarkup,
25
- InlineKeyboardButton,
26
- )
27
- from pyrogram.errors import MessageNotModified
28
- from huggingface_hub import HfApi, upload_file, hf_hub_url
29
- from huggingface_hub.utils import EntryNotFoundError
30
 
31
- # ------------------- Configuration -------------------
 
 
 
32
  BOT_TOKEN = os.environ["BOT_TOKEN"]
33
  API_ID = int(os.environ["API_ID"])
34
  API_HASH = os.environ["API_HASH"]
35
- HF_TOKEN = os.environ["HF_TOKEN"]
36
- SECRET_KEY = os.environ["SECRET_KEY"]
37
- SPACE_URL = os.environ.get("SPACE_URL", "http://localhost:7860") # <-- use public URL
38
-
39
- HF_REPO_ID = "Cxops/Bzxv"
40
- HF_REPO_TYPE = "dataset"
41
- HF_BRANCH = "main"
42
-
43
- MIN_FREE_DISK = 45 * 1024**3
44
- SPLIT_SIZE = 2 * 1024**3 - 10*1024*1024
45
- PROGRESS_INTERVAL = 3
46
- KEEPALIVE_INTERVAL = 300
47
-
48
- # ------------------- Logging -------------------
49
- logging.basicConfig(
50
- level=logging.INFO,
51
- format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
52
- )
53
- logger = logging.getLogger(__name__)
54
-
55
- # ------------------- Encryption -------------------
56
- SALT = b"huggingbot_salt_2025"
57
- kdf = PBKDF2HMAC(
58
- algorithm=hashes.SHA256(),
59
- length=32,
60
- salt=SALT,
61
- iterations=100_000,
62
- backend=default_backend(),
63
- )
64
- key = base64.urlsafe_b64encode(kdf.derive(SECRET_KEY.encode()))
65
- fernet = Fernet(key)
66
-
67
- def encrypt(data: str) -> str:
68
- token = fernet.encrypt(data.encode())
69
- return base64.urlsafe_b64encode(token).decode().rstrip("=")
70
-
71
- def decrypt(token: str) -> str:
72
- pad = 4 - len(token) % 4
73
- if pad != 4:
74
- token += "=" * pad
75
- raw = base64.urlsafe_b64decode(token)
76
- return fernet.decrypt(raw).decode()
77
-
78
- def get_user_folder(user_id: int) -> str:
79
- return encrypt(str(user_id))
80
-
81
- # ------------------- Hugging Face API -------------------
82
- hf_api = HfApi(token=HF_TOKEN)
83
-
84
- def hf_read_json(path: str) -> Optional[dict]:
85
- try:
86
- content = hf_api.read_file(HF_REPO_ID, path, repo_type=HF_REPO_TYPE, revision=HF_BRANCH)
87
- return json.loads(content)
88
- except EntryNotFoundError:
89
- return None
90
- except Exception as e:
91
- logger.error(f"hf_read_json error for {path}: {e}")
92
- return None
93
-
94
- def hf_write_json(path: str, data: dict):
95
- content = json.dumps(data, indent=2).encode("utf-8")
96
- hf_api.upload_file(
97
- path_or_fileobj=content,
98
- path_in_repo=path,
99
- repo_id=HF_REPO_ID,
100
- repo_type=HF_REPO_TYPE,
101
- commit_message=f"update {path}",
102
- )
103
-
104
- def hf_delete_file(path: str):
105
- try:
106
- hf_api.delete_file(path, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE,
107
- commit_message=f"delete {path}")
108
- except Exception as e:
109
- logger.error(f"Failed to delete {path}: {e}")
110
-
111
- def hf_file_size(path: str) -> Optional[int]:
112
- try:
113
- info = hf_api.get_file_metadata(HF_REPO_ID, path, repo_type=HF_REPO_TYPE)
114
- return info.size
115
- except EntryNotFoundError:
116
- return None
117
- except Exception as e:
118
- logger.error(f"hf_file_size error for {path}: {e}")
119
- return None
120
-
121
- def free_disk_gb() -> float:
122
- return shutil.disk_usage("/").free / (1024**3)
123
-
124
- def enough_disk(needed: int = 0) -> bool:
125
- return (shutil.disk_usage("/").free - needed) >= MIN_FREE_DISK
126
-
127
- # ------------------- Bot initialisation -------------------
128
- app_client = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
129
-
130
- # ------------------- Global state -------------------
131
- active_progress: Dict[int, dict] = {}
132
- op_queue = asyncio.Queue()
133
- pending_uploads: Dict[int, dict] = {}
134
-
135
- # ------------------- Progress updater -------------------
136
- async def progress_updater():
137
- while True:
138
- await asyncio.sleep(PROGRESS_INTERVAL)
139
- for msg_id, info in list(active_progress.items()):
140
- try:
141
- chat_id = info["chat_id"]
142
- state = info["state"]
143
- filename = info["filename"]
144
- current = info.get("current", 0)
145
- total = info.get("total", 0)
146
- start_time = info.get("start_time", time.time())
147
- cancel_event = info.get("cancel_event", None)
148
- op_type = info.get("op_type", "")
149
-
150
- elapsed = max(time.time() - start_time, 1)
151
- speed = current / elapsed if current > 0 else 0
152
- if total > 0:
153
- percent = (current / total) * 100
154
- progress_bar = make_progress_bar(percent)
155
- text = (
156
- f"**{op_type}** `{filename}`\n"
157
- f"{progress_bar} {percent:.1f}%\n"
158
- f"📦 {format_bytes(current)} / {format_bytes(total)}\n"
159
- f"⚡ {format_bytes(speed)}/s"
160
- )
161
- else:
162
- text = f"**{op_type}** `{filename}`\n⏳ Processing..."
163
-
164
- keyboard = None
165
- if state in ("downloading_from_tg", "downloading_from_hf", "sending_to_tg"):
166
- keyboard = InlineKeyboardMarkup([
167
- [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_op_{msg_id}")]
168
- ])
169
-
170
- await app_client.edit_message_text(
171
- chat_id, msg_id, text, reply_markup=keyboard
172
- )
173
- except MessageNotModified:
174
- pass
175
- except Exception as e:
176
- logger.error(f"Updater error for msg {msg_id}: {e}")
177
-
178
- def make_progress_bar(percent: float, width: int = 10) -> str:
179
- filled = int(width * percent / 100)
180
- return "█" * filled + "░" * (width - filled)
181
-
182
- def format_bytes(size: int) -> str:
183
- if size == 0:
184
- return "0 B"
185
- units = ["B", "KB", "MB", "GB", "TB"]
186
- i = int(math.floor(math.log(size, 1024)))
187
- p = math.pow(1024, i)
188
- s = round(size / p, 1)
189
- return f"{s} {units[i]}"
190
-
191
- # ------------------- Operation worker -------------------
192
- async def operation_worker():
193
- while True:
194
- op = await op_queue.get()
195
- try:
196
- if op["type"] == "upload":
197
- await handle_upload(op)
198
- elif op["type"] == "download":
199
- await handle_download(op)
200
- except Exception as e:
201
- logger.exception(f"Worker error: {e}")
202
- msg_id = op.get("status_msg_id")
203
- chat_id = op.get("chat_id")
204
- if msg_id and chat_id:
205
- try:
206
- await app_client.edit_message_text(
207
- chat_id, msg_id, f"❌ Error: {e}"
208
- )
209
- except:
210
- pass
211
- if msg_id in active_progress:
212
- del active_progress[msg_id]
213
- finally:
214
- op_queue.task_done()
215
-
216
- # ------------------- Upload / Download handlers (unchanged) -------------------
217
- async def handle_upload(op: dict):
218
- user_id = op["user_id"]
219
- chat_id = op["chat_id"]
220
- file_id = op["file_id"]
221
- file_name = op["file_name"]
222
- msg_id = op["status_msg_id"]
223
- cancel_event = op["cancel_event"]
224
-
225
- active_progress[msg_id] = {
226
- "chat_id": chat_id,
227
- "state": "downloading_from_tg",
228
- "filename": file_name,
229
- "current": 0,
230
- "total": 0,
231
- "start_time": time.time(),
232
- "cancel_event": cancel_event,
233
- "op_type": "Upload",
234
- }
235
-
236
- while not enough_disk():
237
- try:
238
- await app_client.edit_message_text(
239
- chat_id, msg_id,
240
- f"⏳ Waiting for disk space... (free: {free_disk_gb():.1f} GB, need ≥45 GB)",
241
- )
242
- except:
243
- pass
244
- await asyncio.sleep(10)
245
- if cancel_event.is_set():
246
- await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled (disk wait).")
247
- del active_progress[msg_id]
248
- return
249
-
250
- tmp_fd, tmp_path = tempfile.mkstemp(suffix="_" + file_name)
251
- os.close(tmp_fd)
252
- try:
253
- def tg_progress(current, total, msg_id):
254
- info = active_progress.get(msg_id)
255
- if info:
256
- info["current"] = current
257
- info["total"] = total
258
- info["start_time"] = time.time()
259
-
260
- await app_client.download_media(
261
- file_id,
262
- file_name=tmp_path,
263
- progress=tg_progress,
264
- progress_args=(msg_id,),
265
- )
266
- except Exception as e:
267
- logger.error(f"Download failed: {e}")
268
- if os.path.exists(tmp_path):
269
- os.unlink(tmp_path)
270
- await app_client.edit_message_text(chat_id, msg_id, f"❌ Download error: {e}")
271
- del active_progress[msg_id]
272
- return
273
-
274
- if cancel_event.is_set():
275
- if os.path.exists(tmp_path):
276
- os.unlink(tmp_path)
277
- await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
278
- del active_progress[msg_id]
279
- return
280
-
281
- active_progress[msg_id]["state"] = "uploading_to_hf"
282
- active_progress[msg_id]["current"] = 0
283
- active_progress[msg_id]["total"] = 0
284
-
285
- folder = get_user_folder(user_id)
286
- enc_fname = encrypt(file_name)
287
- hf_path = f"{folder}/{enc_fname}"
288
- meta_path = f"{folder}/meta.json"
289
-
290
- def hf_progress(current, total, msg_id):
291
- info = active_progress.get(msg_id)
292
- if info:
293
- info["current"] = current
294
- info["total"] = total
295
- info["start_time"] = time.time()
296
-
297
- try:
298
- upload_file(
299
- path_or_fileobj=tmp_path,
300
- path_in_repo=hf_path,
301
- repo_id=HF_REPO_ID,
302
- repo_type=HF_REPO_TYPE,
303
- token=HF_TOKEN,
304
- progress_callback=hf_progress,
305
- progress_callback_msg_id=msg_id,
306
- )
307
- except Exception as e:
308
- logger.error(f"HF upload failed: {e}")
309
- if os.path.exists(tmp_path):
310
- os.unlink(tmp_path)
311
- await app_client.edit_message_text(chat_id, msg_id, f"❌ Upload error: {e}")
312
- del active_progress[msg_id]
313
- return
314
-
315
- if cancel_event.is_set():
316
- hf_delete_file(hf_path)
317
- meta = hf_read_json(meta_path) or {}
318
- meta.pop(enc_fname, None)
319
- hf_write_json(meta_path, meta)
320
- if os.path.exists(tmp_path):
321
- os.unlink(tmp_path)
322
- await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled & file removed.")
323
- del active_progress[msg_id]
324
- return
325
-
326
- meta = hf_read_json(meta_path) or {}
327
- meta[enc_fname] = file_name
328
- try:
329
- hf_write_json(meta_path, meta)
330
- except Exception as e:
331
- logger.error(f"Meta upload failed: {e}")
332
- await app_client.edit_message_text(chat_id, msg_id, f"✅ File uploaded, but metadata update failed: {e}")
333
- if os.path.exists(tmp_path):
334
- os.unlink(tmp_path)
335
- del active_progress[msg_id]
336
- return
337
-
338
- if os.path.exists(tmp_path):
339
- os.unlink(tmp_path)
340
- await app_client.edit_message_text(chat_id, msg_id, f"✅ Uploaded `{file_name}` successfully.")
341
- del active_progress[msg_id]
342
-
343
- async def handle_download(op: dict):
344
- user_id = op["user_id"]
345
- chat_id = op["chat_id"]
346
- folder = op["folder"]
347
- enc_fname = op["enc_fname"]
348
- orig_name = op["orig_name"]
349
- file_size = op["file_size"]
350
- msg_id = op["status_msg_id"]
351
- cancel_event = op["cancel_event"]
352
-
353
- active_progress[msg_id] = {
354
- "chat_id": chat_id,
355
- "state": "downloading_from_hf",
356
- "filename": orig_name,
357
- "current": 0,
358
- "total": file_size if file_size else 0,
359
- "start_time": time.time(),
360
- "cancel_event": cancel_event,
361
- "op_type": "Download",
362
- }
363
-
364
- url = hf_hub_url(HF_REPO_ID, f"{folder}/{enc_fname}", repo_type=HF_REPO_TYPE, revision=HF_BRANCH)
365
-
366
- if file_size is None or file_size <= SPLIT_SIZE:
367
- tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{orig_name}")
368
- os.close(tmp_fd)
369
- try:
370
- success = await download_from_url(url, tmp_path, msg_id, cancel_event,
371
- file_size, orig_name)
372
- if not success:
373
- return
374
- active_progress[msg_id]["state"] = "sending_to_tg"
375
- active_progress[msg_id]["current"] = 0
376
- active_progress[msg_id]["total"] = os.path.getsize(tmp_path)
377
- await app_client.send_document(
378
- chat_id, tmp_path,
379
- caption=orig_name,
380
- progress=upload_progress,
381
- progress_args=(msg_id,),
382
- )
383
- if cancel_event.is_set():
384
- await app_client.stop_transmission()
385
- await app_client.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
386
- del active_progress[msg_id]
387
- return
388
- await app_client.edit_message_text(chat_id, msg_id, f"✅ Sent `{orig_name}`.")
389
- finally:
390
- if os.path.exists(tmp_path):
391
- os.unlink(tmp_path)
392
- del active_progress[msg_id]
393
- else:
394
- total_parts = math.ceil(file_size / SPLIT_SIZE)
395
- for part_idx in range(total_parts):
396
- if cancel_event.is_set():
397
- await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
398
- del active_progress[msg_id]
399
- return
400
- start = part_idx * SPLIT_SIZE
401
- end = min(start + SPLIT_SIZE - 1, file_size - 1)
402
- part_size = end - start + 1
403
- part_name = f"{orig_name}.part{part_idx+1:03d}"
404
- active_progress[msg_id]["state"] = f"downloading part {part_idx+1}/{total_parts}"
405
- active_progress[msg_id]["current"] = 0
406
- active_progress[msg_id]["total"] = part_size
407
- tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{part_name}")
408
- os.close(tmp_fd)
409
- try:
410
- success = await download_range(url, start, end, tmp_path, msg_id,
411
- cancel_event, part_size, part_name)
412
- if not success:
413
- return
414
- active_progress[msg_id]["state"] = f"sending part {part_idx+1}/{total_parts}"
415
- active_progress[msg_id]["total"] = part_size
416
- await app_client.send_document(
417
- chat_id, tmp_path,
418
- caption=f"{orig_name} - Part {part_idx+1}/{total_parts}",
419
- progress=upload_progress,
420
- progress_args=(msg_id,),
421
- )
422
- if cancel_event.is_set():
423
- await app_client.stop_transmission()
424
- await app_client.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
425
- del active_progress[msg_id]
426
- return
427
- finally:
428
- if os.path.exists(tmp_path):
429
- os.unlink(tmp_path)
430
- await app_client.edit_message_text(chat_id, msg_id, f"✅ All {total_parts} parts sent.")
431
- del active_progress[msg_id]
432
-
433
- def upload_progress(current, total, msg_id):
434
- info = active_progress.get(msg_id)
435
- if info:
436
- info["current"] = current
437
- info["total"] = total
438
- info["start_time"] = time.time()
439
-
440
- async def download_from_url(url: str, dest: str, msg_id: int, cancel_event: asyncio.Event,
441
- total_size: Optional[int], name: str) -> bool:
442
- try:
443
- async with aiohttp.ClientSession() as session:
444
- async with session.get(url) as resp:
445
- if resp.status != 200:
446
- raise Exception(f"HTTP {resp.status}")
447
- total = total_size or int(resp.headers.get("Content-Length", 0))
448
- info = active_progress.get(msg_id)
449
- if info:
450
- info["total"] = total
451
- downloaded = 0
452
- with open(dest, "wb") as f:
453
- async for chunk in resp.content.iter_chunked(64*1024):
454
- if cancel_event.is_set():
455
- return False
456
- f.write(chunk)
457
- downloaded += len(chunk)
458
- if info:
459
- info["current"] = downloaded
460
- info["start_time"] = time.time()
461
- return True
462
- except Exception as e:
463
- logger.error(f"Download error: {e}")
464
- await app_client.edit_message_text(msg_id, f"❌ Download error: {e}")
465
- return False
466
-
467
- async def download_range(url: str, start: int, end: int, dest: str, msg_id: int,
468
- cancel_event: asyncio.Event, size: int, name: str) -> bool:
469
- headers = {"Range": f"bytes={start}-{end}"}
470
- try:
471
- async with aiohttp.ClientSession() as session:
472
- async with session.get(url, headers=headers) as resp:
473
- if resp.status not in (200, 206):
474
- raise Exception(f"HTTP {resp.status}")
475
- total = size
476
- info = active_progress.get(msg_id)
477
- if info:
478
- info["total"] = total
479
- downloaded = 0
480
- with open(dest, "wb") as f:
481
- async for chunk in resp.content.iter_chunked(64*1024):
482
- if cancel_event.is_set():
483
- return False
484
- f.write(chunk)
485
- downloaded += len(chunk)
486
- if info:
487
- info["current"] = downloaded
488
- info["start_time"] = time.time()
489
- return True
490
- except Exception as e:
491
- logger.error(f"Range download error: {e}")
492
- await app_client.edit_message_text(msg_id, f"❌ Download error: {e}")
493
- return False
494
-
495
- # ===================== TELEGRAM HANDLERS =====================
496
-
497
- # 1. Catch‑all debug handler (logs EVERY message)
498
- @app_client.on_message()
499
- async def debug_log_all(client, message: Message):
500
- logger.info(f"RECEIVED MESSAGE from {message.from_user.id}: {message.text or message.caption or '<no text>'} | chat id: {message.chat.id}")
501
-
502
- # 2. Basic /ping command for connectivity test
503
- @app_client.on_message(filters.command("ping"))
504
- async def ping_cmd(client, message: Message):
505
- logger.info(f"/ping from {message.from_user.id}")
506
- await message.reply("🏓 Pong!")
507
-
508
- # 3. /start command
509
- @app_client.on_message(filters.command("start"))
510
- async def start_cmd(client, message: Message):
511
- logger.info(f"/start from {message.from_user.id}")
512
- await message.reply(
513
- "👋 **Welcome to Cloud Storage Bot!**\n\n"
514
- "📤 Send any file to upload it.\n"
515
- "📂 Use /files to see your uploaded files.\n"
516
- "ℹ️ /help for more info.\n"
517
- "🏓 /ping to test."
518
- )
519
-
520
- # 4. /help command
521
- @app_client.on_message(filters.command("help"))
522
- async def help_cmd(client, message: Message):
523
- await message.reply(
524
- "**Commands:**\n"
525
- "/start - Start the bot\n"
526
- "/files - List your files\n"
527
- "/help - Show this help\n"
528
- "/ping - Test bot connectivity\n\n"
529
- "**How to use:**\n"
530
- "1. Send any file (document, video, audio, photo, voice, sticker…).\n"
531
- "2. Click **Upload** to store it, or **Cancel** to discard.\n"
532
- "3. Use /files to browse and download your files back.\n\n"
533
- "Files > 2GB are split automatically."
534
- )
535
-
536
- # 5. /files command
537
- @app_client.on_message(filters.command("files"))
538
- async def list_files(client, message: Message):
539
- user_id = message.from_user.id
540
- folder = get_user_folder(user_id)
541
- meta_path = f"{folder}/meta.json"
542
- meta = hf_read_json(meta_path)
543
- if not meta or len(meta) == 0:
544
- await message.reply("📭 You haven't uploaded any files yet.")
545
- return
546
-
547
- keyboard = []
548
- for enc_name, orig_name in meta.items():
549
- keyboard.append([InlineKeyboardButton(orig_name, callback_data=f"dl_{enc_name}")])
550
- keyboard.append([InlineKeyboardButton("🔄 Refresh", callback_data="files_refresh")])
551
- await message.reply("📂 Your files:", reply_markup=InlineKeyboardMarkup(keyboard))
552
-
553
- @app_client.on_callback_query(filters.regex(r"^files_refresh$"))
554
- async def refresh_files(client, query: CallbackQuery):
555
- await query.answer("Refreshing…")
556
- await list_files(client, query.message)
557
- await query.message.delete()
558
-
559
- @app_client.on_callback_query(filters.regex(r"^dl_(.+)"))
560
- async def download_file_cb(client, query: CallbackQuery):
561
- enc_fname = query.data.split("_", 1)[1]
562
- user_id = query.from_user.id
563
- folder = get_user_folder(user_id)
564
- meta = hf_read_json(f"{folder}/meta.json")
565
- if not meta or enc_fname not in meta:
566
- await query.answer("File not found!", show_alert=True)
567
- return
568
- orig_name = meta[enc_fname]
569
- file_size = hf_file_size(f"{folder}/{enc_fname}")
570
- if file_size is None:
571
- await query.answer("Cannot read file size.", show_alert=True)
572
- return
573
-
574
- await query.answer("Starting download…")
575
- status_msg = await client.send_message(
576
- query.message.chat.id, f"⏳ Preparing download: `{orig_name}`…"
577
- )
578
- cancel_event = asyncio.Event()
579
- active_progress[status_msg.id] = {
580
- "chat_id": status_msg.chat.id,
581
- "state": "starting",
582
- "filename": orig_name,
583
- "current": 0,
584
- "total": 0,
585
- "start_time": time.time(),
586
- "cancel_event": cancel_event,
587
- "op_type": "Download",
588
- }
589
- await op_queue.put({
590
- "type": "download",
591
- "user_id": user_id,
592
- "chat_id": status_msg.chat.id,
593
- "folder": folder,
594
- "enc_fname": enc_fname,
595
- "orig_name": orig_name,
596
- "file_size": file_size,
597
- "status_msg_id": status_msg.id,
598
- "cancel_event": cancel_event,
599
- })
600
-
601
- @app_client.on_callback_query(filters.regex(r"^cancel_op_(\d+)$"))
602
- async def cancel_operation(client, query: CallbackQuery):
603
- msg_id = int(query.data.split("_")[2])
604
- info = active_progress.get(msg_id)
605
- if info and "cancel_event" in info:
606
- info["cancel_event"].set()
607
- await query.answer("Cancelling…")
608
- else:
609
- await query.answer("Nothing to cancel.", show_alert=True)
610
-
611
- # ===================== MEDIA HANDLER (no private filter, for testing) =====================
612
- @app_client.on_message(filters.media)
613
- async def media_handler(client, message: Message):
614
- user_id = message.from_user.id
615
- logger.info(f"Media from {user_id}, type={message.media}")
616
-
617
- file_id = None
618
- file_name = "file"
619
- file_size = 0
620
-
621
- if message.document:
622
- file_id = message.document.file_id
623
- file_name = message.document.file_name or "document"
624
- file_size = message.document.file_size
625
- elif message.video:
626
- file_id = message.video.file_id
627
- file_name = message.video.file_name or "video.mp4"
628
- file_size = message.video.file_size
629
- elif message.audio:
630
- file_id = message.audio.file_id
631
- file_name = message.audio.file_name or "audio.mp3"
632
- file_size = message.audio.file_size
633
- elif message.photo:
634
- file_id = message.photo.file_id
635
- file_name = f"photo_{message.photo.file_unique_id}.jpg"
636
- file_size = message.photo.file_size or 0
637
- elif message.voice:
638
- file_id = message.voice.file_id
639
- file_name = f"voice_{message.voice.file_unique_id}.ogg"
640
- file_size = message.voice.file_size
641
- elif message.video_note:
642
- file_id = message.video_note.file_id
643
- file_name = f"video_note_{message.video_note.file_unique_id}.mp4"
644
- file_size = message.video_note.file_size
645
- elif message.sticker:
646
- file_id = message.sticker.file_id
647
- file_name = f"sticker_{message.sticker.file_unique_id}.webp"
648
- file_size = message.sticker.file_size
649
- else:
650
- file_id = getattr(message, message.media.value, None)
651
- if file_id:
652
- file_name = f"media_{message.id}"
653
- file_size = 0
654
-
655
- if not file_id:
656
- await message.reply("❌ Could not extract file.")
657
- return
658
-
659
- prompt = await message.reply(
660
- f"📁 `{file_name}` ({format_bytes(file_size) if file_size else 'unknown size'})\n"
661
- "Do you want to upload this file?",
662
- reply_markup=InlineKeyboardMarkup([
663
- [InlineKeyboardButton("✅ Upload", callback_data=f"upload_{message.id}")],
664
- [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_prompt_{message.id}")],
665
- ]),
666
- quote=True,
667
- )
668
- pending_uploads[prompt.id] = {
669
- "file_id": file_id,
670
- "file_name": file_name,
671
- "file_size": file_size,
672
- "user_id": user_id,
673
- }
674
-
675
- @app_client.on_callback_query(filters.regex(r"^upload_(\d+)$"))
676
- async def upload_confirm(client, query: CallbackQuery):
677
- prompt_msg = query.message
678
- info = pending_uploads.pop(prompt_msg.id, None)
679
- if not info:
680
- await query.answer("Session expired, please send the file again.", show_alert=True)
681
- return
682
-
683
- await query.answer()
684
- await prompt_msg.delete()
685
-
686
- status_msg = await client.send_message(
687
- prompt_msg.chat.id, f"⏳ Preparing upload: `{info['file_name']}`…"
688
- )
689
- cancel_event = asyncio.Event()
690
- await op_queue.put({
691
- "type": "upload",
692
- "user_id": info["user_id"],
693
- "chat_id": prompt_msg.chat.id,
694
- "file_id": info["file_id"],
695
- "file_name": info["file_name"],
696
- "status_msg_id": status_msg.id,
697
- "cancel_event": cancel_event,
698
- })
699
-
700
- @app_client.on_callback_query(filters.regex(r"^cancel_prompt_(\d+)$"))
701
- async def cancel_prompt(client, query: CallbackQuery):
702
- prompt_msg = query.message
703
- pending_uploads.pop(prompt_msg.id, None)
704
- await query.answer("Cancelled.")
705
- await prompt_msg.delete()
706
-
707
- # ------------------- Keep‑alive (pings SPACE_URL) -------------------
708
- async def keep_alive_server():
709
- async def handle(request):
710
- return web.Response(text="Bot is alive")
711
- app = web.Application()
712
- app.router.add_get("/", handle)
713
- runner = web.AppRunner(app)
714
- await runner.setup()
715
- site = web.TCPSite(runner, "0.0.0.0", 7860)
716
- await site.start()
717
- logger.info(f"Keep‑alive server started on port 7860, external pings will go to {SPACE_URL}")
718
-
719
- async def self_ping():
720
- await asyncio.sleep(10)
721
- while True:
722
- try:
723
- async with aiohttp.ClientSession() as session:
724
- async with session.get(SPACE_URL) as resp:
725
- logger.info(f"Self‑ping {SPACE_URL}: {resp.status}")
726
- except Exception as e:
727
- logger.error(f"Self‑ping failed: {e}")
728
- await asyncio.sleep(KEEPALIVE_INTERVAL)
729
 
730
- asyncio.create_task(self_ping())
731
 
732
- # ------------------- Main -------------------
733
- async def main():
734
- await keep_alive_server()
735
- await app_client.start()
736
- logger.info("Bot started, waiting for messages...")
737
- asyncio.create_task(operation_worker())
738
- asyncio.create_task(progress_updater())
739
- await asyncio.Event().wait()
740
 
741
  if __name__ == "__main__":
742
- try:
743
- asyncio.run(main())
744
- except KeyboardInterrupt:
745
- logger.info("Bot stopped.")
 
1
  import os
 
 
 
 
 
 
 
2
  import logging
 
 
 
 
 
 
 
 
 
 
3
  from pyrogram import Client, filters
 
 
 
 
 
 
 
 
 
4
 
5
+ # Suppress Pyrogram’s own spammy logs
6
+ logging.basicConfig(level=logging.WARNING)
7
+ log = logging.getLogger(__name__)
8
+
9
  BOT_TOKEN = os.environ["BOT_TOKEN"]
10
  API_ID = int(os.environ["API_ID"])
11
  API_HASH = os.environ["API_HASH"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ app = Client("echo_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
14
 
15
+ @app.on_message()
16
+ async def echo(client, msg):
17
+ log.warning(f"Message from {msg.from_user.id}: {msg.text}")
18
+ await msg.reply(f"Echo: {msg.text}")
 
 
 
 
19
 
20
  if __name__ == "__main__":
21
+ log.warning("Starting echo bot...")
22
+ app.run()