-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.py
More file actions
1289 lines (1123 loc) Β· 49.7 KB
/
Main.py
File metadata and controls
1289 lines (1123 loc) Β· 49.7 KB
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import io
import json
import logging
import time
import asyncio
import signal
import sys
from contextlib import asynccontextmanager
from typing import Dict, Any, Optional
from urllib.parse import urlsplit
try:
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse, PlainTextResponse
from fastapi.middleware.cors import CORSMiddleware
FASTAPI_AVAILABLE = True
except Exception:
# Minimal Safe Stubs For FastAPI Types Used Elsewhere In This Module.
FASTAPI_AVAILABLE = False
class HTTPException(Exception):
def __init__(self, status_code=500, detail=None):
super().__init__(detail)
self.status_code = status_code
self.detail = detail
class PlainTextResponse(str):
pass
class JSONResponse(dict):
def __init__(self, content=None, status_code=200):
super().__init__(content or {})
self.status_code = status_code
class CORSMiddleware:
def __init__(self, *args, **kwargs):
pass
class FastAPI:
def __init__(self, *args, **kwargs):
# Store Simple Route Lists; Decorators Will Be No-Ops
self._routes = {}
def get(self, path, **kwargs):
def _decorator(fn):
self._routes[path] = fn
return fn
return _decorator
def post(self, path, **kwargs):
def _decorator(fn):
self._routes[path] = fn
return fn
return _decorator
def exception_handler(self, exc_type):
def _decorator(fn):
return fn
return _decorator
def add_middleware(self, *args, **kwargs):
return None
try:
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, InputFile
from telegram.ext import (
Application,
ApplicationBuilder,
CommandHandler,
CallbackQueryHandler,
ContextTypes,
)
from telegram.error import TelegramError, Conflict, NetworkError
TELEGRAM_AVAILABLE = True
except Exception:
TELEGRAM_AVAILABLE = False
# Minimal Safe Stubs For Telegram Types Used In This Module.
class TelegramError(Exception):
pass
class Conflict(TelegramError):
pass
class NetworkError(TelegramError):
pass
class Update:
pass
class InlineKeyboardButton:
def __init__(self, text, callback_data=None):
self.text = text
self.callback_data = callback_data
class InlineKeyboardMarkup:
def __init__(self, keyboard):
self.inline_keyboard = keyboard
class InputFile:
def __init__(self, fileobj):
self.file = fileobj
class ContextTypes:
DEFAULT_TYPE = object
class CommandHandler:
def __init__(self, *args, **kwargs):
pass
class CallbackQueryHandler:
def __init__(self, *args, **kwargs):
pass
class _DummyBot:
async def get_updates(self, *a, **k):
raise RuntimeError("Telegram Package Not Installed")
async def get_me(self):
raise RuntimeError("Telegram Package Not Installed")
class _DummyUpdater:
def __init__(self):
self.running = False
async def start_polling(self, *a, **k):
self.running = True
async def stop(self):
self.running = False
class Application:
def __init__(self):
self.bot = _DummyBot()
self.updater = _DummyUpdater()
async def initialize(self):
return None
async def start(self):
return None
async def stop(self):
return None
async def shutdown(self):
return None
def add_handler(self, handler):
return None
class ApplicationBuilder:
def __init__(self):
pass
def token(self, *a, **k):
return self
def connect_timeout(self, *a, **k):
return self
def read_timeout(self, *a, **k):
return self
def write_timeout(self, *a, **k):
return self
def pool_timeout(self, *a, **k):
return self
def get_updates_connect_timeout(self, *a, **k):
return self
def get_updates_read_timeout(self, *a, **k):
return self
def concurrent_updates(self, *a, **k):
return self
def build(self):
return Application()
# ---------- Production Logging ----------
def setup_logging():
"""Setup Production-Grade Logging"""
log_level = os.getenv("LOG_LEVEL", "INFO").upper()
# Create Logs Directory If It Doesn't Exist
log_dir = "/app/logs"
if not os.path.exists(log_dir):
os.makedirs(log_dir, exist_ok=True)
# Configure Logging Format
log_format = "%(asctime)s | %(levelname)s | %(name)s | %(process)d | %(message)s"
logging.basicConfig(
level=getattr(logging, log_level, logging.INFO),
format=log_format,
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler(f"{log_dir}/app.log", mode="a")
]
)
# Set Specific Loggers
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("telegram").setLevel(logging.INFO)
return logging.getLogger("TeleIdentityBot")
log = setup_logging()
# ---------- Developer Signature ----------
SIGNATURE = os.getenv("BOT_SIGNATURE", "i8o8i Developer")
APP_VERSION = "2.1.0"
WEBHOOK_ENDPOINT = "/webhook"
def build_webhook_url() -> str:
"""Build A Stable Webhook URL From WEBHOOK_URL Environment Variable."""
base_url = WEBHOOK_BASE_URL.rstrip("/")
if not base_url:
return ""
if base_url.endswith(WEBHOOK_ENDPOINT):
return base_url
return f"{base_url}{WEBHOOK_ENDPOINT}"
# ---------- Configuration And Validation ----------
def validate_environment():
"""Validate Required Environment Variables"""
required_vars = ["TELEGRAM_BOT_TOKEN", "WEBHOOK_URL"]
missing_vars = [var for var in required_vars if not os.getenv(var)]
if missing_vars:
error_msg = f"Missing Required Environment Variables: {', '.join(missing_vars)}"
log.error(error_msg)
raise RuntimeError(error_msg)
# Validate Bot Token Format
bot_token = os.getenv("TELEGRAM_BOT_TOKEN")
if not bot_token or len(bot_token.split(":")) != 2:
raise RuntimeError("Invalid TELEGRAM_BOT_TOKEN Format")
webhook_url = build_webhook_url()
parsed_webhook_url = urlsplit(webhook_url)
if parsed_webhook_url.scheme not in ("http", "https") or not parsed_webhook_url.netloc:
raise RuntimeError("WEBHOOK_URL Must Be A Valid Absolute HTTP/HTTPS URL")
log.info("Environment Validation Passed")
BOT_TOKEN = None
APP_ENV = os.getenv("APP_ENV", "production")
MAX_RETRIES = int(os.getenv("MAX_RETRIES", "3"))
# Separate Timeouts For Different Operations
# Regular API Calls (get_me, send_message, etc.) - Should Be Reasonably Short
REQUEST_TIMEOUT = int(os.getenv("REQUEST_TIMEOUT", "30"))
# If Set To A Truthy Value ("1", "true", "yes"), The Health Endpoint Will Skip
# Calling The Telegram API. This Is Useful In Network-Restricted Environments Where
# Outbound Access To Telegram May Be Blocked But You Still Want The Service To Be
# Considered "Healthy" By The Orchestration Platform
SKIP_TELEGRAM_HEALTH_CHECK = os.getenv("SKIP_TELEGRAM_HEALTH_CHECK", "false").lower() in ("1", "true", "yes")
# Sync With Docker/Coolify Defaults
PORT = int(os.getenv("PORT", "5860"))
WEBHOOK_BASE_URL = os.getenv("WEBHOOK_URL", "").strip()
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
# ---------- Global State ----------
application: Optional[Application] = None
shutdown_event = asyncio.Event()
# ---------- Graceful Shutdown Handler ----------
def signal_handler(signum, frame):
"""Handle Shutdown Signals Gracefully"""
log.info(f"Received Signal {signum}, Initiating Graceful Shutdown...")
try:
shutdown_event.set()
except Exception:
pass
# Register Signal Handlers
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
# ---------- Error Handling Decorator ----------
def handle_errors(func):
"""Decorator For Error Handling In Commands"""
async def wrapper(update: Update, context: ContextTypes.DEFAULT_TYPE):
try:
return await func(update, context)
except TelegramError as e:
log.error(f"Telegram Error In {func.__name__}: {e}")
try:
await update.effective_message.reply_text(
f"β οΈ <b>Telegram API Error</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π§ <b>Issue:</b> API Communication Problem\n"
f"π <b>Solution:</b> Please Try Again In A Moment\n"
f"π± <b>Status:</b> Temporary Issue\n\n"
f"π‘ <i>If This Persists, Telegram May Be Having Issues!</i>",
parse_mode="HTML"
)
except:
pass
except Exception as e:
log.error(f"Unexpected Error In {func.__name__}: {e}")
try:
await update.effective_message.reply_text(
f"β <b>Unexpected Error</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π« <b>Issue:</b> Something Went Wrong\n"
f"π <b>Solution:</b> Please Try Again\n"
f"π οΈ <b>Status:</b> Error Logged For Review\n\n"
f"π‘ <i>Our Team Will Investigate This Issue!</i>",
parse_mode="HTML"
)
except:
pass
return wrapper
# ---------- Enhanced Command Handlers ----------
@handle_errors
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
kb = InlineKeyboardMarkup([
[InlineKeyboardButton("π Your ID", callback_data="id"),
InlineKeyboardButton("β©οΈ Reply ID", callback_data="replyid")],
[InlineKeyboardButton("π¬ Chat/Group ID", callback_data="chatid"),
InlineKeyboardButton("π·οΈ Chat Details", callback_data="chatinfo")],
[InlineKeyboardButton("π Admins", callback_data="admins"),
InlineKeyboardButton("π₯ Member Count", callback_data="members")],
[InlineKeyboardButton("π§΅ Topic ID", callback_data="topicid"),
InlineKeyboardButton("π§Ύ Message Info", callback_data="messageinfo")],
[InlineKeyboardButton("βΉοΈ User Info", callback_data="userinfo"),
InlineKeyboardButton("ποΈ File ID", callback_data="fileid")],
[InlineKeyboardButton("π¦ Export JSON", callback_data="export"),
InlineKeyboardButton("π Ping Test", callback_data="ping")],
[InlineKeyboardButton("π Help & Commands", callback_data="help")]
])
user_name = update.effective_user.first_name if update.effective_user else "User"
text = (
f"π <b>Telegram ID Bot</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π Hello <b>{user_name}</b>! I Can Help You Discover IDs and Chat Information.\n\n"
f"β¨ <b>Quick Actions:</b>\n"
f"π Get Your Telegram ID\n"
f"β©οΈ Extract IDs From Replied Messages\n"
f"π¬ Find Chat/Group IDs\n"
f"π·οΈ Inspect Detailed Chat Metadata\n"
f"π§΅ Discover Topic IDs\n"
f"π§Ύ Capture Message IDs Instantly\n"
f"π List Administrators\n"
f"π Export Chat Data\n\n"
f"π± <i>Choose An Option Below Or Use Commands Directly!</i>"
f"\n\nβ <i>{SIGNATURE}</i>"
)
await update.effective_message.reply_text(text, reply_markup=kb, parse_mode="HTML")
@handle_errors
async def help_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
help_text = (
f"π <b>Command Reference</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π <code>/start</code> β Show Main Menu\n"
f"π <code>/help</code> β Display This Help\n\n"
f"π <b>ID Commands:</b>\n"
f"π <code>/id</code> β Your Telegram ID\n"
f"β©οΈ <code>/replyid</code> β ID Of Replied User / Sender Chat\n"
f"π¬ <code>/chatid</code> β Current Chat/Group ID\n"
f"π·οΈ <code>/chatinfo</code> β Detailed Chat Metadata\n"
f"π§΅ <code>/topicid</code> β Topic ID (In Threads)\n\n"
f"π₯ <b>Group Info:</b>\n"
f"π <code>/members</code> β Member Count\n"
f"π <code>/admins</code> β List Administrators\n\n"
f"π± <b>Utilities:</b>\n"
f"π§Ύ <code>/messageid</code> β Message / Reply / Topic IDs\n"
f"βΉοΈ <code>/userinfo</code> β Detailed User Info\n"
f"π¦ <code>/export</code> β Export Chat Data (JSON)\n"
f"π <code>/ping</code> β Test Bot Response Time\n"
f"ποΈ <code>/fileid</code> β Get Media File ID\n\n"
f"π‘ <i>Tip: Use The Buttons Above For Quick Access!</i>"
)
# Append Signature To Help
help_text = help_text + f"\n\nβ <i>{SIGNATURE}</i>"
await update.effective_message.reply_text(help_text, parse_mode="HTML")
@handle_errors
async def cmd_id(update: Update, context: ContextTypes.DEFAULT_TYPE):
u = update.effective_user
await update.effective_message.reply_text(
f"π <b>Your Telegram ID</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π€ <b>User:</b> {u.full_name}\n"
f"π’ <b>ID:</b> <code>{u.id}</code>\n\n"
f"π‘ <i>Copy The ID by Tapping On It!</i>",
parse_mode="HTML"
)
@handle_errors
async def cmd_chatid(update: Update, context: ContextTypes.DEFAULT_TYPE):
c = update.effective_chat
# Get Chat Icon Based On Type
chat_icons = {
"private": "π€",
"group": "π₯",
"supergroup": "π’",
"channel": "π’"
}
icon = chat_icons.get(c.type, "π¬")
chat_name = c.title or c.first_name or "Unknown"
await update.effective_message.reply_text(
f"{icon} <b>Chat Information</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π <b>Name:</b> {chat_name}\n"
f"π’ <b>Chat ID:</b> <code>{c.id}</code>\n"
f"π <b>Type:</b> {c.type.title()}\n\n"
f"π‘ <i>Tap The ID To Copy It!</i>",
parse_mode="HTML"
)
@handle_errors
async def cmd_replyid(update: Update, context: ContextTypes.DEFAULT_TYPE):
msg = update.effective_message
replied_msg = msg.reply_to_message
if not replied_msg:
await msg.reply_text(
f"β©οΈ <b>Reply ID Finder</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"β <b>No Reply Found</b>\n\n"
f"π± Reply To Any User, Bot, Or Anonymous Admin Message\n"
f"π Then Send <code>/replyid</code> Again\n\n"
f"π‘ <i>This Is The Fastest Way To Capture Someone Else's ID!</i>",
parse_mode="HTML"
)
return
sender = replied_msg.from_user
sender_chat = replied_msg.sender_chat
reply_to_message_id = replied_msg.reply_to_message.message_id if replied_msg.reply_to_message else None
topic_id = replied_msg.message_thread_id if replied_msg.is_topic_message else None
if sender:
username = f"@{sender.username}" if sender.username else "β No username"
await msg.reply_text(
f"β©οΈ <b>Reply Target Information</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π€ <b>Name:</b> {sender.full_name}\n"
f"π <b>User ID:</b> <code>{sender.id}</code>\n"
f"π <b>Username:</b> {username}\n"
f"π€ <b>Bot:</b> {'Yes' if sender.is_bot else 'No'}\n"
f"βοΈ <b>Message ID:</b> <code>{replied_msg.message_id}</code>\n"
f"β©οΈ <b>Replying To:</b> <code>{reply_to_message_id}</code>\n"
f"π§΅ <b>Topic ID:</b> <code>{topic_id}</code>\n\n"
f"π‘ <i>Tap The Numeric IDs To Copy Them.</i>",
parse_mode="HTML"
)
return
if sender_chat:
sender_chat_name = sender_chat.title or sender_chat.username or "Unknown"
await msg.reply_text(
f"β©οΈ <b>Sender Chat Information</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π’ <b>Name:</b> {sender_chat_name}\n"
f"π <b>Chat ID:</b> <code>{sender_chat.id}</code>\n"
f"π·οΈ <b>Type:</b> {sender_chat.type.title()}\n"
f"βοΈ <b>Message ID:</b> <code>{replied_msg.message_id}</code>\n"
f"π§΅ <b>Topic ID:</b> <code>{topic_id}</code>\n\n"
f"π‘ <i>Useful For Anonymous Admin Or Channel-Linked Messages.</i>",
parse_mode="HTML"
)
return
await msg.reply_text(
f"β©οΈ <b>Reply Target Information</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"β οΈ <b>Sender Data Unavailable</b>\n\n"
f"Telegram Did Not Include User Or Sender Chat Details For That Message.\n"
f"βοΈ <b>Message ID:</b> <code>{replied_msg.message_id}</code>\n\n"
f"π‘ <i>Try Again With A Regular User Or Channel Message.</i>",
parse_mode="HTML"
)
@handle_errors
async def cmd_chatinfo(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat = update.effective_chat
try:
full_chat = await context.bot.get_chat(chat.id)
except Exception:
full_chat = chat
try:
member_count = await context.bot.get_chat_member_count(chat.id)
except Exception:
member_count = None
chat_name = full_chat.title or full_chat.first_name or "Unknown"
username = f"@{full_chat.username}" if getattr(full_chat, "username", None) else "β No public username"
description = getattr(full_chat, "description", None) or getattr(full_chat, "bio", None) or "Not available"
invite_link = getattr(full_chat, "invite_link", None) or "Not available"
linked_chat_id = getattr(full_chat, "linked_chat_id", None)
member_line = f"π₯ <b>Members:</b> <code>{member_count:,}</code>\n" if member_count is not None else ""
linked_chat_line = f"π <b>Linked Chat ID:</b> <code>{linked_chat_id}</code>\n" if linked_chat_id else ""
await update.effective_message.reply_text(
f"π·οΈ <b>Detailed Chat Info</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π <b>Name:</b> {chat_name}\n"
f"π <b>Chat ID:</b> <code>{full_chat.id}</code>\n"
f"π <b>Type:</b> {full_chat.type.title()}\n"
f"π <b>Username:</b> {username}\n"
f"{member_line}"
f"{linked_chat_line}"
f"π§Ύ <b>Description:</b> {description}\n"
f"π <b>Invite Link:</b> <code>{invite_link}</code>\n\n"
f"π‘ <i>Handy For Group Setup, Migration, And Support Work.</i>",
parse_mode="HTML"
)
@handle_errors
async def cmd_topicid(update: Update, context: ContextTypes.DEFAULT_TYPE):
msg = update.effective_message
chat = update.effective_chat
if chat.type in ["supergroup", "group"]:
if msg.is_topic_message:
thread_id = msg.message_thread_id
await msg.reply_text(
f"π§΅ <b>Topic Information</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π¬ <b>Chat:</b> {chat.title or 'Unknown'}\n"
f"π’ <b>Topic ID:</b> <code>{thread_id}</code>\n\n"
f"β
<i>This Message Is In A Topic Thread!</i>",
parse_mode="HTML",
)
else:
await msg.reply_text(
f"π§΅ <b>Topic Status</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"β οΈ <b>No Topic Found</b>\n\n"
f"π This Chat Doesn't Have Topics Enabled\n"
f"π Or This Message Isn't In A Topic Thread\n\n"
f"π‘ <i>Topics Are Available In Supergroups Only!</i>",
parse_mode="HTML"
)
else:
await msg.reply_text(
f"π§΅ <b>Topic Feature</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"β <b>Not Available</b>\n\n"
f"π± Topics Only Work In <b>Supergroups</b>\n"
f"π Convert Your Group To Supergroup First\n\n"
f"π‘ <i>Private Chats Don't Support Topics!</i>",
parse_mode="HTML"
)
@handle_errors
async def cmd_members(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat = update.effective_chat
try:
count = await context.bot.get_chat_member_count(chat.id)
# Member Count Visualization
if count < 10:
status = "π₯ Small Group"
elif count < 100:
status = "ποΈ Medium Group"
elif count < 1000:
status = "π’ Large Group"
else:
status = "π Huge Community"
await update.effective_message.reply_text(
f"π₯ <b>Member Statistics</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π <b>Total Members:</b> <code>{count:,}</code>\n"
f"π·οΈ <b>Status:</b> {status}\n"
f"π¬ <b>Chat:</b> {chat.title or 'Unknown'}\n\n"
f"π <i>Live Member Count Updated!</i>",
parse_mode="HTML"
)
except Exception as e:
log.error(f"Error Getting Member Count: {e}")
await update.effective_message.reply_text(
f"π₯ <b>Member Count</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"β <b>Access Denied</b>\n\n"
f"π Cannot Fetch Member Count\n"
f"π± Bot Might Lack Permissions\n"
f"π Try In A Group Where I'm Admin\n\n"
f"π‘ <i>This Works Best In Public Groups!</i>",
parse_mode="HTML"
)
@handle_errors
async def cmd_admins(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat = update.effective_chat
# Private Chats Don't Have Administrators
if chat.type == "private":
await update.effective_message.reply_text(
f"π <b>Administrators</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"β <b>Not Applicable</b>\n\n"
f"π Private Chats Don't Have Administrators\n"
f"π± Only Groups And Channels Have Admins\n"
f"π Try In A Group Chat Instead\n\n"
f"π‘ <i>Use /chatid To Get Chat Info!</i>",
parse_mode="HTML"
)
return
try:
admins = await context.bot.get_chat_administrators(chat.id)
if not admins:
await update.effective_message.reply_text(
f"π <b>Administrators</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"β <b>No Admins Found</b>\n\n"
f"π€ This Is Unusual...\n"
f"π¬ <i>Every Group Should Have Admins!</i>",
parse_mode="HTML"
)
return
admin_list = []
owner_count = 0
admin_count = 0
for admin in admins:
user = admin.user
if admin.status == "creator":
admin_list.append(f"π {user.mention_html()} <i>(Owner)</i>")
owner_count += 1
else:
admin_list.append(f"π‘οΈ {user.mention_html()}")
admin_count += 1
admin_text = "\n".join(admin_list)
total_admins = len(admins)
await update.effective_message.reply_text(
f"π <b>Chat Administrators</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π <b>Total:</b> {total_admins} administrator{'s' if total_admins != 1 else ''}\n"
f"π <b>Owners:</b> {owner_count}\n"
f"π‘οΈ <b>Admins:</b> {admin_count}\n\n"
f"<b>Admin List:</b>\n{admin_text}\n\n"
f"π‘ <i>Tap Names To View Profiles!</i>",
parse_mode="HTML"
)
except Exception as e:
log.error(f"Error getting admins: {e}")
await update.effective_message.reply_text(
f"π <b>Administrators</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"β <b>Access Denied</b>\n\n"
f"π Cannot Fetch Admin List\n"
f"π± Bot Might Lack Permissions\n"
f"π Make Me Admin to See Full List\n\n"
f"π‘ <i>Some Groups Restrict This Info!</i>",
parse_mode="HTML"
)
def _chat_snapshot(update: Update) -> Dict[str, Any]:
chat = update.effective_chat
user = update.effective_user
msg = update.effective_message
return {
"timestamp": time.time(),
"chat": {
"id": chat.id,
"type": chat.type,
"title": chat.title,
"username": chat.username,
"first_name": chat.first_name,
"last_name": chat.last_name,
"bio": getattr(chat, "bio", None),
"description": getattr(chat, "description", None),
"invite_link": getattr(chat, "invite_link", None),
},
"from_user": {
"id": user.id if user else None,
"is_bot": user.is_bot if user else None,
"username": user.username if user else None,
"first_name": user.first_name if user else None,
"last_name": user.last_name if user else None,
"full_name": user.full_name if user else None,
"language_code": user.language_code if user else None,
} if user else None,
"message": {
"message_id": msg.message_id if msg else None,
"text": msg.text if msg else None,
"caption": msg.caption if msg else None,
"media_group_id": msg.media_group_id if msg else None,
"has_protected_content": msg.has_protected_content if msg else None,
"date": msg.date.isoformat() if msg and msg.date else None,
"edit_date": msg.edit_date.isoformat() if msg and msg.edit_date else None,
"entities": [e.to_dict() for e in msg.entities] if msg and msg.entities else None,
"reply_to_message_id": msg.reply_to_message.message_id if msg and msg.reply_to_message else None,
} if msg else None,
}
@handle_errors
async def cmd_export(update: Update, context: ContextTypes.DEFAULT_TYPE):
try:
# Show progress Message
progress_msg = await update.effective_message.reply_text(
f"π¦ <b>Exporting Chat Data...</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"β³ <i>Gathering Chat Information...</i>",
parse_mode="HTML"
)
payload = _chat_snapshot(update)
# Enhanced Export With Metadata
export_data = {
"export_info": {
"generated_by": f"Telegram ID Bot v2.0.0 β {SIGNATURE}",
"export_date": time.strftime("%Y-%m-%d %H:%M:%S UTC"),
"export_timestamp": time.time(),
},
"data": payload
}
buf = io.BytesIO(json.dumps(export_data, indent=2, ensure_ascii=False).encode())
timestamp = time.strftime("%Y%m%d_%H%M%S")
buf.name = f"Chat_Export_{timestamp}.json"
await progress_msg.edit_text(
f"π¦ <b>Export Complete!</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"β
<b>Status:</b> Ready For Download\n"
f"π <b>Format:</b> JSON\n"
f"π <b>Generated:</b> {time.strftime('%H:%M:%S')}\n\n"
f"π₯ <i>Sending File...</i>",
parse_mode="HTML"
)
await update.effective_message.reply_document(
InputFile(buf),
caption=(
f"π <b>Chat Data Export</b>\n\n"
f"πΎ Complete Chat Information In JSON Format\n"
f"π All Sensitive Data Included\n"
f"β‘ Generated Instantly\n\n"
f"π‘ <i>Use This Data For Backups Or Analysis!</i>"
),
parse_mode="HTML"
)
# Delete Progress Message
await progress_msg.delete()
except Exception as e:
log.error(f"Error Exporting Data: {e}")
await update.effective_message.reply_text(
f"π¦ <b>Export Failed</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"β <b>Error:</b> Could Not Export Data\n"
f"π§ <b>Reason:</b> Technical Error\n"
f"π <b>Solution:</b> Try Again In A Moment\n\n"
f"π‘ <i>If Issue Persists, Contact Support!</i>",
parse_mode="HTML"
)
@handle_errors
async def cmd_userinfo(update: Update, context: ContextTypes.DEFAULT_TYPE):
u = update.effective_user
# User Status Indicators
bot_status = "π€ Bot" if u.is_bot else "π€ Human"
username_display = f"@{u.username}" if u.username else "β No username"
language_display = u.language_code.upper() if u.language_code else "π Unknown"
# Premium Status (if Available)
premium_status = ""
if hasattr(u, 'is_premium') and u.is_premium:
premium_status = "β Premium User\n"
info = (
f"βΉοΈ <b>User Information</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π€ <b>Name:</b> {u.full_name}\n"
f"π <b>ID:</b> <code>{u.id}</code>\n"
f"π <b>Username:</b> {username_display}\n"
f"π <b>Language:</b> {language_display}\n"
f"π° <b>Type:</b> {bot_status}\n"
f"{premium_status}\n"
f"π <b>Checked:</b> {time.strftime('%H:%M:%S')}\n\n"
f"π‘ <i>All Your Telegram Details In One Place!</i>"
)
await update.effective_message.reply_text(info, parse_mode="HTML")
@handle_errors
async def cmd_messageid(update: Update, context: ContextTypes.DEFAULT_TYPE):
msg = update.effective_message
chat = update.effective_chat
reply_to_message_id = msg.reply_to_message.message_id if msg.reply_to_message else "Not a reply"
topic_id = msg.message_thread_id if msg.is_topic_message else "Not in a topic"
sender_chat_id = msg.sender_chat.id if msg.sender_chat else "Not sent as chat"
await msg.reply_text(
f"π§Ύ <b>Message Information</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"βοΈ <b>Message ID:</b> <code>{msg.message_id}</code>\n"
f"π¬ <b>Chat ID:</b> <code>{chat.id}</code>\n"
f"β©οΈ <b>Reply To ID:</b> <code>{reply_to_message_id}</code>\n"
f"π§΅ <b>Topic ID:</b> <code>{topic_id}</code>\n"
f"π’ <b>Sender Chat ID:</b> <code>{sender_chat_id}</code>\n\n"
f"π‘ <i>Useful For Topic Routing, Logging, And Bot Automations.</i>",
parse_mode="HTML"
)
@handle_errors
async def cmd_ping(update: Update, context: ContextTypes.DEFAULT_TYPE):
start = time.time()
msg = await update.effective_message.reply_text(
f"π <b>Testing Connection...</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"β³ <i>Measuring Response Time...</i>"
)
latency = (time.time() - start) * 1000
# Latency Status
if latency < 100:
status = "π’ Excellent"
emoji = "β‘"
elif latency < 300:
status = "π‘ Good"
emoji = "π"
elif latency < 500:
status = "π Fair"
emoji = "β οΈ"
else:
status = "π΄ Slow"
emoji = "π"
await msg.edit_text(
f"π <b>Ping Test Results</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"{emoji} <b>Response Time:</b> <code>{latency:.2f} ms</code>\n"
f"π <b>Status:</b> {status}\n"
f"π <b>Tested:</b> {time.strftime('%H:%M:%S')}\n\n"
f"β
<i>Bot Is Responding Normally!</i>",
parse_mode="HTML"
)
@handle_errors
async def cmd_fileid(update: Update, context: ContextTypes.DEFAULT_TYPE):
msg = update.effective_message
file_id = None
file_type = None
file_size = None
if msg.reply_to_message:
replied_msg = msg.reply_to_message
if replied_msg.sticker:
file_id = replied_msg.sticker.file_id
file_type = "π Sticker"
file_size = getattr(replied_msg.sticker, 'file_size', None)
elif replied_msg.photo:
file_id = replied_msg.photo[-1].file_id
file_type = "πΌοΈ Photo"
file_size = getattr(replied_msg.photo[-1], 'file_size', None)
elif replied_msg.animation:
file_id = replied_msg.animation.file_id
file_type = "ποΈ Animation"
file_size = getattr(replied_msg.animation, 'file_size', None)
elif replied_msg.document:
file_id = replied_msg.document.file_id
file_type = f"π Document ({replied_msg.document.file_name or 'Unknown'})"
file_size = getattr(replied_msg.document, 'file_size', None)
elif replied_msg.video:
file_id = replied_msg.video.file_id
file_type = "π₯ Video"
file_size = getattr(replied_msg.video, 'file_size', None)
elif replied_msg.video_note:
file_id = replied_msg.video_note.file_id
file_type = "πΉ Video Note"
file_size = getattr(replied_msg.video_note, 'file_size', None)
elif replied_msg.audio:
file_id = replied_msg.audio.file_id
file_type = "π΅ Audio"
file_size = getattr(replied_msg.audio, 'file_size', None)
elif replied_msg.voice:
file_id = replied_msg.voice.file_id
file_type = "π€ Voice Message"
file_size = getattr(replied_msg.voice, 'file_size', None)
if file_id:
size_text = f"\nπ <b>Size:</b> {file_size:,} bytes" if file_size else ""
await msg.reply_text(
f"ποΈ <b>File Information</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"π <b>Type:</b> {file_type}\n"
f"π <b>File ID:</b>\n<code>{file_id}</code>{size_text}\n\n"
f"π‘ <i>Tap The ID To Copy It!\n"
f"Use This ID To Send The Same File.</i>",
parse_mode="HTML"
)
else:
await msg.reply_text(
f"ποΈ <b>File ID Extractor</b>\n"
f"βββββββββββββββββββββββββ\n\n"
f"β <b>No Media Found</b>\n\n"
f"π± <b>How To Use:</b>\n"
f"1οΈβ£ Find A Message With Media\n"
f"2οΈβ£ Reply To It With <code>/fileid</code>\n"
f"3οΈβ£ Get The Unique File ID!\n\n"
f"π― <b>Supported Types:</b>\n"
f"πΌοΈ Photos β’ π₯ Videos β’ π Documents\n"
f"π Stickers β’ π΅ Audio β’ π€ Voice\n"
f"ποΈ Animations β’ πΉ Video Notes\n\n"
f"π‘ <i>File IDs Never Expire!</i>",
parse_mode="HTML"
)
@handle_errors
async def on_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
data = update.callback_query.data
await update.callback_query.answer()
if data == "id":
await cmd_id(update, context)
elif data == "replyid":
await cmd_replyid(update, context)
elif data == "chatid":
await cmd_chatid(update, context)
elif data == "chatinfo":
await cmd_chatinfo(update, context)
elif data == "admins":
await cmd_admins(update, context)
elif data == "members":
await cmd_members(update, context)
elif data == "export":
await cmd_export(update, context)
elif data == "userinfo":
await cmd_userinfo(update, context)
elif data == "messageinfo":
await cmd_messageid(update, context)
elif data == "fileid":
await cmd_fileid(update, context)
elif data == "help":
await help_cmd(update, context)
elif data == "topicid":
await cmd_topicid(update, context)
elif data == "ping":
await cmd_ping(update, context)
# ---------- Handler Registration ----------
def register_handlers(app: Application):
"""Register all bot handlers"""
handlers = [
CommandHandler("start", start),
CommandHandler("help", help_cmd),
CommandHandler("id", cmd_id),
CommandHandler("replyid", cmd_replyid),
CommandHandler("chatid", cmd_chatid),
CommandHandler("chatinfo", cmd_chatinfo),
CommandHandler("topicid", cmd_topicid),
CommandHandler("members", cmd_members),
CommandHandler("admins", cmd_admins),
CommandHandler("export", cmd_export),
CommandHandler("userinfo", cmd_userinfo),
CommandHandler("messageid", cmd_messageid),
CommandHandler("ping", cmd_ping),
CommandHandler("fileid", cmd_fileid),
CallbackQueryHandler(on_callback),
]
for handler in handlers:
app.add_handler(handler)
log.info(f"β
Registered {len(handlers)} Handlers")
# ---------- Application Lifespan ----------
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Manage Application LifeSpan With Proper Startup and Shutdown"""
global application
application_initialized = False
application_started = False
try: