File size: 33,330 Bytes
0477ed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel, Field
from bot import Bot, temp
from database.users_chats_db import db
from database.ia_filterdb import Media, get_file_details, get_search_results
from database.connections_mdb import add_connection, active_connection, all_connections, if_active, make_active, make_inactive, delete_connection
from database.filters_mdb import add_filter, find_filter, get_filters, delete_filter, del_all, count_filters, filter_stats
from database.gfilters_mdb import add_gfilter, find_gfilter, get_gfilters, delete_gfilter, del_allg, count_gfilters, gfilter_stats
from utils import get_settings, save_group_settings, humanbytes, get_size, extract_user, get_file_id, get_poster, parser, get_shortlink, extract_time, admin_check
from info import API_ID, API_HASH, BOT_TOKEN, LOG_CHANNEL, UPTIME, WEB_SUPPORT, LOG_MSG, ADMINS, CHANNELS
from pyrogram import Client, filters, enums, types
from pyrogram.errors import ChatAdminRequired, UserIsBlocked, MessageNotModified, PeerIdInvalid, FloodWait
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message, CallbackQuery
from telegraph import upload_file
from io import BytesIO
import aiohttp
import asyncio
import requests
import os
import logging
import re
import traceback
import json
from googletrans import Translator
from gtts import gTTS
from youtube_search import YoutubeSearch
from youtubesearchpython import SearchVideos
from yt_dlp import YoutubeDL
import shutil
import psutil
import wget
from datetime import datetime, timedelta
from telegraph import upload_file
from PIL import Image, ImageDraw, ImageFont
import textwrap

app = FastAPI()

# Shared instance of the Bot class
bot_instance = Bot()

# Initialize Pyrogram client
@app.on_event("startup")
async def startup_event():
    asyncio.create_task(bot_instance.start())

@app.on_event("shutdown")
async def shutdown_event():
    await bot_instance.stop()

# Utility functions
async def get_chat_member(client, chat_id, user_id):
    try:
        return await client.get_chat_member(chat_id, user_id)
    except Exception as e:
        logger.error(f"Error getting chat member: {e}")
        return None

async def send_message(client, chat_id, text, reply_markup=None, disable_web_page_preview=False):
    try:
        return await client.send_message(chat_id, text, reply_markup=reply_markup, disable_web_page_preview=disable_web_page_preview)
    except Exception as e:
        logger.error(f"Error sending message: {e}")
        return None

async def edit_message(client, message, text, reply_markup=None):
    try:
        return await message.edit_text(text, reply_markup=reply_markup)
    except Exception as e:
        logger.error(f"Error editing message: {e}")
        return None

async def delete_message(client, message):
    try:
        return await message.delete()
    except Exception as e:
        logger.error(f"Error deleting message: {e}")
        return None

# Models
class User(BaseModel):
    user_id: int

class Group(BaseModel):
    group_id: int

class Filter(BaseModel):
    group_id: int
    text: str
    reply_text: str
    btn: str = Field(default=None)
    file: str = Field(default=None)
    alert: str = Field(default=None)

class GlobalFilter(BaseModel):
    text: str
    reply_text: str
    btn: str = Field(default=None)
    file: str = Field(default=None)
    alert: str = Field(default=None)

class BroadcastMessage(BaseModel):
    message_id: int

class ShortenURL(BaseModel):
    url: str

class SettingsUpdate(BaseModel):
    group_id: int
    setting_key: str
    setting_value: bool

class SearchQuery(BaseModel):
    query: str
    file_type: str = Field(default=None)
    offset: int = Field(default=0)
    max_results: int = Field(default=10)

class ConnectionRequest(BaseModel):
    user_id: int
    group_id: int

class TextToSpeechRequest(BaseModel):
    text: str

class YouTubeDownloadRequest(BaseModel):
    url: str

class TelegraphUploadRequest(BaseModel):
    file_path: str

class CarbonRequest(BaseModel):
    text: str

class FontRequest(BaseModel):
    text: str
    style: str

class PasteRequest(BaseModel):
    text: str

class ShareTextRequest(BaseModel):
    text: str

