File size: 21,416 Bytes
d0c4cfb
e3bce8f
 
d0c4cfb
e3bce8f
d0c4cfb
e3bce8f
582a79f
e3bce8f
d0c4cfb
e3bce8f
 
 
 
 
 
 
d0c4cfb
e3bce8f
 
 
 
 
 
 
 
 
 
 
b0e0338
e3bce8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeabd48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3bce8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
582a79f
e3bce8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2afcfa
e3bce8f
 
 
 
 
e2afcfa
e3bce8f
 
e2afcfa
 
e3bce8f
 
 
 
e2afcfa
e3bce8f
 
 
 
 
e2afcfa
e3bce8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeabd48
e3bce8f
 
 
 
eeabd48
e3bce8f
 
 
 
 
 
 
 
 
eeabd48
e3bce8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeabd48
e3bce8f
 
 
 
 
 
 
 
 
 
 
eeabd48
 
 
 
 
 
 
 
 
 
 
 
 
 
e3bce8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeabd48
 
e3bce8f
eeabd48
 
 
e3bce8f
eeabd48
 
 
 
 
 
 
 
 
e3bce8f
 
eeabd48
 
e3bce8f
 
 
 
 
 
 
 
eeabd48
e3bce8f
 
eeabd48
 
 
 
 
 
 
e3bce8f
eeabd48
 
 
 
 
 
e3bce8f
eeabd48
 
 
 
 
 
 
 
 
 
e3bce8f
 
 
 
 
 
 
 
 
 
eeabd48
e3bce8f
 
 
 
 
 
eeabd48
e3bce8f
 
 
 
b0e0338
 
 
 
 
 
 
 
eeabd48
e3bce8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeabd48
e3bce8f
 
 
 
 
 
eeabd48
 
 
 
 
 
 
 
 
 
 
 
 
 
e3bce8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0c4cfb
64ced8b
e3bce8f
64ced8b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
import os
import time
import asyncio
import logging
import tempfile
import aiohttp
from collections import defaultdict
from pyrogram import Client, filters
from pyrogram.types import Message

# โ”€โ”€โ”€ ุฅุนุฏุงุฏ ุงู„ุณุฌู„ุงุช โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(message)s",
    datefmt="%H:%M:%S",
)
logger = logging.getLogger(__name__)

# โ”€โ”€โ”€ ุฅู†ุดุงุก ุงู„ุจูˆุช โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
app = Client(
    "gofile_bot",
    api_id=int(os.environ.get("API_ID", "0")),
    api_hash=os.environ.get("API_HASH", ""),
    bot_token=os.environ.get("BOT_TOKEN", ""),
)

# โ”€โ”€โ”€ ุซูˆุงุจุช โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
PROGRESS_UPDATE_INTERVAL = 3   # ุซุงู†ูŠุฉ ุจูŠู† ูƒู„ ุชุญุฏูŠุซ ู„ุฑุณุงู„ุฉ ุงู„ุชู‚ุฏู…
FILE_COLLECT_DELAY       = 1.5 # ุซุงู†ูŠุฉ ุงู†ุชุธุงุฑ ู„ุชุฌู…ูŠุน ู…ู„ูุงุช ู…ุชุนุฏุฏุฉ
SERVER_TEST_SIZE         = 300 # ุญุฌู… ู…ู„ู ุงู„ุงุฎุชุจุงุฑ ุจุงู„ูƒูŠู„ูˆุจุงูŠุช (ู…ูƒุจู‘ุฑ ู„ู‚ูŠุงุณ ุฃุฏู‚)
CHUNK_SIZE               = 512 * 1024  # 512 KB ู„ูƒู„ ู‚ุทุนุฉ ุฑูุน

# โ”€โ”€โ”€ ู‚ูˆุงู…ูŠุณ ู„ุฅุฏุงุฑุฉ ุญุงู„ุฉ ุงู„ู…ุณุชุฎุฏู…ูŠู† โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
pending_files: dict[int, list[Message]] = defaultdict(list)
pending_tasks: dict[int, asyncio.Task]  = {}
pending_locks: dict[int, asyncio.Lock]  = defaultdict(asyncio.Lock)


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  ุฏูˆุงู„ ุงู„ู…ุณุงุนุฏุฉ
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

def fmt_size(b: int) -> str:
    """ุชุญูˆูŠู„ ุงู„ุจุงูŠุช ุฅู„ู‰ ู†ุต ู…ู‚ุฑูˆุก"""
    if b < 1024:
        return f"{b} B"
    if b < 1024 ** 2:
        return f"{b / 1024:.1f} KB"
    if b < 1024 ** 3:
        return f"{b / 1024**2:.2f} MB"
    return f"{b / 1024**3:.2f} GB"


def fmt_speed(bps: float) -> str:
    return fmt_size(int(bps)) + "/s"


def fmt_eta(secs: float) -> str:
    secs = int(secs)
    if secs < 60:
        return f"{secs}ุซ"
    if secs < 3600:
        return f"{secs // 60}ุฏ {secs % 60}ุซ"
    return f"{secs // 3600}ุณ {(secs % 3600) // 60}ุฏ"


def progress_bar(current: int, total: int, width: int = 12) -> str:
    if total <= 0:
        return "โ–‘" * width + "  โ€”%"
    pct   = current / total
    filled = int(width * pct)
    bar   = "โ–ˆ" * filled + "โ–‘" * (width - filled)
    return f"[{bar}] {pct * 100:.1f}%"


def safe_md(text: str) -> str:
    """ูŠู…ู†ุน ูƒุณุฑ ุชู†ุณูŠู‚ Markdown ุฅุฐุง ุงุญุชูˆู‰ ุงู„ู†ุต (ู…ุซู„ ุงุณู… ู…ู„ู) ุนู„ู‰ backtick"""
    return str(text).replace("`", "ห‹")


TELEGRAM_MAX_LEN = 4000  # ู‡ุงู…ุด ุฃู…ุงู† ุชุญุช ุญุฏ ุชูŠู„ูŠุบุฑุงู… (4096)


async def send_long(target: Message, text: str, **kwargs):
    """ูŠุฑุณู„ ู†ุตุงู‹ ุทูˆูŠู„ุงู‹ ู…ู‚ุณู‘ู…ุงู‹ ุนู„ู‰ ุนุฏุฉ ุฑุณุงุฆู„ ุฅุฐุง ุชุฌุงูˆุฒ ุญุฏ ุชูŠู„ูŠุบุฑุงู…"""
    if len(text) <= TELEGRAM_MAX_LEN:
        await target.reply(text, **kwargs)
        return

    chunks = []
    current = ""
    for line in text.split("\n"):
        if len(current) + len(line) + 1 > TELEGRAM_MAX_LEN:
            chunks.append(current)
            current = line
        else:
            current = f"{current}\n{line}" if current else line
    if current:
        chunks.append(current)

    for chunk in chunks:
        await target.reply(chunk, **kwargs)


def get_file_info(msg: Message) -> tuple[str, int]:
    """ุงุณุชุฎุฑุงุฌ ุงุณู… ุงู„ู…ู„ู ูˆุญุฌู…ู‡ ู…ู† ุงู„ุฑุณุงู„ุฉ"""
    media = getattr(msg, msg.media.value, None)
    if msg.photo:
        return f"photo_{msg.id}.jpg", 0
    name = getattr(media, "file_name", None) or f"file_{msg.id}"
    size = getattr(media, "file_size", 0) or 0
    return name, size


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  ุงุฎุชุจุงุฑ ุณุฑุนุฉ ุงู„ุณูŠุฑูุฑุงุช
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

async def benchmark_server(
    session: aiohttp.ClientSession,
    server_name: str,
    test_data: bytes,
) -> tuple[str, float]:
    """ุฑูุน ู…ู„ู ุตุบูŠุฑ ูˆู‚ูŠุงุณ ุงู„ุณุฑุนุฉ ุงู„ุญู‚ูŠู‚ูŠุฉ"""
    try:
        form = aiohttp.FormData()
        form.add_field(
            "file",
            test_data,
            filename="bench.bin",
            content_type="application/octet-stream",
        )
        t0 = time.monotonic()
        async with session.post(
            f"https://{server_name}.gofile.io/contents/uploadfile",
            data=form,
            timeout=aiohttp.ClientTimeout(total=20),
        ) as resp:
            elapsed = time.monotonic() - t0
            if resp.status == 200 and elapsed > 0:
                speed = len(test_data) / elapsed
                logger.info(f"Server {server_name}: {fmt_speed(speed)}")
                return server_name, speed
    except Exception as ex:
        logger.warning(f"Server {server_name} failed benchmark: {ex}")
    return server_name, 0.0


async def get_best_server(session: aiohttp.ClientSession) -> tuple[str, float]:
    """ุฅุญุถุงุฑ ู‚ุงุฆู…ุฉ ุงู„ุณูŠุฑูุฑุงุช ูˆุงุฎุชูŠุงุฑ ุงู„ุฃุณุฑุน ุนุจุฑ ุงุฎุชุจุงุฑ ุญู‚ูŠู‚ูŠ"""
    try:
        async with session.get(
            "https://api.gofile.io/servers",
            timeout=aiohttp.ClientTimeout(total=10),
        ) as resp:
            data   = await resp.json()
            servers = [s["name"] for s in data["data"]["servers"]]
    except Exception as ex:
        logger.error(f"Failed to fetch servers: {ex}")
        return "store1", 0.0

    if not servers:
        return "store1", 0.0

    if len(servers) == 1:
        return servers[0], 0.0

    test_data = os.urandom(SERVER_TEST_SIZE * 1024)
    tasks     = [benchmark_server(session, s, test_data) for s in servers]
    results   = await asyncio.gather(*tasks)

    best_name, best_speed = max(results, key=lambda x: x[1])
    logger.info(f"Best server selected: {best_name} @ {fmt_speed(best_speed)}")
    return best_name, best_speed


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  ุชุชุจุน ุงู„ุชู‚ุฏู… ุฃุซู†ุงุก ุงู„ุฑูุน
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

class ProgressTracker:
    def __init__(self, total: int):
        self.total      = total
        self.uploaded   = 0
        self._start     = time.monotonic()
        self._lock      = asyncio.Lock()

    async def add(self, n: int):
        async with self._lock:
            self.uploaded += n

    @property
    def speed(self) -> float:
        elapsed = time.monotonic() - self._start
        return self.uploaded / elapsed if elapsed > 0 else 0.0

    @property
    def eta(self) -> str:
        spd = self.speed
        if spd <= 0 or self.total <= 0:
            return "โ€”"
        return fmt_eta((self.total - self.uploaded) / spd)

    def status_line(self) -> str:
        return (
            f"{progress_bar(self.uploaded, self.total)}\n"
            f"๐Ÿ“ฆ `{fmt_size(self.uploaded)}` / `{fmt_size(self.total)}`\n"
            f"๐Ÿš€ ุงู„ุณุฑุนุฉ: `{fmt_speed(self.speed)}`\n"
            f"โฑ ุงู„ู…ุชุจู‚ูŠ: `{self.eta}`"
        )


class TrackingFileReader:
    """ู‚ุงุฑุฆ ู…ู„ู ูŠุชุงุจุน ุงู„ุจุงูŠุชุงุช ุงู„ู…ุฑุณู„ุฉ โ€” ุจุฏูˆู† ู…ูƒุชุจุงุช ุฎุงุฑุฌูŠุฉ"""

    def __init__(self, path: str, tracker: ProgressTracker):
        self._path    = path
        self._tracker = tracker
        self._file    = None
        self._loop    = None

    async def __aenter__(self):
        self._loop = asyncio.get_event_loop()
        self._file = await self._loop.run_in_executor(None, open, self._path, "rb")
        return self

    async def __aexit__(self, *_):
        if self._file:
            await self._loop.run_in_executor(None, self._file.close)

    def __aiter__(self):
        return self

    async def __anext__(self) -> bytes:
        chunk = await self._loop.run_in_executor(None, self._file.read, CHUNK_SIZE)
        if not chunk:
            raise StopAsyncIteration
        await self._tracker.add(len(chunk))
        return chunk


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  ุฑูุน ู…ู„ู ูˆุงุญุฏ
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

