-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcatbot.py
More file actions
3824 lines (3308 loc) · 195 KB
/
catbot.py
File metadata and controls
3824 lines (3308 loc) · 195 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
# MyCatBot - Telegram bot
# Copyright (C) 2025 R0X
# Licensed under the GNU General Public License v3.0
# See the LICENSE file for details.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# --- MyCatBot ---
import logging
import random
import os
import requests
import html
import sqlite3
import speedtest
import asyncio
import re
import io
import telegram
from typing import List, Tuple
from telegram import Update, User, Chat, constants, ChatPermissions, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.constants import ChatType, ParseMode, ChatMemberStatus
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, ApplicationHandlerStop, JobQueue
from telegram.error import TelegramError
from telegram.request import HTTPXRequest
from datetime import datetime, timezone, timedelta
from texts import (
MEOW_TEXTS, NAP_TEXTS, PLAY_TEXTS, TREAT_TEXTS, ZOOMIES_TEXTS,
JUDGE_TEXTS, ATTACK_TEXTS, KILL_TEXTS, PUNCH_TEXTS, SLAP_TEXTS,
BITE_TEXTS, HUG_TEXTS, FED_TEXTS, OWNER_WELCOME_TEXTS, LEAVE_TEXTS,
CANT_TARGET_OWNER_TEXTS, CANT_TARGET_SELF_TEXTS,
CANT_TARGET_OWNER_HUG_TEXTS, CANT_TARGET_SELF_HUG_TEXTS
)
# --- Logging Configuration ---
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("telegram.vendor.ptb_urllib3.urllib3").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
# --- Owner ID Configuration & Bot Start Time ---
OWNER_ID = None
BOT_START_TIME = datetime.now()
TENOR_API_KEY = None
DB_NAME = "catbot_data.db"
LOG_CHAT_ID = None
# --- Load configuration from environment variables ---
try:
owner_id_str = os.getenv("TELEGRAM_OWNER_ID")
if owner_id_str: OWNER_ID = int(owner_id_str); logger.info(f"Owner ID loaded: {OWNER_ID}")
else: raise ValueError("TELEGRAM_OWNER_ID environment variable not set or empty")
except (ValueError, TypeError) as e: logger.critical(f"CRITICAL: Invalid or missing TELEGRAM_OWNER_ID: {e}"); print(f"\n--- FATAL ERROR --- \nInvalid or missing TELEGRAM_OWNER_ID."); exit(1)
except Exception as e: logger.critical(f"CRITICAL: Unexpected error loading OWNER_ID: {e}"); print(f"\n--- FATAL ERROR --- \nUnexpected error loading OWNER_ID: {e}"); exit(1)
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
if not BOT_TOKEN: logger.critical("CRITICAL: TELEGRAM_BOT_TOKEN not set!"); print("\n--- FATAL ERROR --- \nTELEGRAM_BOT_TOKEN is not set."); exit(1)
TENOR_API_KEY = os.getenv("TENOR_API_KEY")
if not TENOR_API_KEY: logger.warning("WARNING: TENOR_API_KEY not set. Themed GIFs disabled.")
else: logger.info("Tenor API Key loaded. Themed GIFs enabled.")
log_chat_id_str = os.getenv("LOG_CHAT_ID")
if log_chat_id_str:
try:
LOG_CHAT_ID = int(log_chat_id_str)
logger.info(f"Log Chat ID loaded: {LOG_CHAT_ID}")
except ValueError:
logger.error(f"Invalid LOG_CHAT_ID: '{log_chat_id_str}' is not a valid integer. Will fallback to OWNER_ID for logs.")
LOG_CHAT_ID = None
else:
logger.info("LOG_CHAT_ID not set. Operational logs (globalbans/blacklist/sudo) will be sent to OWNER_ID if available.")
# --- Database Initialization ---
def init_db():
conn = None
try:
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
username TEXT,
first_name TEXT,
last_name TEXT,
language_code TEXT,
is_bot INTEGER,
last_seen TEXT
)
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_username ON users (username)")
cursor.execute("""
CREATE TABLE IF NOT EXISTS blacklist (
user_id INTEGER PRIMARY KEY,
reason TEXT,
banned_by_id INTEGER,
timestamp TEXT
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS sudo_users (
user_id INTEGER PRIMARY KEY,
added_by_id INTEGER NOT NULL,
timestamp TEXT NOT NULL
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS global_bans (
user_id INTEGER PRIMARY KEY,
reason TEXT,
banned_by_id INTEGER NOT NULL,
timestamp TEXT NOT NULL
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS bot_chats (
chat_id INTEGER PRIMARY KEY,
chat_title TEXT,
added_at TEXT NOT NULL,
enforce_gban INTEGER DEFAULT 1 NOT NULL
)
""")
conn.commit()
logger.info(f"Database '{DB_NAME}' initialized successfully (tables users, blacklist, sudo_users ensured).")
except sqlite3.Error as e:
logger.error(f"SQLite error during DB initialization: {e}", exc_info=True)
finally:
if conn:
conn.close()
# --- Blacklist Helper Functions ---
def add_to_blacklist(user_id: int, banned_by_id: int, reason: str | None = "No reason provided.") -> bool:
conn = None
try:
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
current_timestamp_iso = datetime.now(timezone.utc).isoformat()
cursor.execute(
"INSERT OR IGNORE INTO blacklist (user_id, reason, banned_by_id, timestamp) VALUES (?, ?, ?, ?)",
(user_id, reason, banned_by_id, current_timestamp_iso)
)
conn.commit()
return cursor.rowcount > 0
except sqlite3.Error as e:
logger.error(f"SQLite error adding user {user_id} to blacklist: {e}", exc_info=True)
return False
finally:
if conn:
conn.close()
def remove_from_blacklist(user_id: int) -> bool:
conn = None
try:
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute("DELETE FROM blacklist WHERE user_id = ?", (user_id,))
conn.commit()
return cursor.rowcount > 0
except sqlite3.Error as e:
logger.error(f"SQLite error removing user {user_id} from blacklist: {e}", exc_info=True)
return False
finally:
if conn:
conn.close()
def get_blacklist_reason(user_id: int) -> str | None:
conn = None
try:
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute("SELECT reason FROM blacklist WHERE user_id = ?", (user_id,))
row = cursor.fetchone()
if row:
return row[0]
return None
except sqlite3.Error as e:
logger.error(f"SQLite error checking blacklist reason for user {user_id}: {e}", exc_info=True)
return None
finally:
if conn:
conn.close()
def is_user_blacklisted(user_id: int) -> bool:
return get_blacklist_reason(user_id) is not None
# --- Blacklist Check Handler ---
async def check_blacklist_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if not update.message or not update.effective_user:
return
user = update.effective_user
if user.id == OWNER_ID:
return
if is_user_blacklisted(user.id):
user_mention_log = f"@{user.username}" if user.username else str(user.id)
message_text_preview = update.message.text[:50] if update.message.text else "[No text content]"
logger.info(f"User {user.id} ({user_mention_log}) is blacklisted. Silently ignoring and blocking interaction: '{message_text_preview}'")
raise ApplicationHandlerStop
# --- Sudo ---
def add_sudo_user(user_id: int, added_by_id: int) -> bool:
"""Adds a user to the sudo list."""
conn = None
try:
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
current_timestamp_iso = datetime.now(timezone.utc).isoformat()
cursor.execute(
"INSERT OR IGNORE INTO sudo_users (user_id, added_by_id, timestamp) VALUES (?, ?, ?)",
(user_id, added_by_id, current_timestamp_iso)
)
conn.commit()
return cursor.rowcount > 0
except sqlite3.Error as e:
logger.error(f"SQLite error adding sudo user {user_id}: {e}", exc_info=True)
return False
finally:
if conn:
conn.close()
def remove_sudo_user(user_id: int) -> bool:
"""Removes a user from the sudo list."""
conn = None
try:
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute("DELETE FROM sudo_users WHERE user_id = ?", (user_id,))
conn.commit()
return cursor.rowcount > 0
except sqlite3.Error as e:
logger.error(f"SQLite error removing sudo user {user_id}: {e}", exc_info=True)
return False
finally:
if conn:
conn.close()
def is_sudo_user(user_id: int) -> bool:
"""Checks if a user is on the sudo list (specifically, not checking if they are THE owner)."""
conn = None
try:
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute("SELECT 1 FROM sudo_users WHERE user_id = ?", (user_id,))
return cursor.fetchone() is not None
except sqlite3.Error as e:
logger.error(f"SQLite error checking sudo for user {user_id}: {e}", exc_info=True)
return False
finally:
if conn:
conn.close()
def is_privileged_user(user_id: int) -> bool:
"""Checks if the user is the Owner or a Sudo user."""
if user_id == OWNER_ID:
return True
return is_sudo_user(user_id)
# --- User logger ---
def update_user_in_db(user: User | None):
if not user:
return
conn = None
try:
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
current_timestamp_iso = datetime.now(timezone.utc).isoformat()
cursor.execute("""
INSERT INTO users (user_id, username, first_name, last_name, language_code, is_bot, last_seen)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
username = excluded.username,
first_name = excluded.first_name,
last_name = excluded.last_name,
language_code = excluded.language_code,
is_bot = excluded.is_bot,
last_seen = excluded.last_seen
""", (
user.id, user.username, user.first_name, user.last_name,
user.language_code, 1 if user.is_bot else 0, current_timestamp_iso
))
conn.commit()
except sqlite3.Error as e:
logger.error(f"SQLite error updating user {user.id} in users table: {e}", exc_info=True)
finally:
if conn:
conn.close()
def get_user_from_db_by_username(username_query: str) -> User | None:
if not username_query:
return None
conn = None
user_obj: User | None = None
try:
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
normalized_username = username_query.lstrip('@').lower()
cursor.execute(
"SELECT user_id, username, first_name, last_name, language_code, is_bot FROM users WHERE LOWER(username) = ?",
(normalized_username,)
)
row = cursor.fetchone()
if row:
user_obj = User(
id=row[0], username=row[1], first_name=row[2] or "",
last_name=row[3], language_code=row[4], is_bot=bool(row[5])
)
logger.info(f"User {username_query} found in DB with ID {row[0]}.")
except sqlite3.Error as e:
logger.error(f"SQLite error fetching user by username '{username_query}': {e}", exc_info=True)
finally:
if conn:
conn.close()
return user_obj
async def log_user_from_interaction(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if update.effective_user:
update_user_in_db(update.effective_user)
if update.message and update.message.reply_to_message and update.message.reply_to_message.from_user:
update_user_in_db(update.message.reply_to_message.from_user)
chat = update.effective_chat
if chat and chat.type in [ChatType.GROUP, ChatType.SUPERGROUP]:
if 'known_chats' not in context.bot_data:
context.bot_data['known_chats'] = set()
try:
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
known_ids = {row[0] for row in cursor.execute("SELECT chat_id FROM bot_chats")}
context.bot_data['known_chats'] = known_ids
logger.info(f"Loaded {len(known_ids)} known chats into cache.")
except sqlite3.Error as e:
logger.error(f"Could not preload known chats into cache: {e}")
if chat.id not in context.bot_data['known_chats']:
logger.info(f"Passively discovered and adding new chat to DB: {chat.title} ({chat.id})")
add_chat_to_db(chat.id, chat.title or f"Untitled Chat {chat.id}")
context.bot_data['known_chats'].add(chat.id)
def get_all_sudo_users_from_db() -> List[Tuple[int, str]]:
conn = None
sudo_list = []
try:
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute("SELECT user_id, timestamp FROM sudo_users ORDER BY timestamp DESC")
rows = cursor.fetchall()
for row in rows:
sudo_list.append((row[0], row[1]))
except sqlite3.Error as e:
logger.error(f"SQLite error fetching all sudo users: {e}", exc_info=True)
finally:
if conn:
conn.close()
return sudo_list
def parse_duration_to_timedelta(duration_str: str | None) -> timedelta | None:
if not duration_str:
return None
duration_str = duration_str.lower()
value = 0
unit = None
match = re.match(r"(\d+)([smhdw])", duration_str)
if match:
value = int(match.group(1))
unit = match.group(2)
else:
try:
value = int(duration_str)
unit = 'm'
except ValueError:
return None
if unit == 's': return timedelta(seconds=value)
elif unit == 'm': return timedelta(minutes=value)
elif unit == 'h': return timedelta(hours=value)
elif unit == 'd': return timedelta(days=value)
elif unit == 'w': return timedelta(weeks=value)
return None
async def _parse_mod_command_args(args: list[str]) -> tuple[str | None, str | None, str | None]:
target_arg: str | None = None
duration_arg: str | None = None
reason_list: list[str] = []
if not args: return None, None, None
target_arg = args[0]
remaining_args = args[1:]
if remaining_args:
potential_duration_td = parse_duration_to_timedelta(remaining_args[0])
if potential_duration_td is not None:
duration_arg = remaining_args[0]
reason_list = remaining_args[1:]
else:
reason_list = remaining_args
reason_str = " ".join(reason_list) if reason_list else None
return target_arg, duration_arg, reason_str
def parse_promote_args(args: list[str]) -> tuple[str | None, str | None]:
target_arg: str | None = None
custom_title_full: str | None = None
if not args:
return None, None
target_arg = args[0]
if len(args) > 1:
custom_title_full = " ".join(args[1:])
return target_arg, custom_title_full
async def send_safe_reply(update: Update, context: ContextTypes.DEFAULT_TYPE, text: str, **kwargs):
"""
Tries to reply to the message. If the original message is deleted,
it sends a new message to the chat instead of crashing.
"""
try:
await update.message.reply_text(text=text, **kwargs)
except telegram.error.BadRequest as e:
if "Message to be replied not found" in str(e):
logger.warning("Original message not found for reply. Sending as a new message.")
await context.bot.send_message(chat_id=update.effective_chat.id, text=text, **kwargs)
else:
raise e
async def _can_user_perform_action(
update: Update,
context: ContextTypes.DEFAULT_TYPE,
permission: str,
failure_message: str,
allow_bot_privileged_override: bool = True
) -> bool:
user = update.effective_user
chat = update.effective_chat
if allow_bot_privileged_override and is_privileged_user(user.id):
return True
try:
actor_chat_member = await context.bot.get_chat_member(chat.id, user.id)
if actor_chat_member.status == "creator":
return True
if actor_chat_member.status == "administrator" and getattr(actor_chat_member, permission, False):
return True
except TelegramError as e:
logger.error(f"Error checking permissions for {user.id} in chat {chat.id}: {e}")
await send_safe_reply(update, context, text="Mrow? Couldn't verify your permissions due to an API error.")
return False
await send_safe_reply(update, context, text=failure_message)
return False
# --- Utility Functions ---
def get_readable_time_delta(delta: timedelta) -> str:
total_seconds = int(delta.total_seconds())
if total_seconds < 0:
return "0s"
days, rem = divmod(total_seconds, 86400)
hours, rem = divmod(rem, 3600)
minutes, seconds = divmod(rem, 60)
parts = []
if days > 0:
parts.append(f"{days}d")
if hours > 0:
parts.append(f"{hours}h")
if minutes > 0:
parts.append(f"{minutes}m")
if not parts and seconds >= 0 :
parts.append(f"{seconds}s")
elif seconds > 0:
parts.append(f"{seconds}s")
return ", ".join(parts) if parts else "0s"
def add_to_gban(user_id: int, banned_by_id: int, reason: str | None) -> bool:
reason = reason or "No reason provided."
try:
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
timestamp = datetime.now(timezone.utc).isoformat()
cursor.execute(
"INSERT OR REPLACE INTO global_bans (user_id, reason, banned_by_id, timestamp) VALUES (?, ?, ?, ?)",
(user_id, reason, banned_by_id, timestamp)
)
return cursor.rowcount > 0
except sqlite3.Error as e:
logger.error(f"SQLite error adding user {user_id} to gban list: {e}")
return False
def remove_from_gban(user_id: int) -> bool:
try:
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM global_bans WHERE user_id = ?", (user_id,))
return cursor.rowcount > 0
except sqlite3.Error as e:
logger.error(f"SQLite error removing user {user_id} from gban list: {e}")
return False
def get_gban_reason(user_id: int) -> str | None:
try:
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
cursor.execute("SELECT reason FROM global_bans WHERE user_id = ?", (user_id,))
row = cursor.fetchone()
return row[0] if row else None
except sqlite3.Error as e:
logger.error(f"SQLite error checking gban status for user {user_id}: {e}")
return None
def add_chat_to_db(chat_id: int, chat_title: str):
try:
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
timestamp = datetime.now(timezone.utc).isoformat()
cursor.execute(
"INSERT OR REPLACE INTO bot_chats (chat_id, chat_title, added_at) VALUES (?, ?, ?)",
(chat_id, chat_title, timestamp)
)
except sqlite3.Error as e:
logger.error(f"Failed to add chat {chat_id} to DB: {e}")
def remove_chat_from_db(chat_id: int):
try:
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM bot_chats WHERE chat_id = ?", (chat_id,))
except sqlite3.Error as e:
logger.error(f"Failed to remove chat {chat_id} from DB: {e}")
def is_gban_enforced(chat_id: int) -> bool:
"""Checks if gban enforcement is enabled for a specific chat."""
try:
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
res = cursor.execute(
"SELECT enforce_gban FROM bot_chats WHERE chat_id = ?", (chat_id,)
).fetchone()
if res is None:
return True
return bool(res[0])
except sqlite3.Error as e:
logger.error(f"Could not check gban enforcement status for chat {chat_id}: {e}")
return True
# --- Helper Functions (Check Targets, Get GIF) ---
async def check_target_protection(target_user_id: int, context: ContextTypes.DEFAULT_TYPE) -> bool:
if target_user_id == OWNER_ID: return True
if target_user_id == context.bot.id: return True
return False
async def check_username_protection(target_mention: str, context: ContextTypes.DEFAULT_TYPE) -> tuple[bool, bool]:
is_protected = False; is_owner_match = False; bot_username = context.bot.username
if bot_username and target_mention.lower() == f"@{bot_username.lower()}": is_protected = True
elif OWNER_ID:
owner_username = None
try: owner_chat = await context.bot.get_chat(OWNER_ID); owner_username = owner_chat.username
except Exception as e: logger.warning(f"Could not fetch owner username for protection check: {e}")
if owner_username and target_mention.lower() == f"@{owner_username.lower()}": is_protected = True; is_owner_match = True
return is_protected, is_owner_match
async def get_themed_gif(context: ContextTypes.DEFAULT_TYPE, search_terms: list[str]) -> str | None:
if not TENOR_API_KEY: return None
if not search_terms: logger.warning("No search terms for get_themed_gif."); return None
search_term = random.choice(search_terms); logger.info(f"Searching Tenor: '{search_term}'")
url = "https://tenor.googleapis.com/v2/search"; params = { "q": search_term, "key": TENOR_API_KEY, "client_key": "my_cat_bot_project_py", "limit": 15, "media_filter": "gif", "contentfilter": "medium", "random": "true" }
try:
response = requests.get(url, params=params, timeout=7)
if response.status_code != 200:
logger.error(f"Tenor API failed for '{search_term}', status: {response.status_code}")
try: error_content = response.json(); logger.error(f"Tenor error content: {error_content}")
except requests.exceptions.JSONDecodeError: logger.error(f"Tenor error response (non-JSON): {response.text[:500]}")
return None
data = response.json(); results = data.get("results")
if results:
selected_gif = random.choice(results); gif_url = selected_gif.get("media_formats", {}).get("gif", {}).get("url")
if not gif_url: gif_url = selected_gif.get("media_formats", {}).get("tinygif", {}).get("url")
if gif_url: logger.info(f"Found GIF URL: {gif_url}"); return gif_url
else: logger.warning(f"Could not extract GIF URL from Tenor item for '{search_term}'.")
else: logger.warning(f"No results on Tenor for '{search_term}'."); logger.debug(f"Tenor response (no results): {data}")
except requests.exceptions.Timeout: logger.error(f"Timeout fetching GIF from Tenor for '{search_term}'.")
except requests.exceptions.RequestException as e: logger.error(f"Network/Request error fetching GIF from Tenor: {e}")
except Exception as e: logger.error(f"Unexpected error in get_themed_gif for '{search_term}': {e}", exc_info=True)
return None
# --- Command Handlers ---
HELP_TEXT = """
<b>Meeeow! 🐾 Here are the commands you can use:</b>
<b>Bot Commands:</b>
/start - Shows the welcome message. ✨
/help - Shows this help message. ❓
/github - Get the link to my source code! 💻
/owner - Info about my designated human! ❤️
/sudocmds - List sudo commands. 👷♂️
<b>User Commands:</b>
/info <ID/@user/reply> - Get info about a user. 👤
/chatstat - Get basic stats about the current chat. 📈
/kickme - Kick yourself from chat. 👋
/listadmins - Show the list of administrators in the current chat. 📃
<i>Note: /admins works too</i>
<b>Management Commands:</b>
/ban <ID/@user/reply> [Time] [Reason] - Ban user in chat. ⛔️
/unban <ID/@user/reply> - Unban user in chat. 🔓
/mute <ID/@user/reply> [Time] [Reason] - Mute user in chat. 🚫
/unmute <ID/@user/reply> - Unmute user in chat. 🎙
<i>Note: [Time] is optional</i>
/kick <ID/@user/reply> [Reason] - Kick user from chat. ⚠️
/promote <ID/@user/reply> [Title] - Promote a user to administrator. 👷♂️
<i>Note: [Title] is optional</i>
/demote <ID/@user/reply> - Demote an administrator to a regular member. 🙍♂️
/pin <loud|notify> - Pin the replied message. 📌
/unpin - Unpin the replied message. 📍
/purge <silent> - Deletes user messages up to the replied-to message. 🗑
/report <ID/@user/reply> [reason] - Report user. ⚠️
<b>Security:</b>
/enforcegban <yes/no> - Enable/disable Global Ban enforcement in this chat. 🛡️
<i>(Chat Creator only)</i>
<b>4FUN Commands:</b>
/gif - Get a random cat GIF! 🖼️
/photo - Get a random cat photo! 📷
/meow - Get a random cat sound or phrase. 🔊
/nap - What's on a cat's mind during naptime? 😴
/play - Random playful cat actions. 🧶
/treat - Demand treats! 🎁
/zoomies - Witness sudden bursts of cat energy! 💥
/judge - Get judged by a superior feline. 🧐
/fed - I just ate, thank you! 😋
/attack <@user/reply> - Launch a playful attack! ⚔️
/kill <@user/reply> - Metaphorically eliminate someone! 💀
/punch <@user/reply> - Deliver a textual punch! 👊
/slap <@user/reply> - Administer a swift slap! 👋
/bite <@user/reply> - Take a playful bite! 😬
/hug <@user/reply> - Offer a comforting hug! 🤗
"""
SUDO_COMMANDS_TEXT = """
<b>Sudo Commands:</b>
/status - Show bot status.
/cinfo [Optional chat ID] - Get detailed info about the current or specified chat.
/say [Optional chat ID] [Your text] - Send message as bot.
/blist <ID/@user/reply> [Reason] - Add user to blacklist.
/unblist <ID/@user/reply> - Remove user from blacklist.
/gban <ID/@user/reply> [Reason] - Ban user globally.
/ungban <ID/@user/reply> - Unban user globally.
<i>Note: Commands: /ban, /unban, /mute, /unmute, /kick, /pin, /unpin, /purge; can be used by sudo users even if they are not chat creator/administrator.</i>
"""
OWNER_COMMANDS_TEXT = """
<b>Owner Commands:</b>
/leave [Optional chat ID] - Make the bot leave a chat.
/speedtest - Perform an internet speed test.
/listsudo - List all users with sudo privileges.
/addsudo <ID/@user/reply> - Grants SUDO (bot admin) permissions to a user.
/delsudo <ID/@user/reply> - Revokes SUDO (bot admin) permissions from a user.
"""
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user = update.effective_user
welcome_message = f"Meow {user.mention_html()}! I'm the Meow Bot. 🐾\nUse /help to see available commands!"
if context.args:
if context.args[0] == 'help':
await update.message.reply_html(HELP_TEXT, disable_web_page_preview=True)
return
if context.args[0] == 'sudocmds':
if not is_privileged_user(user.id):
return
final_sudo_help = SUDO_COMMANDS_TEXT
if user.id == OWNER_ID:
final_sudo_help += "\n" + OWNER_COMMANDS_TEXT
await update.message.reply_html(final_sudo_help, disable_web_page_preview=True)
return
await update.message.reply_html(welcome_message)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
chat = update.effective_chat
if chat.type == ChatType.PRIVATE:
await update.message.reply_html(HELP_TEXT, disable_web_page_preview=True)
return
bot_username = context.bot.username
deep_link_url = f"https://t.me/{bot_username}?start=help"
keyboard = InlineKeyboardMarkup(
[
[InlineKeyboardButton(text="📬 Get Help (PM)", url=deep_link_url)]
]
)
message_text = "Meeeow! 🐾 I've sent the help message to your private chat. Please click the button below to see it."
await send_safe_reply(update, context, text=message_text, reply_markup=keyboard)
async def github(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
github_link = "https://github.com/R0Xofficial/MyCatbot"
await update.message.reply_text(f"Meeeow! I'm open source! 💻 Here is my code: {github_link}", disable_web_page_preview=True)
async def owner_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if OWNER_ID:
owner_mention = f"<code>{OWNER_ID}</code>"; owner_name = "My Esteemed Human"
try: owner_chat = await context.bot.get_chat(OWNER_ID); owner_mention = owner_chat.mention_html(); owner_name = owner_chat.full_name or owner_chat.username or owner_name
except TelegramError as e: logger.warning(f"Could not fetch owner info ({OWNER_ID}): {e}")
except Exception as e: logger.warning(f"Unexpected error fetching owner info: {e}")
message = (f"My designated human is: 👤 <b>{html.escape(owner_name)}</b> ({owner_mention}) ❤️")
await update.message.reply_html(message)
else: await update.message.reply_text("Meow? Owner info not configured! 😿")
# --- User Info Command ---
def format_entity_info(entity: Chat | User,
chat_member_status_str: str | None = None,
is_target_owner: bool = False,
is_target_sudo: bool = False,
blacklist_reason_str: str | None = None,
gban_reason_str: str | None = None,
current_chat_id_for_status: int | None = None,
bot_context: ContextTypes.DEFAULT_TYPE | None = None
) -> str:
info_lines = []
entity_id = entity.id
is_user_type = isinstance(entity, User)
entity_chat_type = getattr(entity, 'type', None) if not is_user_type else ChatType.PRIVATE
if is_user_type or entity_chat_type == ChatType.PRIVATE:
user = entity
info_lines.append(f"👤 <b>User Information:</b>\n")
first_name = html.escape(getattr(user, 'first_name', "N/A") or "N/A")
last_name = html.escape(getattr(user, 'last_name', "") or "")
username_display = f"@{html.escape(user.username)}" if user.username else "N/A"
permalink_user_url = f"tg://user?id={user.id}"
permalink_text_display = "Link"
permalink_html_user = f"<a href=\"{permalink_user_url}\">{permalink_text_display}</a>"
is_bot_val = getattr(user, 'is_bot', False)
is_bot_str = "Yes" if is_bot_val else "No"
language_code_val = getattr(user, 'language_code', "N/A")
info_lines.extend([
f"<b>• ID:</b> <code>{user.id}</code>",
f"<b>• First Name:</b> {first_name}",
])
if getattr(user, 'last_name', None):
info_lines.append(f"<b>• Last Name:</b> {last_name}")
info_lines.extend([
f"<b>• Username:</b> {username_display}",
f"<b>• Permalink:</b> {permalink_html_user}",
f"<b>• Is Bot:</b> <code>{is_bot_str}</code>",
f"<b>• Language Code:</b> <code>{language_code_val if language_code_val else 'N/A'}</code>\n"
])
if chat_member_status_str and current_chat_id_for_status != user.id and current_chat_id_for_status is not None:
display_status = ""
if chat_member_status_str == "creator": display_status = "<code>Creator</code>"
elif chat_member_status_str == "administrator": display_status = "<code>Admin</code>"
elif chat_member_status_str == "member": display_status = "<code>Member</code>"
elif chat_member_status_str == "left": display_status = "<code>Not in chat</code>"
elif chat_member_status_str == "kicked": display_status = "<code>Banned</code>"
elif chat_member_status_str == "restricted": display_status = "<code>Muted</code>"
elif chat_member_status_str == "not_a_member": display_status = "<code>Not in chat</code>"
else: display_status = f"<code>{html.escape(chat_member_status_str.replace('_', ' ').capitalize())}</code>"
info_lines.append(f"<b>• Status:</b> {display_status}\n")
if is_target_owner:
info_lines.append(f"<b>• Bot Owner:</b> <code>Yes</code>")
elif is_target_sudo:
info_lines.append(f"<b>• Bot Sudo:</b> <code>Yes</code>")
if blacklist_reason_str is not None:
info_lines.append(f"<b>• Blacklisted:</b> <code>Yes</code>")
info_lines.append(f"<b>Reason:</b> {html.escape(blacklist_reason_str)}")
else:
info_lines.append(f"<b>• Blacklisted:</b> <code>No</code>")
if gban_reason_str is not None:
info_lines.append(f"<b>• Globally Banned:</b> <code>Yes</code>")
info_lines.append(f"<b>Reason:</b> {html.escape(gban_reason_str)}")
else:
info_lines.append(f"<b>• Globally Banned:</b> <code>No</code>")
elif entity_chat_type == ChatType.CHANNEL:
channel = entity
info_lines.append(f"📢 <b>Channel info:</b>\n")
info_lines.append(f"<b>• ID:</b> <code>{channel.id}</code>")
channel_name_to_display = channel.title or getattr(channel, 'first_name', None) or f"Channel {channel.id}"
info_lines.append(f"<b>• Title:</b> {html.escape(channel_name_to_display)}")
if channel.username:
info_lines.append(f"<b>• Username:</b> @{html.escape(channel.username)}")
permalink_channel_url = f"https://t.me/{html.escape(channel.username)}"
permalink_text_display = "Link"
permalink_channel_html = f"<a href=\"{permalink_channel_url}\">{permalink_text_display}</a>"
info_lines.append(f"<b>• Permalink:</b> {permalink_channel_html}")
else:
info_lines.append(f"<b>• Permalink:</b> Private channel (no public link)")
elif entity_chat_type in [ChatType.GROUP, ChatType.SUPERGROUP]:
chat = entity
title = html.escape(chat.title or f"{entity_chat_type.capitalize()} {chat.id}")
info_lines.append(f"ℹ️ Entity <code>{chat.id}</code> is a <b>{entity_chat_type.capitalize()}</b> ({title}).")
info_lines.append(f"This command primarily provides detailed info for Users and Channels.")
else:
info_lines.append(f"❓ <b>Unknown or Unsupported Entity Type:</b> ID <code>{html.escape(str(entity_id))}</code>")
if entity_chat_type:
info_lines.append(f" • Type detected: {entity_chat_type.capitalize()}")
return "\n".join(info_lines)
async def entity_info_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
target_entity_obj: Chat | User | None = None
initial_user_obj_from_update: User | None = None
target_chat_obj_from_api: Chat | None = None
initial_entity_id_for_refresh: int | None = None
current_chat_id = update.effective_chat.id
command_caller_id = update.effective_user.id
if update.effective_user:
update_user_in_db(update.effective_user)
if update.message.reply_to_message:
if update.message.reply_to_message.sender_chat:
target_chat_obj_from_api = update.message.reply_to_message.sender_chat
initial_entity_id_for_refresh = target_chat_obj_from_api.id
logger.info(f"/info target is replied sender_chat: ID={target_chat_obj_from_api.id}")
else:
initial_user_obj_from_update = update.message.reply_to_message.from_user
if initial_user_obj_from_update:
update_user_in_db(initial_user_obj_from_update)
initial_entity_id_for_refresh = initial_user_obj_from_update.id
logger.info(f"/info target is replied user: {initial_user_obj_from_update.id}")
elif context.args:
target_input_str = context.args[0]
logger.info(f"/info target is argument: {target_input_str}")
resolved_user_from_db: User | None = None
if target_input_str.startswith("@"):
username_to_find = target_input_str[1:]
resolved_user_from_db = get_user_from_db_by_username(username_to_find)
if resolved_user_from_db:
initial_user_obj_from_update = resolved_user_from_db
initial_entity_id_for_refresh = resolved_user_from_db.id
else:
logger.info(f"Trying find entity @{username_to_find} by using Telegram API.")
try:
target_chat_obj_from_api = await context.bot.get_chat(target_input_str)
initial_entity_id_for_refresh = target_chat_obj_from_api.id
if target_chat_obj_from_api.type == ChatType.PRIVATE:
user_to_save = User(id=target_chat_obj_from_api.id, first_name=target_chat_obj_from_api.first_name or "", is_bot=getattr(target_chat_obj_from_api, 'is_bot', False), username=target_chat_obj_from_api.username, last_name=target_chat_obj_from_api.last_name, language_code=getattr(target_chat_obj_from_api, 'language_code', None))
update_user_in_db(user_to_save)
initial_user_obj_from_update = user_to_save
except TelegramError as e:
logger.error(f"Telegram API error for @ '{target_input_str}': {e}")
await update.message.reply_text(f"😿 Mrow! I couldn't find '{html.escape(target_input_str)}'.")
return
except Exception as e:
logger.error(f"Unexpected error processing @ '{target_input_str}': {e}", exc_info=True)
await update.message.reply_text(f"💥 An unexpected error occurred with '{html.escape(target_input_str)}'.")
return
else:
try:
target_id = int(target_input_str)
initial_entity_id_for_refresh = target_id
target_chat_obj_from_api = await context.bot.get_chat(target_id)
if target_chat_obj_from_api.type == ChatType.PRIVATE:
user_to_save = User(id=target_chat_obj_from_api.id, first_name=target_chat_obj_from_api.first_name or "", is_bot=getattr(target_chat_obj_from_api, 'is_bot', False), username=target_chat_obj_from_api.username, last_name=target_chat_obj_from_api.last_name, language_code=getattr(target_chat_obj_from_api, 'language_code', None))
update_user_in_db(user_to_save)
initial_user_obj_from_update = user_to_save
except ValueError:
await update.message.reply_text(f"Mrow? Invalid format: '{html.escape(target_input_str)}'.")
return
except TelegramError as e:
logger.error(f"Error fetching chat/user info for ID '{target_input_str}': {e}")
await update.message.reply_text(f"😿 Couldn't find or access info for ID '{html.escape(target_input_str)}': {e}")
return
except Exception as e:
logger.error(f"Unexpected error processing ID '{target_input_str}': {e}", exc_info=True)
await update.message.reply_text(f"💥 An unexpected error occurred processing ID '{html.escape(target_input_str)}'.")
return
else:
initial_user_obj_from_update = update.effective_user
if initial_user_obj_from_update:
update_user_in_db(initial_user_obj_from_update)
initial_entity_id_for_refresh = initial_user_obj_from_update.id
logger.info(f"/info target is command sender: {initial_user_obj_from_update.id}")
final_entity_to_display: Chat | User | None = None
if initial_user_obj_from_update:
final_entity_to_display = initial_user_obj_from_update
elif target_chat_obj_from_api:
final_entity_to_display = target_chat_obj_from_api
if final_entity_to_display and initial_entity_id_for_refresh is not None:
is_target_owner_flag = False
is_target_sudo_flag = False
member_status_in_current_chat_str: str | None = None
blacklist_reason_str: str | None = None
gban_reason_str: str | None = None
try:
fresh_data_chat_obj = await context.bot.get_chat(chat_id=initial_entity_id_for_refresh)
if isinstance(final_entity_to_display, User) or fresh_data_chat_obj.type == ChatType.PRIVATE:
current_is_bot = getattr(final_entity_to_display, 'is_bot', False)
current_lang_code = getattr(final_entity_to_display, 'language_code', None)
refreshed_user = User(
id=fresh_data_chat_obj.id,
first_name=fresh_data_chat_obj.first_name or getattr(final_entity_to_display, 'first_name', None) or "",
last_name=fresh_data_chat_obj.last_name or getattr(final_entity_to_display, 'last_name', None),
username=fresh_data_chat_obj.username or getattr(final_entity_to_display, 'username', None),
is_bot=getattr(fresh_data_chat_obj, 'is_bot', current_is_bot),
language_code=getattr(fresh_data_chat_obj, 'language_code', current_lang_code)
)
update_user_in_db(refreshed_user)
final_entity_to_display = refreshed_user
is_target_owner_flag = (OWNER_ID is not None and final_entity_to_display.id == OWNER_ID)
if not is_target_owner_flag:
is_target_sudo_flag = is_sudo_user(final_entity_to_display.id)
blacklist_reason_str = get_blacklist_reason(final_entity_to_display.id)
gban_reason_str = get_gban_reason(final_entity_to_display.id)
if current_chat_id != final_entity_to_display.id and update.effective_chat.type in [ChatType.GROUP, ChatType.SUPERGROUP]:
try:
chat_member = await context.bot.get_chat_member(chat_id=current_chat_id, user_id=final_entity_to_display.id)
member_status_in_current_chat_str = chat_member.status
except TelegramError as e:
if "user not found" in str(e).lower(): member_status_in_current_chat_str = "not_a_member"
else: logger.warning(f"Could not get status for {final_entity_to_display.id}: {e}")
except Exception as e: logger.error(f"Unexpected error getting status: {e}", exc_info=True)
else:
final_entity_to_display = fresh_data_chat_obj
logger.info(f"Loaded entity data for {final_entity_to_display.id} from API.")
except TelegramError as e:
logger.warning(f"Could not load entity data for {initial_entity_id_for_refresh} from API: {e}. Using initially identified data.")
except Exception as e:
logger.error(f"Unexpected error loading entity data for {initial_entity_id_for_refresh}: {e}", exc_info=True)
if final_entity_to_display:
info_message = format_entity_info(
final_entity_to_display,
member_status_in_current_chat_str,
is_target_owner_flag,
is_target_sudo_flag,
blacklist_reason_str,
gban_reason_str,
current_chat_id,
context
)
try:
await update.message.reply_html(info_message)
logger.info(f"Sent /info response for entity {final_entity_to_display.id} in chat {update.effective_chat.id}")
except TelegramError as e_reply:
logger.error(f"Failed to send /info reply in chat {update.effective_chat.id}: {e_reply}")
except Exception as e_reply_other:
logger.error(f"Unexpected error sending /info reply: {e_reply_other}", exc_info=True)
else:
await update.message.reply_text("Mrow? Could not obtain entity details to display.")
else:
await update.message.reply_text("Mrow? Couldn't determine what to get info for.")
async def list_admins_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
chat = update.effective_chat
if chat.type not in [ChatType.GROUP, ChatType.SUPERGROUP, ChatType.CHANNEL]:
await update.message.reply_text("Meeeow! I can only list admins for groups, supergroups, or channels.")
return
try:
administrators = await context.bot.get_chat_administrators(chat_id=chat.id)