class GroupManagerAction(BaseModel):
    action: str
    user_id: int = Field(default=None)
    time: str = Field(default=None)

# Endpoints
@app.get("/uptime")
async def get_uptime():
    uptime = datetime.now() - datetime.fromtimestamp(temp.UPTIME)
    return {"uptime": str(uptime)}

@app.get("/stats")
async def get_stats():
    total_users = await db.total_users_count()
    total_chats = await db.total_chat_count()
    return {"total_users": total_users, "total_chats": total_chats}

@app.post("/ban_user")
async def ban_user_endpoint(user: User):
    await db.ban_user(user.user_id, "No Reason")
    temp.BANNED_USERS.append(user.user_id)
    return {"status": "User banned successfully"}

@app.post("/unban_user")
async def unban_user_endpoint(user: User):
    await db.remove_ban(user.user_id)
    temp.BANNED_USERS.remove(user.user_id)
    return {"status": "User unbanned successfully"}

@app.post("/add_filter")
async def add_filter_endpoint(filter_data: Filter):
    await add_filter(filter_data.group_id, filter_data.text, filter_data.reply_text, filter_data.btn, filter_data.file, filter_data.alert)
    return {"status": "Filter added successfully"}

@app.post("/find_filter")
async def find_filter_endpoint(filter_data: Filter):
    reply_text, btn, alert, fileid = await find_filter(filter_data.group_id, filter_data.text)
    return {"reply_text": reply_text, "btn": btn, "alert": alert, "fileid": fileid}

@app.post("/get_filters")
async def get_filters_endpoint(group_id: int):
    texts = await get_filters(group_id)
    return {"filters": texts}

@app.post("/delete_filter")
async def delete_filter_endpoint(filter_data: Filter):
    await delete_filter(None, filter_data.text, filter_data.group_id)
    return {"status": "Filter deleted successfully"}

@app.post("/del_all_filters")
async def del_all_filters_endpoint(group_id: int):
    await del_all(None, group_id, "Group")
    return {"status": "All filters deleted successfully"}

@app.post("/add_gfilter")
async def add_gfilter_endpoint(gfilter_data: GlobalFilter):
    await add_gfilter('gfilters', gfilter_data.text, gfilter_data.reply_text, gfilter_data.btn, gfilter_data.file, gfilter_data.alert)
    return {"status": "Global filter added successfully"}

@app.post("/find_gfilter")
async def find_gfilter_endpoint(gfilter_data: GlobalFilter):
    reply_text, btn, alert, fileid = await find_gfilter('gfilters', gfilter_data.text)
    return {"reply_text": reply_text, "btn": btn, "alert": alert, "fileid": fileid}

@app.post("/get_gfilters")
async def get_gfilters_endpoint():
    texts = await get_gfilters('gfilters')
    return {"global_filters": texts}

@app.post("/delete_gfilter")
async def delete_gfilter_endpoint(gfilter_data: GlobalFilter):
    await delete_gfilter(None, gfilter_data.text, 'gfilters')
    return {"status": "Global filter deleted successfully"}

@app.post("/del_all_gfilters")
async def del_all_gfilters_endpoint():
    await del_allg(None, 'gfilters')
    return {"status": "All global filters deleted successfully"}

@app.post("/broadcast")
async def broadcast_endpoint(broadcast_data: BroadcastMessage):
    users = await db.get_all_users()
    b_msg = await bot_instance.get_messages(broadcast_data.message_id)
    sts = await send_message(bot_instance, broadcast_data.message_id, "Broadcasting your messages...")
    start_time = time.time()
    total_users = await db.total_users_count()
    done = 0
    blocked = 0
    deleted = 0
    failed = 0
    success = 0
    async for user in users:
        pti, sh = await broadcast_messages(int(user['id']), b_msg)
        if pti:
            success += 1
        elif pti == False:
            if sh == "Blocked":
                blocked += 1
            elif sh == "Deleted":
                deleted += 1
            elif sh == "Error":
                failed += 1
        done += 1
        if not done % 20:
            await edit_message(bot_instance, sts, f"Broadcast in progress:\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}")
    time_taken = datetime.timedelta(seconds=int(time.time() - start_time))
    await delete_message(bot_instance, sts)
    await send_message(bot_instance, broadcast_data.message_id, f"Broadcast completed:\nTime taken: {time_taken}\n\nTotal Users: {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}")
    return {"status": "Broadcast completed"}