async def upload_single(
    client:     Client,
    msg:        Message,
    status_msg: Message,
    server:     str,
    srv_speed:  float,
    file_num:   int,
    total_files: int,
    session:    aiohttp.ClientSession,
) -> dict:
    """ุชุญู…ูŠู„ ุงู„ู…ู„ู ู…ู† ุชูŠู„ูŠุบุฑุงู… ุซู… ุฑูุนู‡ ุนู„ู‰ GoFile ู…ุน ุชุชุจุน ุงู„ุชู‚ุฏู…"""

    file_name, file_size = get_file_info(msg)
    safe_name = safe_md(file_name)

    # โ”€โ”€ ุฅู†ุดุงุก ู…ู„ู ู…ุคู‚ุช โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    tmp_fd, tmp_path = tempfile.mkstemp()
    os.close(tmp_fd)

    try:
        # โ”€โ”€ 1. ุชุญู…ูŠู„ ู…ู† ุชูŠู„ูŠุบุฑุงู… โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        await status_msg.edit(
            f"โฌ‡๏ธ **ุฌุงุฑูŠ ุงู„ุชุญู…ูŠู„ ู…ู† ุชูŠู„ูŠุบุฑุงู…...**\n\n"
            f"๐Ÿ“„ `{safe_name}`\n"
            f"๐Ÿ—‚ ุงู„ู…ู„ู `{file_num}` ู…ู† `{total_files}`\n"
            f"๐Ÿ–ฅ ุงู„ุณูŠุฑูุฑ: `{server}`"
            + (f" โšก `{fmt_speed(srv_speed)}`" if srv_speed > 0 else "")
        )

        await client.download_media(msg, file_name=tmp_path)
        actual_size = os.path.getsize(tmp_path)

        # โ”€โ”€ 2. ุฑูุน ุนู„ู‰ GoFile ู…ุน ุชุชุจุน ุงู„ุชู‚ุฏู… โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        tracker   = ProgressTracker(actual_size)
        stop_evt  = asyncio.Event()

        async def _live_progress():
            """ูŠุญุฏู‘ุซ ุฑุณุงู„ุฉ ุงู„ุชู‚ุฏู… ูƒู„ PROGRESS_UPDATE_INTERVAL ุซุงู†ูŠุฉ"""
            while not stop_evt.is_set():
                await asyncio.sleep(PROGRESS_UPDATE_INTERVAL)
                if stop_evt.is_set():
                    break
                try:
                    await status_msg.edit(
                        f"โฌ†๏ธ **ุฌุงุฑูŠ ุงู„ุฑูุน ุนู„ู‰ GoFile...**\n\n"
                        f"๐Ÿ“„ `{safe_name}`\n"
                        f"๐Ÿ—‚ ุงู„ู…ู„ู `{file_num}` ู…ู† `{total_files}`\n"
                        f"๐Ÿ–ฅ ุงู„ุณูŠุฑูุฑ: `{server}`"
                        + (f" โšก `{fmt_speed(srv_speed)}`" if srv_speed > 0 else "")
                        + f"\n\n{tracker.status_line()}"
                    )
                except Exception:
                    pass  # ุชุฌุงู‡ู„ ุฃุฎุทุงุก FloodWait ุงู„ุจุณูŠุทุฉ

        progress_task = asyncio.create_task(_live_progress())

        try:
            async with TrackingFileReader(tmp_path, tracker) as reader:
                form = aiohttp.FormData()
                form.add_field(
                    "file",
                    reader,
                    filename=file_name,
                    content_type="application/octet-stream",
                )
                async with session.post(
                    f"https://{server}.gofile.io/contents/uploadfile",
                    data=form,
                    timeout=aiohttp.ClientTimeout(total=0),  # ุจุฏูˆู† ุญุฏ ุฒู…ู†ูŠ
                ) as resp:
                    resp_data = await resp.json()

            stop_evt.set()
            await progress_task

            if resp.status == 200 and resp_data.get("status") == "ok":
                return {
                    "ok":        True,
                    "name":      file_name,
                    "size":      actual_size,
                    "link":      resp_data["data"]["downloadPage"],
                    "server":    server,
                }
            else:
                err = resp_data.get("message", f"HTTP {resp.status}")
                return {"ok": False, "name": file_name, "error": err}

        finally:
            stop_evt.set()
            progress_task.cancel()

    except Exception as ex:
        logger.exception(f"Error uploading {file_name}")
        return {"ok": False, "name": file_name, "error": str(ex)}

    finally:
        try:
            os.unlink(tmp_path)
        except OSError:
            pass


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  ู…ุนุงู„ุฌ ุงู„ู…ู„ูุงุช ุงู„ุฑุฆูŠุณูŠ
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

