This repository has been archived by the owner on Oct 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
adminbot.py
2124 lines (1967 loc) · 67.7 KB
/
adminbot.py
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
from bot import *
from telethon import events, functions, types
from telethon.utils import pack_bot_file_id
from bot.sql.welcomesql import (
add_welcome_setting,
get_current_welcome_settings,
rm_welcome_setting,
update_previous_welcome,
)
from bot.sql.filtersql import (
add_filter,
get_all_filters,
remove_all_filters,
remove_filter,
)
from bot.sql.notessql import (
get_snips,
add_snip,
remove_snip,
get_all_snips,
remove_all_snip,
)
import bot.sql.antifloodsql as ansql
import os
from telethon import *
from telethon.tl import *
from typing import Optional
import bot.sql.rulessql as sql
import logging
from logging import DEBUG, INFO, basicConfig, getLogger,WARNING
from telethon.tl.functions.messages import EditChatDefaultBannedRightsRequest
from telethon.tl.types import ChatBannedRights
from bot.config import Config
OWNER = Config.OWNER_ID
# =================== CONSTANT ===================
PP_TOO_SMOL = "`The image is too small`"
PP_ERROR = "`Failure while processing the image`"
NO_ADMIN = "`I am not an admin nub nibba!`"
NO_PERM = (
"`I don't have sufficient permissions! This is so sed. Alexa play Tera Baap Aaya`"
)
NO_SQL = "`Almost Done! Wait...`"
CHAT_PP_CHANGED = "`Chat Picture Changed`"
CHAT_PP_ERROR = (
"`Some issue with updating the pic,`"
"`maybe coz I'm not an admin,`"
"`or don't have enough rights.`"
)
INVALID_MEDIA = "`Invalid Extension`"
BANNED_RIGHTS = ChatBannedRights(
until_date=None,
view_messages=True,
send_messages=True,
send_media=True,
send_stickers=True,
send_gifs=True,
send_games=True,
send_inline=True,
embed_links=True,
)
UNBAN_RIGHTS = ChatBannedRights(
until_date=None,
send_messages=None,
send_media=None,
send_stickers=None,
send_gifs=None,
send_games=None,
send_inline=None,
embed_links=None,
)
MUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=True)
UNMUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=False)
basicConfig(format="%(name)s - %(message)s", level=WARNING)
OWNER_ID = OWNER
#==========================================================================
# For Inlines Of bot
@callback("backer")
async def _(event):
botun = (await adminbot.get_me()).username
botname = (await adminbot.get_me()).first_name
await event.edit(
f"Hi There, I am {botname},\nI Help Admins To Manage Their Chats Easily\n\n - This Bot is Purely Made in Telethon..\n\nJoin Our Updates Channel for Updates and Support Group for help",
buttons=[
[
Button.inline("Help", data="helpstarter"),
],
[
Button.url("Updates Channel", url="https://t.me/FutureCodes"),
Button.url("Support Group", url="https://t.me/FutureCodesChat"),
],
[
Button.url("Add To Group 👥", f"https://t.me/{botun}?startgroup=true"),
],
],
)
@callback("helpstarter")
async def _(event):
botun = (await adminbot.get_me()).username
botname = (await adminbot.get_me()).first_name
await event.edit(
f"Hey there! I am {botname}.\nI help admins manage their groups with Pro Features!\nHave a look at the following for an idea of some of the things I can help you with.\n\nAll commands can be used with /.\nAnd You May Check The Help for Plugins :"
,buttons=[
[
Button.inline("Antiflood", data="antifloodhelp"),
Button.inline("Bans", data="banhelp"),
Button.inline("Blacklists" , data="blacklisthelp"),
],
[
Button.inline("Promote" , data="promotehelp"),
Button.inline("Kick" , data="kickhelp"),
Button.inline("Pin/Unpin", data="pinhelp"),
],
[
Button.inline("Purge" , data="purgehelp"),
Button.inline("Filters" , data="filterhelp"),
Button.inline("Rules" , data="ruleshelp"),
],
[
Button.inline("Locks", data="lockhelp"),
Button.inline("Notes", data="noteshelp"),
Button.inline("Warns", data="warnhelp"),
],
[
Button.inline("Welcomes" , data="welcomehelp"),
],
[
Button.inline("<-- Back" , data="backer"),
],
],
)
#======================================================================================================
# For Pms Of Bot
@admin_cmd("start", is_args="simple")
async def _(event):
if event.is_group:
try :
botun = (await adminbot.get_me()).username
botname = (await adminbot.get_me()).first_name
return await event.reply(f"Hi There, I am {botname}\nTo know More PM Me",buttons=[Button.url("Start Me In PM", url=f"https://t.me/{botun}?start")])
except BaseException:
pass
else:
try :
botun = (await adminbot.get_me()).username
botname = (await adminbot.get_me()).first_name
return await event.reply(
f"Hi There, I am {botname},\nI Help Admins To Mange Their Chats Easily\n\n - This Bot is Purely Made in Telethon....\n\nJoin Our Updates Channel for Updates and Support Group for help",
buttons=[
[
Button.inline("Help", data="helpstarter"),
],
[
Button.url("Updates Channel", url="https://t.me/FutureCodes"),
Button.url("Support Group", url="https://t.me/FutureCodesChat"),
],
[
Button.url("Add To Group 👥", f"https://t.me/{botun}?startgroup=true"),
],
],
)
except BaseException:
pass
#==========================================================================
# Admin Module
@admin_cmd("ban", is_args=True)
@only_groups
@is_bot_admin
@is_admin
@can_restrict
async def ban(event):
chat = await event.get_chat()
chat.admin_rights
chat.creator
user, reason = await get_user_from_event(event)
kekme = await adminbot.get_permissions(event.chat_id, user)
momos = user
momoz = momos.first_name
if kekme.is_admin:
await event.reply("Oh, Yeah? Lets Start Banning Admins.")
return
if user:
pass
else:
return
try:
await event.client(EditBannedRequest(event.chat_id, user.id, BANNED_RIGHTS))
except BadRequestError:
await event.reply("I Could't Ban That User Probably Due To Less Permissions.")
return
if reason:
await event.reply(f"Banned {momoz} For \nReason: {reason}")
else:
await event.reply(f"Banned {momoz} !")
@admin_cmd("unban", is_args=True)
@only_groups
@is_bot_admin
@is_admin
@can_restrict
async def nothanos(event):
chat = await event.get_chat()
chat.admin_rights
chat.creator
user = await get_user_from_event(event)
user = user[0]
if user:
pass
else:
return
try:
await event.client(EditBannedRequest(event.chat_id, user.id, UNBAN_RIGHTS))
await event.reply("`Unbanned Successfully. Granting another chance.🚶`")
except BadRequestError:
await event.reply("I Could't UnBan That User Probably Due To Less Permissions.")
return
@admin_cmd("promote", is_args=True)
@only_groups
@is_bot_admin
@is_admin
@can_promote
async def promote(event):
chat = await event.get_chat()
chat.admin_rights
chat.creator
new_rights = ChatAdminRights(
add_admins=False,
invite_users=False,
change_info=False,
ban_users=True,
delete_messages=True,
pin_messages=True,
)
user, rank = await get_user_from_event(event)
kekme = await adminbot.get_permissions(event.chat_id, user)
if kekme.is_admin:
await event.reply("Oh, Yeah? Promote A Admin?")
return
if not rank:
rank = "Admin"
if user:
pass
else:
return
try:
await event.client(EditAdminRequest(event.chat_id, user.id, new_rights, rank))
await event.reply("Promoted Successfully! Now give Party")
except BadRequestError:
await event.reply(
"I Could't Promote That User Probably Due To Less Permissions."
)
return
@admin_cmd("demote", is_args=True)
@only_groups
@is_bot_admin
@is_admin
@can_promote
async def demote(event):
chat = await event.get_chat()
chat.admin_rights
chat.creator
rank = "Admin"
user = await get_user_from_event(event)
user = user[0]
if user:
pass
else:
return
newrights = ChatAdminRights(
add_admins=None,
invite_users=None,
change_info=None,
ban_users=None,
delete_messages=None,
pin_messages=None,
)
try:
await event.client(EditAdminRequest(event.chat_id, user.id, newrights, rank))
except BadRequestError:
await event.reply(
"I Could't Demote That User Probably Due To Less Permissions."
)
return
await event.reply("Demoted This User Sucessfully.")
@admin_cmd("pin", is_args=True)
@only_groups
@is_bot_admin
@is_admin
@can_pin
async def pin(event):
await event.get_chat()
to_pin = event.reply_to_msg_id
if not to_pin:
await event.reply("`Reply to a message to pin it.`")
return
options = event.pattern_match.group(1)
is_silent = True
if options.lower() == "loud":
is_silent = False
try:
await event.client(UpdatePinnedMessageRequest(event.to_id, to_pin, is_silent))
except BadRequestError:
await event.reply(
"I Could't Pin That Message Probably Due To Less Permissions."
)
return
await event.reply("Pinned This Message Sucessfully.")
await get_user_sender_id(event.sender_id, event)
@admin_cmd("kick", is_args=True)
@only_groups
@is_bot_admin
@is_admin
@can_restrict
async def kick(event):
chat = await event.get_chat()
chat.admin_rights
chat.creator
user, reason = await get_user_from_event(event)
kekme = await adminbot.get_permissions(event.chat_id, user)
momos = user
momos.first_name
if kekme.is_admin:
await event.reply("Oh, Yeah? Lets Start kicking Admins.")
retur
if not user:
await event.reply("Mention A User")
return
try:
await event.client.kick_participant(event.chat_id, user.id)
except:
await event.reply("I Could't Kick That User Probably Due To Less Permissions.")
return
if reason:
await event.reply(
f"`Kicked` [{user.first_name}](tg://user?id={user.id})`!`\nReason: {reason}"
)
else:
await event.reply(f"`Kicked` [{user.first_name}](tg://user?id={user.id})`!`")
@admin_cmd("mute", is_args=True)
@only_groups
@is_bot_admin
@is_admin
@can_restrict
async def mute(event):
chat = await event.get_chat()
chat.admin_rights
chat.creator
user, reason = await get_user_from_event(event)
kekme = await adminbot.get_permissions(event.chat_id, user)
momos = user
momos.first_name
if kekme.is_admin:
await event.reply("Oh, Mutting? Lets Start Banning Admins.")
retur
if not user:
await event.reply("Mention A User")
return
try:
await event.client(EditBannedRequest(event.chat_id, user.id, MUTE_RIGHTS))
except:
await event.reply("I Could't Mute That User Probably Due To Less Permissions.")
return
if reason:
await event.reply(
f"`Muted` [{user.first_name}](tg://user?id={user.id})`!`\nReason: {reason}"
)
else:
await event.reply(f"`Kicked` [{user.first_name}](tg://user?id={user.id})`!`")
@admin_cmd("unmute", is_args=True)
@only_groups
@is_bot_admin
@is_admin
@can_restrict
async def mute(event):
chat = await event.get_chat()
chat.admin_rights
chat.creator
user, reason = await get_user_from_event(event)
if not user:
await event.reply("Mention A User")
return
try:
await event.client(EditBannedRequest(event.chat_id, user.id, UNMUTE_RIGHTS))
except:
await event.reply(
"I Could't UnMute That User Probably Due To Less Permissions."
)
return
if reason:
await event.reply(
f"`UnMuted` [{user.first_name}](tg://user?id={user.id})`!`\nReason: {reason}"
)
else:
await event.reply(f"`Unmute` [{user.first_name}](tg://user?id={user.id})`!`")
@admin_cmd("purge")
@can_delete
@only_groups
@is_bot_admin
@is_admin
async def purge(event):
chat = event.chat_id
msgs = []
msg = await event.get_reply_message()
if not msg:
await event.reply("Reply to a message to select where to start purging from.")
return
try:
msg_id = msg.id
count = 0
to_delete = event.message.id - 1
await adminbot.delete_messages(chat, event.message.id)
msgs.append(event.reply_to_msg_id)
for m_id in range(to_delete, msg_id - 1, -1):
msgs.append(m_id)
count += 1
if len(msgs) == 100:
await adminbot.delete_messages(chat, msgs)
msgs = []
await adminbot.delete_messages(chat, msgs)
del_res = await adminbot.send_message(
event.chat_id, f"Fast Purged {count} messages."
)
await del_res.delete()
await asyncio.sleep(4)
except MessageDeleteForbiddenError:
text = "Failed to delete messages.\n"
text += "Messages maybe too old or I'm not admin! or dont have delete rights!"
del_res = await respond(text, parse_mode="md")
await asyncio.sleep(5)
await del_res.delete()
@admin_cmd("del", is_args=False)
@can_delete
@only_groups
@is_bot_admin
@is_admin
async def delete_msg(event):
chat = event.chat_id
msg = await event.get_reply_message()
if not msg:
await event.reply("Reply to some message to delete it.")
return
to_delete = event.message
chat = await event.get_input_chat()
rm = [msg, to_delete]
await adminbot.delete_messages(chat, rm)
@admin_cmd("unpin", is_args="unpin")
@only_groups
@is_bot_admin
@is_admin
@can_pin
async def _(event):
ch = (event.pattern_match.group(1)).strip()
msg = event.reply_to_msg_id
if msg and not ch:
try:
await adminbot.unpin_message(event.chat_id, msg)
except BadRequestError:
return await event.reply("Insufficient Permissions")
except Exception as e:
return await event.reply(f"**ERROR:**\n`{str(e)}`")
elif ch == "all":
try:
await adminbot.unpin_message(event.chat_id)
except BadRequestError:
return await event.reply("Insufficient Permissions")
except Exception as e:
return await event.reply(f"**ERROR:**`{str(e)}`")
else:
return await event.reply(f"Either reply to a message, or, use `/unpin all`")
if not msg and ch != "all":
return await event.reply(f"Either reply to a message, or, use `/unpin all`")
await event.reply("`Unpinned!`")
async def get_user_from_event(event):
""" Get the user from argument or replied message. """
args = event.pattern_match.group(1).split(" ", 1)
extra = None
if event.reply_to_msg_id:
previous_message = await event.get_reply_message()
user_obj = await event.client.get_entity(previous_message.sender_id)
extra = event.pattern_match.group(1)
elif args:
user = args[0]
if len(args) == 2:
extra = args[1]
if user.isnumeric():
user = int(user)
if not user:
await event.reply("`Pass the user's username, id or reply!`")
return
if event.message.entities is not None:
probable_user_mention_entity = event.message.entities[0]
if isinstance(probable_user_mention_entity, MessageEntityMentionName):
user_id = probable_user_mention_entity.user_id
user_obj = await event.client.get_entity(user_id)
return user_obj
try:
user_obj = await event.client.get_entity(user)
except (TypeError, ValueError) as err:
await event.edit(str(err))
return None
return user_obj, extra
async def get_user_sender_id(user, event):
if isinstance(user, str):
user = int(user)
try:
user_obj = await event.client.get_entity(user)
except (TypeError, ValueError) as err:
await event.edit(str(err))
return None
return user_obj
###########====================================================================================================
#LockTypes
@admin_cmd("lock", is_args="simple")
@only_groups
@is_bot_admin
@is_admin
@change_info
async def locks(event):
input_str = event.pattern_match.group(1).lower()
peer_id = event.chat_id
msg = None
media = None
sticker = None
gif = None
gamee = None
ainline = None
gpoll = None
adduser = None
cpin = None
changeinfo = None
if input_str == "msg":
msg = True
what = "messages"
elif input_str == "media":
media = True
what = "media"
elif input_str == "sticker":
sticker = True
what = "stickers"
elif input_str == "gif":
gif = True
what = "GIFs"
elif input_str == "game":
gamee = True
what = "games"
elif input_str == "inline":
ainline = True
what = "inline bots"
elif input_str == "poll":
gpoll = True
what = "polls"
elif input_str == "invite":
adduser = True
what = "invites"
elif input_str == "pin":
cpin = True
what = "pins"
elif input_str == "info":
changeinfo = True
what = "chat info"
elif input_str == "all":
msg = True
media = True
sticker = True
gif = True
gamee = True
ainline = True
gpoll = True
adduser = True
cpin = True
changeinfo = True
what = "everything"
else:
if not input_str:
await event.reply("Specify to What to Lock !!")
return
else:
await event.reply(f"Invalid lock type: `{input_str}` .\nSee /locktypes for more info")
return
lock_rights = types.ChatBannedRights(
until_date=None,
send_messages=msg,
send_media=media,
send_stickers=sticker,
send_gifs=gif,
send_games=gamee,
send_inline=ainline,
send_polls=gpoll,
invite_users=adduser,
pin_messages=cpin,
change_info=changeinfo,
)
try:
await event.client(
EditChatDefaultBannedRightsRequest(peer=peer_id, banned_rights=lock_rights)
)
await event.reply(f"`Locked {what} !`")
except BaseException as e:
await event.reply(f"**Error Occured:** {str(e)}")
return
@admin_cmd("unlock", is_args="simple")
@only_groups
@is_bot_admin
@is_admin
@change_info
async def rem_locks(event):
input_str = event.pattern_match.group(1).lower()
peer_id = event.chat_id
msg = None
media = None
sticker = None
gif = None
gamee = None
ainline = None
gpoll = None
adduser = None
cpin = None
changeinfo = None
if input_str == "msg":
msg = False
what = "messages"
elif input_str == "media":
media = False
what = "media"
elif input_str == "sticker":
sticker = False
what = "stickers"
elif input_str == "gif":
gif = False
what = "GIFs"
elif input_str == "game":
gamee = False
what = "games"
elif input_str == "inline":
ainline = False
what = "inline bots"
elif input_str == "poll":
gpoll = False
what = "polls"
elif input_str == "invite":
adduser = False
what = "invites"
elif input_str == "pin":
cpin = False
what = "pins"
elif input_str == "info":
changeinfo = False
what = "chat info"
elif input_str == "all":
msg = False
media = False
sticker = False
gif = False
gamee = False
ainline = False
gpoll = False
adduser = False
cpin = False
changeinfo = False
what = "everything"
else:
if not input_str:
await event.reply("`Specify What to Unlock !!`")
return
else:
await event.reply(f"Invalid lock type: `{input_str}` .\nSee /locktypes for more info")
return
unlock_rights = types.ChatBannedRights(
until_date=None,
send_messages=msg,
send_media=media,
send_stickers=sticker,
send_gifs=gif,
send_games=gamee,
send_inline=ainline,
send_polls=gpoll,
invite_users=adduser,
pin_messages=cpin,
change_info=changeinfo,
)
try:
await event.client(
EditChatDefaultBannedRightsRequest(
peer=peer_id, banned_rights=unlock_rights
)
)
await event.reply(f"Unlocked {what} !!")
except BaseException as e:
await event.reply(f"**Error Occured:\n** {str(e)}")
return
@admin_cmd("locktypes", is_args=False)
async def locktypes(event):
await event.reply(lockktypes)
#==============================================================================================================
#Welcome
@adminbot.on(events.ChatAction())
async def _(event):
cws = get_current_welcome_settings(event.chat_id)
if cws:
# logger.info(event.stringify())
"""user_added=False,
user_joined=True,
user_left=False,
user_kicked=False,"""
if event.user_joined:
if cws.should_clean_welcome:
try:
await adminbot.delete_messages( # pylint:disable=E0602
event.chat_id, cws.previous_welcome
)
except Exception as e: # pylint:disable=C0103,W0703
logger.warn(str(e)) # pylint:disable=E0602
a_user = await event.get_user()
chat = await event.get_chat()
title = chat.title if chat.title else "this chat"
participants = await event.client.get_participants(chat)
count = len(participants)
mention = "[{}](tg://user?id={})".format(a_user.first_name, a_user.id)
first = a_user.first_name
last = a_user.last_name
if last:
fullname = f"{first} {last}"
else:
fullname = first
userid = a_user.id
current_saved_welcome_message = cws.custom_welcome_message
mention = "[{}](tg://user?id={})".format(a_user.first_name, a_user.id)
current_message = await event.reply(
current_saved_welcome_message.format(
mention=mention,
title=title,
count=count,
first=first,
last=last,
fullname=fullname,
username=username,
userid=userid,
),
file=cws.media_file_id,
)
update_previous_welcome(event.chat_id, current_message.id)
@admin_cmd("savewelcome",is_args=True)
@only_groups
@is_bot_admin
@is_admin
@change_info
async def _(event):
if event.fwd_from:
return
msg = await event.get_reply_message()
if msg and msg.media:
bot_api_file_id = pack_bot_file_id(msg.media)
add_welcome_setting(event.chat_id, msg.message, True, 0, bot_api_file_id)
await event.reply("Welcome note saved. ")
else:
input_str = event.text.split(None, 1)
add_welcome_setting(event.chat_id, input_str[1], True, 0, None)
await event.reply("Welcome note saved. ")
@admin_cmd("clearwelcome",is_args=True)
@only_groups
@is_bot_admin
@is_admin
@change_info
async def _(event):
if event.fwd_from:
return
cws = get_current_welcome_settings(event.chat_id)
rm_welcome_setting(event.chat_id)
await event.reply(
"Welcome note cleared. "
+ "The previous welcome message was `{}`.".format(cws.custom_welcome_message)
)
@admin_cmd("welcome", is_args="False")
@only_groups
@is_bot_admin
@is_admin
async def _(event):
if event.fwd_from:
return
cws = get_current_welcome_settings(event.chat_id)
if hasattr(cws, "custom_welcome_message"):
await event.reply(
"Welcome note found. "
+ "Your welcome message is\n\n`{}`.".format(cws.custom_welcome_message)
)
else:
await event.reply("No Welcome Message found")
#===================================================================================================
#Global
DELETE_TIMEOUT = 0
TYPE_TEXT = 0
TYPE_PHOTO = 1
TYPE_DOCUMENT = 2
global last_triggered_filters
last_triggered_filters = {} # pylint:disable=E0602
# ===================================================================================================
#Filters
@adminbot.on(events.NewMessage(incoming=True))
async def on_snip(event):
global last_triggered_filters
name = event.raw_text
if event.chat_id in last_triggered_filters:
if name in last_triggered_filters[event.chat_id]:
return False
snips = get_all_filters(event.chat_id)
if snips:
for snip in snips:
pattern = r"( |^|[^\w])" + re.escape(snip.keyword) + r"( |$|[^\w])"
if re.search(pattern, name, flags=re.IGNORECASE):
if snip.snip_type == TYPE_PHOTO:
media = types.InputPhoto(
int(snip.media_id),
int(snip.media_access_hash),
snip.media_file_reference,
)
elif snip.snip_type == TYPE_DOCUMENT:
media = types.InputDocument(
int(snip.media_id),
int(snip.media_access_hash),
snip.media_file_reference,
)
else:
media = None
event.message.id
if event.reply_to_msg_id:
event.reply_to_msg_id
await event.reply(snip.reply, file=media)
if event.chat_id not in last_triggered_filters:
last_triggered_filters[event.chat_id] = []
last_triggered_filters[event.chat_id].append(name)
await asyncio.sleep(DELETE_TIMEOUT)
last_triggered_filters[event.chat_id].remove(name)
@admin_cmd("savefilter",is_args=True)
@only_groups
@is_bot_admin
@is_admin
@change_info
async def on_snip_save(event):
name = event.pattern_match.group(1)
msg = await event.get_reply_message()
if msg:
snip = {"type": TYPE_TEXT, "text": msg.message or ""}
if msg.media:
media = None
if isinstance(msg.media, types.MessageMediaPhoto):
media = utils.get_input_photo(msg.media.photo)
snip["type"] = TYPE_PHOTO
elif isinstance(msg.media, types.MessageMediaDocument):
media = utils.get_input_document(msg.media.document)
snip["type"] = TYPE_DOCUMENT
if media:
snip["id"] = media.id
snip["hash"] = media.access_hash
snip["fr"] = media.file_reference
add_filter(
event.chat_id,
name,
snip["text"],
snip["type"],
snip.get("id"),
snip.get("hash"),
snip.get("fr"),
)
await event.reply(f"Filter {name} saved successfully. Get it with `{name}`")
else:
await event.reply("Reply to a message with `/savefilter <keyword>` to save the filter")
@admin_cmd("filters",is_args=True)
@only_groups
@is_bot_admin
async def on_snip_list(event):
all_snips = get_all_filters(event.chat_id)
OUT_STR = "Available Filters in the Current Chat:\n"
if len(all_snips) > 0:
for a_snip in all_snips:
OUT_STR += f" - {a_snip.keyword} \n"
else:
OUT_STR = "No Filters in Current Chat"
if len(OUT_STR) > 4096:
with io.BytesIO(str.encode(OUT_STR)) as out_file:
out_file.name = "filters.text"
await adminbot.send_file(
event.chat_id,
out_file,
force_document=True,
allow_cache=False,
caption="Available Filters in the Current Chat",
reply_to=event,
)
await event.delete()
else:
await event.reply(OUT_STR)
@admin_cmd("stop",is_args=True)
@only_groups
@is_bot_admin
@is_admin
@change_info
async def on_snip_delete(event):
name = event.pattern_match.group(1)
remove_filter(event.chat_id, name)
await event.reply(f"Filter `{name}` deleted successfully")
@admin_cmd("clearallfilters",is_args=False)
@only_groups
@is_bot_admin
@is_admin
@chat_creator
async def on_all_snip_delete(event):
remove_all_filters(event.chat_id)
await event.reply(f"Filters **in current chat** deleted successfully")
#====================================================================================================
#Notes
@adminbot.on(events.NewMessage(pattern=r"\#(\S+)"))
async def on_snip(event):
name = event.pattern_match.group(1)
snip = get_snips(event.chat_id, name)
if snip:
if snip.snip_type == TYPE_PHOTO:
media = types.InputPhoto(
int(snip.media_id),
int(snip.media_access_hash),
snip.media_file_reference
)
elif snip.snip_type == TYPE_DOCUMENT:
media = types.InputDocument(
int(snip.media_id),
int(snip.media_access_hash),
snip.media_file_reference
)
else:
media = None
message_id = event.message.id
if event.reply_to_msg_id:
message_id = event.reply_to_msg_id
await event.client.send_message(
event.chat_id,
snip.reply,
reply_to=message_id,
file=media
)