@app.post("/clear_junk")
async def clear_junk_endpoint():
    users = await db.get_all_users()
    sts = await send_message(bot_instance, broadcast_data.message_id, "Clearing junk users...")
    start_time = time.time()
    total_users = await db.total_users_count()
    blocked = 0
    deleted = 0
    failed = 0
    done = 0
    async for user in users:
        pti, sh = await clear_junk(int(user['id']), None)
        if pti == False:
            if sh == "Blocked":
                blocked += 1
            elif sh == "Deleted":
                deleted += 1
            elif sh == "Error":
                failed += 1
        done += 1
        if not done % 20:
            await edit_message(bot_instance, sts, f"Clearing junk in progress:\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nBlocked: {blocked}\nDeleted: {deleted}")
    time_taken = datetime.timedelta(seconds=int(time.time() - start_time))
    await delete_message(bot_instance, sts)
    await send_message(bot_instance, broadcast_data.message_id, f"Clearing junk completed:\nTime taken: {time_taken}\n\nTotal Users: {total_users}\nCompleted: {done} / {total_users}\nBlocked: {blocked}\nDeleted: {deleted}")
    return {"status": "Junk clearing completed"}

@app.post("/group_broadcast")
async def group_broadcast_endpoint(broadcast_data: BroadcastMessage):
    groups = await db.get_all_chats()
    b_msg = await bot_instance.get_messages(broadcast_data.message_id)
    sts = await send_message(bot_instance, broadcast_data.message_id, "Broadcasting to groups...")
    start_time = time.time()
    total_groups = await db.total_chat_count()
    done = 0
    failed = ""
    success = 0
    deleted = 0
    async for group in groups:
        pti, sh, ex = await broadcast_messages_group(int(group['id']), b_msg)
        if pti == True:
            if sh == "Success":
                success += 1
        elif pti == False:
            if sh == "deleted":
                deleted += 1
                failed += ex
                try:
                    await bot_instance.leave_chat(int(group['id']))
                except Exception as e:
                    logger.error(f"{e} > {group['id']}")
        done += 1
        if not done % 20:
            await edit_message(bot_instance, sts, f"Broadcast in progress:\n\nTotal Groups {total_groups}\nCompleted: {done} / {total_groups}\nSuccess: {success}\nDeleted: {deleted}")
    time_taken = datetime.timedelta(seconds=int(time.time() - start_time))
    await delete_message(bot_instance, sts)
    await send_message(bot_instance, broadcast_data.message_id, f"Broadcast completed:\nTime taken: {time_taken}\n\nTotal Groups: {total_groups}\nCompleted: {done} / {total_groups}\nSuccess: {success}\nDeleted: {deleted}\n\nFailed reasons: {failed}")
    return {"status": "Group broadcast completed"}

@app.post("/junk_group")
async def junk_group_endpoint():
    groups = await db.get_all_chats()
    sts = await send_message(bot_instance, broadcast_data.message_id, "Clearing junk groups...")
    start_time = time.time()
    total_groups = await db.total_chat_count()
    done = 0
    failed = ""
    deleted = 0
    async for group in groups:
        pti, sh, ex = await junk_group(int(group['id']), None)
        if pti == False:
            if sh == "deleted":
                deleted += 1
                failed += ex
                try:
                    await bot_instance.leave_chat(int(group['id']))
                except Exception as e:
                    logger.error(f"{e} > {group['id']}")
        done += 1
        if not done % 20:
            await edit_message(bot_instance, sts, f"Clearing junk in progress:\n\nTotal Groups {total_groups}\nCompleted: {done} / {total_groups}\nDeleted: {deleted}")
    time_taken = datetime.timedelta(seconds=int(time.time() - start_time))
    await delete_message(bot_instance, sts)
    await send_message(bot_instance, broadcast_data.message_id, f"Clearing junk completed:\nTime taken: {time_taken}\n\nTotal Groups: {total_groups}\nCompleted: {done} / {total_groups}\nDeleted: {deleted}\n\nFailed reasons: {failed}")
    return {"status": "Junk group clearing completed"}