async def process_user_queue(client: Client, user_id: int):
    """
    ูŠู†ุชุธุฑ ู‚ู„ูŠู„ุงู‹ ู„ุชุฌู…ูŠุน ู…ู„ูุงุช ู…ุชุนุฏุฏุฉ ู‚ุฏ ูŠุฑุณู„ู‡ุง ุงู„ู…ุณุชุฎุฏู… ุฏูุนุฉ ูˆุงุญุฏุฉุŒ
    ูŠุนุงู„ุฌู‡ุงุŒ ุซู… ูŠุชุญู‚ู‚ ุฅุฐุง ูˆุตู„ุช ู…ู„ูุงุช ุฌุฏูŠุฏุฉ ุฃุซู†ุงุก ุงู„ู…ุนุงู„ุฌุฉ (ู…ุซู„ุงู‹ ุงู„ู…ุณุชุฎุฏู…
    ุฃุฑุณู„ ุฏูุนุฉ ุซุงู†ูŠุฉ ูˆู‡ูˆ ูŠู†ุชุธุฑ) ูˆูŠูƒู…ู„ ู…ุนุงู„ุฌุชู‡ุง ุจู†ูุณ ุงู„ู…ู‡ู…ุฉ ุจุฏู„ ู…ุง ุชุถูŠุน.
    """
    try:
        while True:
            await asyncio.sleep(FILE_COLLECT_DELAY)

            async with pending_locks[user_id]:
                messages = pending_files.pop(user_id, [])

            if not messages:
                return

            await _process_batch(client, messages)
    finally:
        pending_tasks.pop(user_id, None)