@app.post("/add_connection")
async def add_connection_endpoint(connection_request: ConnectionRequest):
    result = await add_connection(connection_request.group_id, connection_request.user_id)
    return {"status": "Connection added successfully" if result else "Connection already exists"}

@app.post("/active_connection")
async def active_connection_endpoint(user_id: int):
    group_id = await active_connection(user_id)
    return {"active_group_id": group_id}

@app.post("/all_connections")
async def all_connections_endpoint(user_id: int):
    group_ids = await all_connections(user_id)
    return {"group_ids": group_ids}

@app.post("/if_active")
async def if_active_endpoint(connection_request: ConnectionRequest):
    result = await if_active(connection_request.user_id, connection_request.group_id)
    return {"is_active": result}

@app.post("/make_active")
async def make_active_endpoint(connection_request: ConnectionRequest):
    result = await make_active(connection_request.user_id, connection_request.group_id)
    return {"status": "Made active successfully" if result else "Failed to make active"}

@app.post("/make_inactive")
async def make_inactive_endpoint(user_id: int):
    result = await make_inactive(user_id)
    return {"status": "Made inactive successfully" if result else "Failed to make inactive"}

@app.post("/delete_connection")
async def delete_connection_endpoint(connection_request: ConnectionRequest):
    result = await delete_connection(connection_request.user_id, connection_request.group_id)
    return {"status": "Connection deleted successfully" if result else "Failed to delete connection"}

@app.post("/search")
async def search_endpoint(search_query: SearchQuery):
    files, next_offset, total_results = await get_search_results(search_query.query, file_type=search_query.file_type, offset=search_query.offset, max_results=search_query.max_results)
    return {"files": files, "next_offset": next_offset, "total_results": total_results}

@app.post("/get_file_details")
async def get_file_details_endpoint(file_id: str):
    file_details = await get_file_details(file_id)
    return {"file_details": file_details}

@app.post("/get_settings")
async def get_settings_endpoint(group_id: int):
    settings = await get_settings(group_id)
    return {"settings": settings}

@app.post("/save_group_settings")
async def save_group_settings_endpoint(settings_update: SettingsUpdate):
    await save_group_settings(settings_update.group_id, settings_update.setting_key, settings_update.setting_value)
    return {"status": "Settings updated successfully"}

@app.post("/send_cached_media")
async def send_cached_media_endpoint(user_id: int, file_id: str, caption: str = None, protect_content: bool = False):
    await bot_instance.send_cached_media(chat_id=user_id, file_id=file_id, caption=caption, protect_content=protect_content)
    return {"status": "Media sent successfully"}

@app.post("/get_poster")
async def get_poster_endpoint(query: str, id: bool = False, file: str = None):
    poster = await get_poster(query, bulk=False, id=id, file=file)
    return {"poster": poster}

@app.post("/parse_text")
async def parse_text_endpoint(text: str, keyword: str, cb_data: str):
    note_data, buttons, alerts = parser(text, keyword, cb_data)
    return {"note_data": note_data, "buttons": buttons, "alerts": alerts}

@app.post("/get_shortlink")
async def get_shortlink_endpoint(shorten_url: ShortenURL):
    short_url = await get_shortlink(shorten_url.url)
    return {"short_url": short_url}

@app.post("/extract_time")
async def extract_time_endpoint(time_val: str):
    extracted_time = extract_time(time_val)
    return {"extracted_time": extracted_time}

@app.post("/admin_check")
async def admin_check_endpoint(chat_id: int, user_id: int):
    is_admin = await admin_check(Message(chat_id=chat_id, from_user=types.User(id=user_id)))
    return {"is_admin": is_admin}

@app.post("/auto_filter")
async def auto_filter_endpoint(query: str, chat_id: int, user_id: int, offset: int = 0, max_results: int = 10):
    files, next_offset, total_results = await get_search_results(query, offset=offset, max_results=max_results)
    if not files:
        return {"status": "No files found"}
    pre = 'filep' if await get_settings(chat_id)['file_secure'] else 'file'
    btn = []
    for file in files:
        btn.append([
            InlineKeyboardButton(text=f"[{humanbytes(file.file_size)}] {file.file_name}", callback_data=f'{pre}#{user_id}#{file.file_id}')
        ])
    btn.append([InlineKeyboardButton(text="πŸ”— How to download πŸ”—", callback_data="howdl")])
    reply_markup = InlineKeyboardMarkup(btn)
    return {"files": files, "next_offset": next_offset, "total_results": total_results, "reply_markup": reply_markup}

@app.post("/send_telegram_message")
async def send_telegram_message_endpoint(chat_id: int, text: str):
    message = await send_message(bot_instance, chat_id, text)
    return {"message_id": message.id}

@app.post("/edit_telegram_message")
async def edit_telegram_message_endpoint(message_id: int, chat_id: int, text: str):
    message = await bot_instance.get_messages(chat_id, message_id)
    edited_message = await edit_message(bot_instance, message, text)
    return {"edited_message_id": edited_message.id}

@app.post("/delete_telegram_message")
async def delete_telegram_message_endpoint(message_id: int, chat_id: int):
    message = await bot_instance.get_messages(chat_id, message_id)
    await delete_message(bot_instance, message)
    return {"status": "Message deleted successfully"}

@app.post("/carbon")
async def carbon_endpoint(carbon_request: CarbonRequest):
    carbon_image = await make_carbon(carbon_request.text, True)
    return {"carbon_url": carbon_image}

async def make_carbon(text, tele=False):
    url = "https://carbonara.solopov.dev/api/cook"
    async with aiohttp.ClientSession() as session:
        async with session.post(url, json={"code": text}) as resp:
            image = BytesIO(await resp.read())
    image.name = "carbon.png"
    if tele:
        uf = upload_file(image)
        image.close()
        return f"https://graph.org{uf[0]}"
    return image

@app.post("/font")
async def font_endpoint(font_request: FontRequest):
    fonts = {
        "typewriter": Fonts.typewriter,
        "outline": Fonts.outline,
        "serif": Fonts.serief,
        "bold_cool": Fonts.bold_cool,
        "cool": Fonts.cool,
        "small_cap": Fonts.smallcap,
        "script": Fonts.script,
        "bold_script": Fonts.bold_script,
        "tiny": Fonts.tiny,
        "comic": Fonts.comic,
        "san": Fonts.san,
        "slant_san": Fonts.slant_san,
        "slant": Fonts.slant,
        "sim": Fonts.sim,
        "circles": Fonts.circles,
        "dark_circle": Fonts.dark_circle,
        "gothic": Fonts.gothic,
        "bold_gothic": Fonts.bold_gothic,
        "cloud": Fonts.cloud,
        "happy": Fonts.happy,
        "sad": Fonts.sad,
        "special": Fonts.special,
        "square": Fonts.square,
        "dark_square": Fonts.dark_square,
        "andalucia": Fonts.andalucia,
        "manga": Fonts.manga,
        "stinky": Fonts.stinky,
        "bubbles": Fonts.bubbles,
        "underline": Fonts.underline,
        "ladybug": Fonts.ladybug,
        "rays": Fonts.rays,
        "birds": Fonts.birds,
        "slash": Fonts.slash,
        "stop": Fonts.stop,
        "skyline": Fonts.skyline,
        "arrows": Fonts.arrows,
        "rvnes": Fonts.rvnes,
        "strike": Fonts.strike,
        "frozen": Fonts.frozen
    }
    cls = fonts.get(font_request.style)
    if not cls:
        return {"error": "Invalid style"}
    new_text = cls(font_request.text)
    return {"new_text": new_text}

@app.post("/paste")
async def paste_endpoint(paste_request: PasteRequest):
    paste_response = await p_paste(paste_request.text)
    return paste_response