async def _process_batch(client: Client, messages: list[Message]):
    """ูŠุนุงู„ุฌ ุฏูุนุฉ ูˆุงุญุฏุฉ ู…ู† ุงู„ู…ู„ูุงุช: ุงุฎุชูŠุงุฑ ุณูŠุฑูุฑุŒ ุฑูุน ุชุณู„ุณู„ูŠุŒ ุฅุฑุณุงู„ ุงู„ู†ุชุงุฆุฌ"""
    total   = len(messages)
    first   = messages[0]
    names   = [get_file_info(m)[0] for m in messages]

    # โ”€โ”€ ุฑุณุงู„ุฉ ุฃูˆู„ูŠุฉ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    status_msg = await first.reply(
        f"๐Ÿ” **ุฌุงุฑูŠ ุงุฎุชุจุงุฑ ุงู„ุณูŠุฑูุฑุงุช...**\n\n"
        f"๐Ÿ“ ุนุฏุฏ ุงู„ู…ู„ูุงุช: `{total}`\n"
        + "\n".join(f"  โ€ข `{safe_md(n)}`" for n in names)
    )

    async with aiohttp.ClientSession() as session:
        # โ”€โ”€ ุงุฎุชูŠุงุฑ ุฃุณุฑุน ุณูŠุฑูุฑ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        try:
            server, srv_speed = await get_best_server(session)
        except Exception as ex:
            await status_msg.edit(f"โŒ ูุดู„ ุงู„ุงุชุตุงู„ ุจู€ GoFile: `{ex}`")
            return

        speed_label = f"`{fmt_speed(srv_speed)}`" if srv_speed > 0 else "`โ€”`"
        await status_msg.edit(
            f"โœ… **ุชู… ุงุฎุชูŠุงุฑ ุงู„ุณูŠุฑูุฑ ุงู„ุฃุณุฑุน!**\n\n"
            f"๐Ÿ–ฅ ุงู„ุณูŠุฑูุฑ: `{server}` | โšก {speed_label}\n"
            f"๐Ÿ“ ุนุฏุฏ ุงู„ู…ู„ูุงุช: `{total}`\n\n"
            f"โณ ุจุฏุก ุงู„ุฑูุน..."
        )

        results = []
        for idx, msg in enumerate(messages, 1):
            result = await upload_single(
                client, msg, status_msg,
                server, srv_speed,
                idx, total,
                session,
            )
            results.append(result)

    # โ”€โ”€ ุจู†ุงุก ุฑุณุงู„ุฉ ุงู„ู†ุชุงุฆุฌ ุงู„ู†ู‡ุงุฆูŠุฉ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    ok_list   = [r for r in results if r["ok"]]
    fail_list = [r for r in results if not r["ok"]]

    lines = [f"๐Ÿ“ฆ **ู†ุชูŠุฌุฉ ุงู„ุฑูุน**", ""]

    if ok_list:
        lines.append(f"โœ… **ู†ุฌุญ ุงู„ุฑูุน ({len(ok_list)} ู…ู„ู):**")
        for r in ok_list:
            lines.append(f"โ”œ ๐Ÿ“„ `{safe_md(r['name'])}` โ€” `{fmt_size(r['size'])}`")
            lines.append(f"โ”” ๐Ÿ”— {r['link']}")
            lines.append("")

    if fail_list:
        lines.append(f"โŒ **ูุดู„ ุงู„ุฑูุน ({len(fail_list)} ู…ู„ู):**")
        for r in fail_list:
            lines.append(f"โ€ข `{safe_md(r['name'])}` โ†’ _{safe_md(r['error'])}_")
        lines.append("")

    lines.append(f"๐Ÿ–ฅ **ุงู„ุณูŠุฑูุฑ:** `{server}` | โšก {speed_label}")

    # โ”€โ”€ ุญุฐู ุฑุณุงู„ุฉ ุงู„ุชู‚ุฏู… ูˆุฅุฑุณุงู„ ุฑุณุงู„ุฉ ุฌุฏูŠุฏุฉ ุจุฏู„ ุงู„ุชุนุฏูŠู„ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    # (ุงู„ุชุนุฏูŠู„ ุนู„ู‰ ุฑุณุงู„ุฉ ู„ุง ูŠูˆู„ู‘ุฏ ุฅุดุนุงุฑุงู‹ ุฌุฏูŠุฏุงู‹ ููŠ ุชูŠู„ูŠุบุฑุงู…ุŒ ู„ุฐุง
    #  ู†ุญุฐูู‡ุง ูˆู†ุฑุณู„ ุฑุณุงู„ุฉ ู…ู†ูุตู„ุฉ ู„ุชู†ุจูŠู‡ ุงู„ู…ุณุชุฎุฏู… ุจุงู†ุชู‡ุงุก ุงู„ุฑูุน)
    try:
        await status_msg.delete()
    except Exception:
        pass

    await send_long(first, "\n".join(lines), disable_web_page_preview=True)


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  ู‡ุงู†ุฏู„ุฑุงุช ุงู„ุฃูˆุงู…ุฑ
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