async def p_paste(code, extension=None):
    siteurl = "https://pasty.lus.pm/api/v1/pastes"
    data = {"content": code}
    try:
        response = requests.post(url=siteurl, data=json.dumps(data), headers={"User-Agent": "Mozilla/5.0", "content-type": "application/json"})
    except Exception as e:
        return {"error": str(e)}
    if response.ok:
        response = response.json()
        purl = (
            f"https://pasty.lus.pm/{response['id']}.{extension}"
            if extension
            else f"https://pasty.lus.pm/{response['id']}.txt"
        )
        return {
            "url": purl,
            "raw": f"https://pasty.lus.pm/{response['id']}/raw",
            "bin": "Pasty",
        }
    return {"error": "Unable to reach pasty.lus.pm"}

@app.post("/share_text")
async def share_text_endpoint(share_request: ShareTextRequest):
    share_url = f"https://t.me/share/url?url={quote(share_request.text)}"
    return {"share_url": share_url}

@app.post("/telegraph_upload")
async def telegraph_upload_endpoint(upload_request: TelegraphUploadRequest):
    try:
        response = upload_file(upload_request.file_path)
    except Exception as e:
        logger.error(f"Error uploading to Telegraph: {e}")
        return {"error": str(e)}
    telegraph_url = f"https://graph.org{response[0]}"
    return {"telegraph_url": telegraph_url}

@app.post("/text_to_speech")
async def text_to_speech_endpoint(tts_request: TextToSpeechRequest):
    audio = await convert(tts_request.text)
    return {"audio_url": audio.name}

async def convert(text):
    audio = BytesIO()
    i = Translator().translate(text, dest="en")
    lang = i.src
    tts = gTTS(text, lang=lang)
    audio.name = lang + ".mp3"
    tts.write_to_fp(audio)
    return audio

@app.post("/download_youtube_song")
async def download_youtube_song_endpoint(yt_request: YouTubeDownloadRequest):
    try:
        results = YoutubeSearch(yt_request.url, max_results=1).to_dict()
        link = f"https://youtube.com{results[0]['url_suffix']}"
        title = results[0]["title"][:40]
        thumbnail = results[0]["thumbnails"][0]
        thumb_name = f'thumb{title}.jpg'
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, 'wb').write(thumb.content)
        performer = f"[Mα΄‹Ι΄ Bᴏᴛᴒℒ]"
        duration = results[0]["duration"]
        url_suffix = results[0]["url_suffix"]
        views = results[0]["views"]
    except Exception as e:
        logger.error(f"Error downloading YouTube song: {e}")
        return {"error": str(e)}

    ydl_opts = {"format": "bestaudio[ext=m4a]"}
    try:
        with YoutubeDL(ydl_opts) as ydl:
            info_dict = ydl.extract_info(link, download=False)
            audio_file = ydl.prepare_filename(info_dict)
            ydl.process_info(info_dict)
    except Exception as e:
        logger.error(f"Error processing YouTube song: {e}")
        return {"error": str(e)}

    cap = "**BYβ€Ίβ€Ί [Mα΄‹Ι΄ Bᴏᴛᴒℒ](https://t.me/mkn_bots_updates)**"
    secmul, dur, dur_arr = 1, 0, duration.split(':')
    for i in range(len(dur_arr) - 1, -1, -1):
        dur += (int(dur_arr[i]) * secmul)
        secmul *= 60

    return {"audio_file": audio_file, "caption": cap, "title": title, "duration": dur, "performer": performer, "thumb": thumb_name}

@app.post("/download_youtube_video")
async def download_youtube_video_endpoint(yt_request: YouTubeDownloadRequest):
    url = yt_request.url
    try:
        search = SearchVideos(f"{url}", offset=1, mode="dict", max_results=1)
        mi = search.result()
        mio = mi["search_result"]
        mo = mio[0]["link"]
        thum = mio[0]["title"]
        fridayz = mio[0]["id"]
        mio[0]["channel"]
        kekme = f"https://img.youtube.com/vi/{fridayz}/hqdefault.jpg"
        await asyncio.sleep(0.6)
        sedlyf = wget.download(kekme)
        opts = {
            "format": "best",
            "addmetadata": True,
            "key": "FFmpegMetadata",
            "prefer_ffmpeg": True,
            "geo_bypass": True,
            "nocheckcertificate": True,
            "postprocessors": [{"key": "FFmpegVideoConvertor", "preferedformat": "mp4"}],
            "outtmpl": "%(id)s.mp4",
            "logtostderr": False,
            "quiet": True,
        }
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url, download=True)
    except Exception as e:
        logger.error(f"Error downloading YouTube video: {e}")
        return {"error": str(e)}

    file_stark = f"{ytdl_data['id']}.mp4"
    capy = f"""**πšƒπ™Έπšƒπ™»π™΄ :** [{thum}]({mo})\n**πšπ™΄πš€πš„π™΄πš‚πšƒπ™΄π™³ π™±πšˆ :** {await bot_instance.get_me().mention}"""

    return {"video_file": file_stark, "caption": capy, "title": ytdl_data["title"], "duration": int(ytdl_data["duration"]), "thumb": sedlyf}

@app.post("/group_manager_action")
async def group_manager_action_endpoint(action_request: GroupManagerAction):
    chat_id = action_request.group_id
    action = action_request.action
    user_id = action_request.user_id
    time_val = action_request.time

    if action == "ban":
        await bot_instance.ban_chat_member(chat_id, user_id)
        return {"status": "User banned successfully"}
    elif action == "unban":
        await bot_instance.unban_chat_member(chat_id, user_id)
        return {"status": "User unbanned successfully"}
    elif action == "tban":
        until_date_val = extract_time(time_val)
        if until_date_val is None:
            return {"error": "Invalid time type specified. Expected m, h, or d, Got it: {time_val[-1]}"}
        await bot_instance.ban_chat_member(chat_id, user_id, until_date=until_date_val)
        return {"status": "User temporarily banned successfully"}
    elif action == "mute":
        await bot_instance.restrict_chat_member(chat_id, user_id, permissions=enums.ChatPermissions())
        return {"status": "User muted successfully"}
    elif action == "unmute":
        await bot_instance.restrict_chat_member(chat_id, user_id, permissions=enums.ChatPermissions(can_send_messages=True))
        return {"status": "User unmuted successfully"}
    elif action == "tmute":
        until_date_val = extract_time(time_val)
        if until_date_val is None:
            return {"error": "Invalid time type specified. Expected m, h, or d, Got it: {time_val[-1]}"}
        await bot_instance.restrict_chat_member(chat_id, user_id, permissions=enums.ChatPermissions(), until_date=until_date_val)
        return {"status": "User temporarily muted successfully"}
    elif action == "pin":
        await bot_instance.pin_chat_message(chat_id, action_request.message_id)
        return {"status": "Message pinned successfully"}
    elif action == "unpin":
        await bot_instance.unpin_chat_message(chat_id, action_request.message_id)
        return {"status": "Message unpinned successfully"}
    elif action == "purge":
        if action_request.message_id:
            await purge_messages(bot_instance, chat_id, action_request.message_id)
            return {"status": "Messages purged successfully"}
        else:
            return {"error": "Message ID is required for purge action"}
    else:
        return {"error": "Invalid action"}

async def purge_messages(client, chat_id, message_id):
    try:
        message_ids = []
        count_del_etion_s = 0
        if message_id:
            for a_s_message_id in range(message_id, message_id + 100):
                message_ids.append(a_s_message_id)
                if len(message_ids) == 100:
                    await client.delete_messages(chat_id=chat_id, message_ids=message_ids, revoke=True)
                    count_del_etion_s += len(message_ids)
                    message_ids = []
            if len(message_ids) > 0:
                await client.delete_messages(chat_id=chat_id, message_ids=message_ids, revoke=True)
                count_del_etion_s += len(message_ids)
    except Exception as e:
        logger.error(f"Error purging messages: {e}")
        return {"error": str(e)}

@app.post("/group_leave")
async def group_leave_endpoint(group_id: int):
    await bot_instance.leave_chat(group_id)
    return {"status": "Left the group successfully"}

@app.post("/group_disable")
async def group_disable_endpoint(group_id: int, reason: str = "No Reason"):
    await db.disable_chat(group_id, reason)
    temp.BANNED_CHATS.append(group_id)
    return {"status": "Group disabled successfully"}