@app.on_message(filters.command("start") & filters.private)
async def cmd_start(client: Client, message: Message):
    await message.reply(
        "**๐Ÿš€ ุฃู‡ู„ุงู‹ ุจูƒ ููŠ ุจูˆุช ุฑูุน ุงู„ู…ู„ูุงุช!**\n"
        "โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n\n"
        "๐Ÿ“ค **ูƒูŠููŠุฉ ุงู„ุงุณุชุฎุฏุงู…:**\n"
        "  โ€ข ุฃุฑุณู„ ุฃูŠ ู…ู„ู ูˆุณูŠูุฑูุน ุชู„ู‚ุงุฆูŠุงู‹\n"
        "  โ€ข ูŠู…ูƒู†ูƒ ุฅุฑุณุงู„ ุนุฏุฉ ู…ู„ูุงุช ู…ุฑุฉ ูˆุงุญุฏุฉ\n\n"
        "โš™๏ธ **ู…ุง ูŠูุนู„ู‡ ุงู„ุจูˆุช:**\n"
        "  โ‘  ูŠุฎุชุจุฑ ุฌู…ูŠุน ุณูŠุฑูุฑุงุช GoFile\n"
        "  โ‘ก ูŠุฎุชุงุฑ ุงู„ุฃุณุฑุน ุนุจุฑ ู‚ูŠุงุณ ุญู‚ูŠู‚ูŠ\n"
        "  โ‘ข ูŠุฑูุน ู…ู„ูุงุชูƒ ู…ุน ุดุฑูŠุท ุชู‚ุฏู… ู…ุจุงุดุฑ\n"
        "  โ‘ฃ ูŠุฑุณู„ ุฑูˆุงุจุท ุงู„ุชุญู…ูŠู„ ุจุนุฏ ุงู„ุงู†ุชู‡ุงุก\n\n"
        "๐Ÿ“‚ **ุงู„ุฃู†ูˆุงุน ุงู„ู…ุฏุนูˆู…ุฉ:**\n"
        "  ู…ุณุชู†ุฏุงุช ยท ููŠุฏูŠูˆ ยท ุตูˆุช ยท ุตูˆุฑ ยท ุฃูŠ ู…ู„ู\n\n"
        "๐Ÿ›‘ **ุฅู„ุบุงุก ุนู…ู„ูŠุฉ ุดุบุงู„ุฉ:** /cancel\n\n"
        "โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n"
        "๐ŸŒ **ุงู„ุฎุฏู…ุฉ:** [GoFile.io](https://gofile.io)",
        disable_web_page_preview=True,
    )


@app.on_message(filters.command("cancel") & filters.private)
async def cmd_cancel(client: Client, message: Message):
    user_id = message.from_user.id

    task = pending_tasks.get(user_id)
    if task and not task.done():
        task.cancel()
        async with pending_locks[user_id]:
            pending_files.pop(user_id, None)
        await message.reply("๐Ÿ›‘ **ุชู… ุฅู„ุบุงุก ุนู…ู„ูŠุฉ ุงู„ุฑูุน.**")
    else:
        await message.reply("ู…ุงูƒูˆ ุนู…ู„ูŠุฉ ุฑูุน ุดุบุงู„ุฉ ุญุงู„ูŠุงู‹.")


@app.on_message(
    filters.private
    & (
        filters.document
        | filters.video
        | filters.audio
        | filters.voice
        | filters.photo
        | filters.video_note
    )
)
async def cmd_file(client: Client, message: Message):
    user_id = message.from_user.id

    async with pending_locks[user_id]:
        pending_files[user_id].append(message)

        # ุฅุฐุง ูƒุงู†ุช ู‡ู†ุงูƒ ู…ู‡ู…ุฉ ู‚ูŠุฏ ุงู„ุชุดุบูŠู„ุŒ ุฃุถู ุงู„ู…ู„ู ูู‚ุท
        task = pending_tasks.get(user_id)
        if task and not task.done():
            return

        # ุงุจุฏุฃ ู…ู‡ู…ุฉ ู…ุนุงู„ุฌุฉ ุฌุฏูŠุฏุฉ
        pending_tasks[user_id] = asyncio.create_task(
            process_user_queue(client, user_id)
        )


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  ุชุดุบูŠู„ ุงู„ุจูˆุช
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

if __name__ == "__main__":
    logger.info("Starting GoFile Bot...")
    app.run()