@app.post("/group_enable")
async def group_enable_endpoint(group_id: int):
    await db.re_enable_chat(group_id)
    temp.BANNED_CHATS.remove(group_id)
    return {"status": "Group enabled successfully"}

@app.post("/get_user_info")
async def get_user_info_endpoint(user_id: int):
    user_info = await bot_instance.get_users(user_id)
    return {"user_info": user_info}

@app.post("/get_chat_info")
async def get_chat_info_endpoint(chat_id: int):
    chat_info = await bot_instance.get_chat(chat_id)
    return {"chat_info": chat_info}

@app.post("/send_photo")
async def send_photo_endpoint(chat_id: int, photo_url: str, caption: str = None):
    response = requests.get(photo_url)
    photo = BytesIO(response.content)
    photo.name = "photo.jpg"
    message = await bot_instance.send_photo(chat_id, photo, caption=caption)
    return {"message_id": message.id}

@app.post("/send_document")
async def send_document_endpoint(chat_id: int, document_url: str, caption: str = None):
    response = requests.get(document_url)
    document = BytesIO(response.content)
    document.name = "document.pdf"
    message = await bot_instance.send_document(chat_id, document, caption=caption)
    return {"message_id": message.id}

@app.post("/send_video")
async def send_video_endpoint(chat_id: int, video_url: str, caption: str = None):
    response = requests.get(video_url)
    video = BytesIO(response.content)
    video.name = "video.mp4"
    message = await bot_instance.send_video(chat_id, video, caption=caption)
    return {"message_id": message.id}

@app.post("/send_audio")
async def send_audio_endpoint(chat_id: int, audio_url: str, caption: str = None):
    response = requests.get(audio_url)
    audio = BytesIO(response.content)
    audio.name = "audio.mp3"
    message = await bot_instance.send_audio(chat_id, audio, caption=caption)
    return {"message_id": message.id}

@app.post("/send_voice")
async def send_voice_endpoint(chat_id: int, voice_url: str, caption: str = None):
    response = requests.get(voice_url)
    voice = BytesIO(response.content)
    voice.name = "voice.ogg"
    message = await bot_instance.send_voice(chat_id, voice, caption=caption)
    return {"message_id": message.id}

@app.post("/send_sticker")
async def send_sticker_endpoint(chat_id: int, sticker_url: str):
    response = requests.get(sticker_url)
    sticker = BytesIO(response.content)
    sticker.name = "sticker.webp"
    message = await bot_instance.send_sticker(chat_id, sticker)
    return {"message_id": message.id}

@app.post("/send_animation")
async def send_animation_endpoint(chat_id: int, animation_url: str, caption: str = None):
    response = requests.get(animation_url)
    animation = BytesIO(response.content)
    animation.name = "animation.gif"
    message = await bot_instance.send_animation(chat_id, animation, caption=caption)
    return {"message_id": message.id}

@app.post("/send_video_note")
async def send_video_note_endpoint(chat_id: int, video_note_url: str):
    response = requests.get(video_note_url)
    video_note = BytesIO(response.content)
    video_note.name = "video_note.mp4"
    message = await bot_instance.send_video_note(chat_id, video_note)
    return {"message_id": message.id}

@app.post("/send_location")
async def send_location_endpoint(chat_id: int, latitude: float, longitude: float):
    message = await bot_instance.send_location(chat_id, latitude, longitude)
    return {"message_id": message.id}

@app.post("/send_contact")
async def send_contact_endpoint(chat_id: int, phone_number: str, first_name: str, last_name: str = None):
    message = await bot_instance.send_contact(chat_id, phone_number, first_name, last_name=last_name)
    return {"message_id": message.id}

@app.post("/send_dice")
async def send_dice_endpoint(chat_id: int):
    message = await bot_instance.send_dice(chat_id)
    return {"message_id": message.id}

@app.post("/send_poll")
async def send_poll_endpoint(chat_id: int, question: str, options: list, is_anonymous: bool = False, type: str = "regular", allows_multiple_answers: bool = False, correct_option_id: int = None, explanation: str =