This repository has been archived by the owner on Oct 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.py
915 lines (859 loc) · 31.3 KB
/
main.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import copy
import datetime
import os
import re
import time
from io import BytesIO
from random import SystemRandom
from typing import Optional, Tuple
from telegram import (
CallbackQuery,
ChatAdministratorRights,
ChatPermissions,
InlineKeyboardButton,
InlineKeyboardMarkup,
ParseMode,
Poll,
)
from telegram.error import BadRequest
from telegram.ext import (
CallbackQueryHandler,
CommandHandler,
ConversationHandler,
Filters,
MessageHandler,
PicklePersistence,
Updater,
)
from telegram.ext.callbackcontext import CallbackContext
from telegram.ext.filters import MergedFilter
from telegram.update import Update
from telegram.utils.helpers import mention_markdown
from utils import (
FullChatPermissions,
get_chat_admins,
get_chat_admins_name,
load_config,
log_to_file,
log_to_stream,
logger,
yaml,
)
def escape_markdown(text: str) -> str:
# Use {} and reverse markdown carefully.
parse = re.sub(r"([_*\[\]()~`>\#\+\-=|\.!])", r"\\\1", text)
reparse = re.sub(r"\\\\([_*\[\]()~`>\#\+\-=|\.!])", r"\1", parse)
return reparse
def start_command(update: Update, context: CallbackContext) -> None:
message = update.message
chat = message.chat
user = message.from_user
message.reply_text(
escape_markdown(context.bot_data.get("config").get("START")).format(
chat=chat.id, user=user.id
),
parse_mode=ParseMode.MARKDOWN_V2,
)
logger.info(
f"Current Jobs: {[t.id for t in context.job_queue.scheduler.get_jobs()]}"
)
def kick(context: CallbackContext, chat_id: int, user_id: int) -> bool:
if context.bot.ban_chat_member(
chat_id=chat_id,
user_id=user_id,
until_date=int(time.time()) + context.bot_data.get("config").get("BANTIME"),
):
logger.info(f"Job kick: Successfully kicked user {user_id} at group {chat_id}")
return True
else:
logger.warning(
f"Job kick: No enough permissions to kick user {user_id} at group {chat_id}"
)
return False
def restore(context: CallbackContext, chat_id: int, user_id: int) -> bool:
if context.bot.restrict_chat_member(
chat_id=chat_id,
user_id=user_id,
permissions=FullChatPermissions,
):
logger.info(
f"Job restore: Successfully restored user {user_id} at group {chat_id}"
)
return True
else:
logger.warning(
f"Job restore: No enough permissions to restore user {user_id} at group {chat_id}"
)
return False
def clean(
context: CallbackContext, chat_id: int, user_id: int, message_id: int
) -> bool:
if context.bot.delete_message(chat_id=chat_id, message_id=message_id):
logger.info(
f"Job clean: Successfully delete message {message_id} from {user_id} at group {chat_id}"
)
return True
else:
logger.warning(
f"Job clean: No enough permissions to delete message {message_id} from {user_id} at group {chat_id}"
)
return False
def newmem(update: Update, context: CallbackContext) -> None:
message = update.message
chat = message.chat
if message.from_user.id in get_chat_admins(
context.bot,
chat.id,
extra_user=context.bot_data.get("config").get("SUPER_ADMIN"),
):
return
for user in message.new_chat_members:
if user.is_bot:
continue
num = SystemRandom().randint(
0, len(context.bot_data.get("config").get("CHALLENGE")) - 1
)
flag = context.bot_data.get("config").get("CHALLENGE")[num]
if context.bot.restrict_chat_member(
chat_id=chat.id,
user_id=user.id,
permissions=ChatPermissions(can_send_messages=False),
):
logger.info(
f"New member: Successfully restricted user {user.id} at group {chat.id}"
)
else:
logger.warning(
f"New member: No enough permissions to restrict user {user.id} at group {chat.id}"
)
buttons = [
[
InlineKeyboardButton(
flag.get("WRONG")[t],
callback_data=f"challenge|{user.id}|{num}|{flag.get('wrong')[t]}",
)
]
for t in range(len(flag.get("WRONG")))
]
buttons.append(
[
InlineKeyboardButton(
flag.get("ANSWER"),
callback_data=f"challenge|{user.id}|{num}|{flag.get('answer')}",
)
]
)
SystemRandom().shuffle(buttons)
buttons.append(
[
InlineKeyboardButton(
context.bot_data.get("config").get("PASS_BTN"),
callback_data=f"admin|pass|{user.id}",
),
InlineKeyboardButton(
context.bot_data.get("config").get("KICK_BTN"),
callback_data=f"admin|kick|{user.id}",
),
]
)
question_message = message.reply_text(
escape_markdown(context.bot_data.get("config").get("GREET")).format(
question=escape_markdown(flag.get("QUESTION")),
time=context.bot_data.get("config").get("TIME"),
),
reply_markup=InlineKeyboardMarkup(buttons),
parse_mode=ParseMode.MARKDOWN_V2,
)
context.job_queue.scheduler.add_job(
kick,
"date",
id=f"{chat.id}|{user.id}|kick",
name=f"{chat.id}|{user.id}|kick",
args=[context, chat.id, user.id],
run_date=context.job_queue._tz_now()
+ datetime.timedelta(seconds=context.bot_data.get("config").get("TIME")),
replace_existing=True,
)
context.job_queue.scheduler.add_job(
clean,
"date",
id=f"{chat.id}|{user.id}|clean_join",
name=f"{chat.id}|{user.id}|clean_join",
args=[context, chat.id, user.id, message.message_id],
run_date=context.job_queue._tz_now()
+ datetime.timedelta(seconds=context.bot_data.get("config").get("TIME")),
replace_existing=True,
)
context.job_queue.scheduler.add_job(
clean,
"date",
id=f"{chat.id}|{user.id}|clean_question",
name=f"{chat.id}|{user.id}|clean_question",
args=[context, chat.id, user.id, question_message.message_id],
run_date=context.job_queue._tz_now()
+ datetime.timedelta(seconds=context.bot_data.get("config").get("TIME")),
replace_existing=True,
)
def quiz_command(update: Update, context: CallbackContext) -> None:
num = SystemRandom().randint(
0, len(context.bot_data.get("config").get("CHALLENGE")) - 1
)
flag = context.bot_data.get("config").get("CHALLENGE")[num]
answer = [flag.get("WRONG")[t] for t in range(len(flag.get("WRONG")))]
SystemRandom().shuffle(answer)
index = SystemRandom().randint(0, len(answer) - 1)
answer.insert(index, flag.get("ANSWER"))
update.effective_message.reply_poll(
flag.get("QUESTION"),
answer,
correct_option_id=index,
is_anonymous=False,
open_period=context.bot_data.get("config").get("QUIZTIME"),
type=Poll.QUIZ,
)
def query(update: Update, context: CallbackContext) -> None:
def query_callback(
context: CallbackContext, rawstr: str
) -> Tuple[int, bool, str, str]:
data = rawstr.split("|")
logger.info(f"Parse Callback: {data}")
user_id = int(data[1])
number = int(data[2])
answer = str()
answer_encode = data[3]
question = (
context.bot_data.get("config").get("CHALLENGE")[number].get("QUESTION")
)
if answer_encode == context.bot_data.get("config").get("CHALLENGE")[number].get(
"answer"
):
result = True
answer = (
context.bot_data.get("config").get("CHALLENGE")[number].get("ANSWER")
)
else:
result = False
for t in range(
len(
context.bot_data.get("config").get("CHALLENGE")[number].get("wrong")
)
):
if (
answer_encode
== context.bot_data.get("config")
.get("CHALLENGE")[number]
.get("wrong")[t]
):
answer = (
context.bot_data.get("config")
.get("CHALLENGE")[number]
.get("WRONG")[t]
)
break
logger.info(
f"New challenge parse callback:\nuser_id: {user_id}\nresult: {result}\nquestion: {question}\nanswer: {answer}"
)
return user_id, result, question, answer
callback_query = update.callback_query
user = callback_query.from_user
message = callback_query.message
chat = message.chat
user_id, result, question, answer = query_callback(context, callback_query.data)
if user.id != user_id:
callback_query.answer(
text=context.bot_data.get("config").get("OTHER"),
show_alert=True,
)
return
cqconf = (
context.bot_data.get("config").get("SUCCESS")
if result
else context.bot_data.get("config")
.get("RETRY")
.format(time=context.bot_data.get("config").get("BANTIME"))
)
callback_query.answer(
text=cqconf,
show_alert=False if result else True,
)
if result:
conf = context.bot_data.get("config").get("PASS")
restore(context, chat.id, user_id)
if schedule := context.job_queue.scheduler.get_job(
f"{chat.id}|{user.id}|clean_join"
):
schedule.remove()
else:
if kick(context, chat.id, user_id):
conf = context.bot_data.get("config").get("KICK")
else:
conf = context.bot_data.get("config").get("NOT_KICK")
message.edit_text(
escape_markdown(conf).format(
user=user.mention_markdown_v2(),
question=escape_markdown(question),
ans=escape_markdown(answer),
),
parse_mode=ParseMode.MARKDOWN_V2,
)
if schedule := context.job_queue.scheduler.get_job(f"{chat.id}|{user.id}|kick"):
schedule.remove()
def admin(update: Update, context: CallbackContext) -> None:
def admin_callback(rawstr: str) -> Tuple[bool, int]:
data = rawstr.split("|")
logger.info(f"Parse Callback: {data}")
if data[1] == "pass":
result = True
else:
result = False
user_id = int(data[2])
logger.info(f"New admin parse callback:\nuser_id: {user_id}\nresult: {result}")
return result, user_id
callback_query = update.callback_query
user = callback_query.from_user
message = callback_query.message
chat = message.chat
if user.id not in get_chat_admins(
context.bot,
chat.id,
extra_user=context.bot_data.get("config").get("SUPER_ADMIN"),
):
callback_query.answer(
text=context.bot_data.get("config").get("OTHER"),
show_alert=True,
)
return
result, user_id = admin_callback(callback_query.data)
cqconf = (
context.bot_data.get("config").get("PASS_BTN")
if result
else context.bot_data.get("config").get("KICK_BTN")
)
conf = (
context.bot_data.get("config").get("ADMIN_PASS")
if result
else context.bot_data.get("config").get("ADMIN_KICK")
)
callback_query.answer(
text=cqconf,
show_alert=False,
)
if result:
restore(context, chat.id, user_id)
if schedule := context.job_queue.scheduler.get_job(
f"{chat.id}|{user_id}|clean_join"
):
schedule.remove()
else:
kick(context, chat.id, user_id)
message.edit_text(
escape_markdown(conf).format(
admin=user.mention_markdown_v2(),
user=mention_markdown(user_id, str(user_id), version=2),
),
parse_mode=ParseMode.MARKDOWN_V2,
)
if schedule := context.job_queue.scheduler.get_job(f"{chat.id}|{user_id}|kick"):
schedule.remove()
def admin_command(update: Update, context: CallbackContext) -> None:
message = update.message
message.reply_text(get_chat_admins_name(context.bot, message.chat.id))
def private_callback(rawstr: str) -> int:
data = rawstr.split("|")
logger.info(f"Parse Callback: {data}")
if data[0] in [
"detail_question_private",
"edit_question_private",
"delete_question_private",
]:
number = int(data[1])
logger.info(f"New private parse callback:\nresult: {number}")
return number
else:
return 0
def reload_private(update: Update, context: CallbackContext) -> None:
message = update.message
logger.info(f"Private: Reloaded config")
message.reply_text(reload_config(context))
def start_private(update: Update, context: CallbackContext) -> int:
message = update.message
callback_query = update.callback_query
if callback_query:
callback_query.answer()
user = callback_query.from_user
else:
user = message.from_user
if user.id not in get_chat_admins(
context.bot,
context.bot_data.get("config").get("CHAT"),
extra_user=context.bot_data.get("config").get("SUPER_ADMIN"),
):
logger.info(f"Private: User {user.id} is unauthorized, blocking")
message.reply_text(
context.bot_data.get("config").get("START_UNAUTHORIZED_PRIVATE")
)
return ConversationHandler.END
keyboard = [
[
InlineKeyboardButton(
context.bot_data.get("config").get("SAVE_QUESTION_BTN"),
callback_data="save",
)
],
[
InlineKeyboardButton(
context.bot_data.get("config").get("ADD_NEW_QUESTION_BTN"),
callback_data=f'edit_question_private|{len(context.bot_data.get("config").get("CHALLENGE"))}',
)
],
[
InlineKeyboardButton(
context.bot_data.get("config").get("LIST_ALL_QUESTION_BTN"),
callback_data="list_question_private",
)
],
]
markup = InlineKeyboardMarkup(keyboard)
if callback_query:
callback_query.edit_message_text(
context.bot_data.get("config")
.get("START_PRIVATE")
.format(link=context.bot_data.get("config").get("CHAT")),
reply_markup=markup,
)
else:
message.reply_text(
context.bot_data.get("config")
.get("START_PRIVATE")
.format(link=context.bot_data.get("config").get("CHAT")),
reply_markup=markup,
)
logger.info("Private: Start")
logger.info(
f"Current Jobs: {[t.id for t in context.job_queue.scheduler.get_jobs()]}"
)
logger.debug(callback_query)
return CHOOSING
def list_question_private(update: Update, context: CallbackContext) -> int:
callback_query = update.callback_query
callback_query.answer()
logger.debug(context.bot_data.get("config").get("CHALLENGE"))
keyboard = [
[
InlineKeyboardButton(
flag.get("QUESTION"), callback_data=f"detail_question_private|{num}"
)
]
for (num, flag) in enumerate(context.bot_data.get("config").get("CHALLENGE"))
]
keyboard.insert(
0,
[
InlineKeyboardButton(
context.bot_data.get("config").get("BACK"), callback_data="back"
)
],
)
markup = InlineKeyboardMarkup(keyboard)
callback_query.edit_message_text(
context.bot_data.get("config").get("LIST_PRIVATE"), reply_markup=markup
)
logger.info("Private: List question")
logger.debug(callback_query)
return LIST_VIEW
def detail_question_private(update: Update, context: CallbackContext) -> int:
callback_query = update.callback_query
callback_query.answer()
num = private_callback(callback_query.data)
keyboard = [
[
InlineKeyboardButton(
context.bot_data.get("config").get("BACK"), callback_data="back"
)
],
[
InlineKeyboardButton(
context.bot_data.get("config").get("EDIT_QUESTION_BTN"),
callback_data=f"edit_question_private|{num}",
)
],
[
InlineKeyboardButton(
context.bot_data.get("config").get("DELETE_QUESTION_BTN"),
callback_data=f"delete_question_private|{num}",
)
],
]
markup = InlineKeyboardMarkup(keyboard)
flag = context.bot_data.get("config").get("CHALLENGE")[num]
callback_query.edit_message_text(
context.bot_data.get("config")
.get("DETAIL_QUESTION_PRIVATE")
.format(
question=flag.get("QUESTION"),
ans=flag.get("ANSWER"),
wrong="\n".join(flag.get("WRONG")),
),
reply_markup=markup,
)
logger.info("Private: Detail question")
logger.debug(callback_query)
return DETAIL_VIEW
def save_private(context: CallbackContext, callback_query: CallbackQuery) -> None:
if context.bot_data.get("config"):
save_config(context.bot_data["config"], filename)
context.chat_data.clear()
keyboard = [
[
InlineKeyboardButton(
context.bot_data.get("config").get("BACK"), callback_data="back"
)
],
]
markup = InlineKeyboardMarkup(keyboard)
callback_query.edit_message_text(
reload_config(context),
reply_markup=markup,
)
logger.info(f"Private: Saved config")
logger.debug(context.bot_data.get("config"))
def delete_question_private(update: Update, context: CallbackContext) -> int:
callback_query = update.callback_query
callback_query.answer()
callback_query.edit_message_text(
context.bot_data.get("config").get("DELETING_PRIVATE")
)
num = private_callback(callback_query.data)
tile = context.bot_data.get("config").get("CHALLENGE").pop(num)
logger.info(f"Private: Delete question {tile}")
save_private(context, callback_query)
return DETAIL_VIEW
def edit_question_private(update: Update, context: CallbackContext) -> int:
message = update.message
callback_query = update.callback_query
if callback_query:
text = "Begin"
callback_query.answer()
index = private_callback(callback_query.data)
context.chat_data.clear()
context.chat_data.update(index=index)
callback_query.edit_message_text(
context.bot_data.get("config")
.get("EDIT_QUESTION_PRIVATE")
.format(num=index + 1)
)
elif message:
text = message.text
if not context.chat_data.get("QUESTION"):
context.chat_data.update(QUESTION=text)
return_text = (
context.bot_data.get("config")
.get("EDIT_ANSWER_PRIVATE")
.format(text=text)
)
elif not context.chat_data.get("ANSWER"):
context.chat_data.update(ANSWER=text)
return_text = (
context.bot_data.get("config")
.get("EDIT_WRONG_PRIVATE")
.format(text=text)
)
else:
if not context.chat_data.get("WRONG"):
context.chat_data["WRONG"] = list()
context.chat_data.get("WRONG").append(text)
return_text = (
context.bot_data.get("config")
.get("EDIT_MORE_WRONG_PRIVATE")
.format(text=text)
)
message.reply_text(
context.bot_data.get("config").get("EDIT_PRIVATE").format(text=return_text)
)
logger.info(f"Private: Edit question {text}")
return QUESTION_EDIT
def finish_edit_private(update: Update, context: CallbackContext) -> int:
message = update.message
if not context.chat_data.get("WRONG"):
message.reply_text(context.bot_data.get("config").get("EDIT_UNFINISH_PRIVATE"))
return QUESTION_EDIT
index = context.chat_data.get("index")
keyboard = [
[
InlineKeyboardButton(
context.bot_data.get("config").get("SAVE_QUESTION_BTN"),
callback_data="save",
)
],
[
InlineKeyboardButton(
context.bot_data.get("config").get("REEDIT_QUESTION_BTN"),
callback_data=f"edit_question_private|{index}",
)
],
]
markup = InlineKeyboardMarkup(keyboard)
message.reply_text(
"\n".join(
[
context.bot_data.get("config")
.get("EDIT_FINISH_PRIVATE")
.format(num=index + 1),
context.bot_data.get("config")
.get("DETAIL_QUESTION_PRIVATE")
.format(
question=context.chat_data.get("QUESTION"),
ans=context.chat_data.get("ANSWER"),
wrong="\n".join(context.chat_data.get("WRONG", "")),
),
]
),
reply_markup=markup,
)
logger.info(f"Private: Finish edit {context.chat_data}")
return DETAIL_VIEW
def save_question_private(update: Update, context: CallbackContext) -> int:
callback_query = update.callback_query
callback_query.answer()
callback_query.edit_message_text(
context.bot_data.get("config").get("SAVING_PRIVATE")
)
if context.chat_data:
index = (
context.chat_data.pop("index")
if "index" in context.chat_data
else len(context.bot_data.get("config").get("CHALLENGE"))
)
if index < len(context.bot_data.get("config").get("CHALLENGE")):
context.bot_data.get("config").get("CHALLENGE")[
index
] = context.chat_data.copy()
else:
context.bot_data.get("config").get("CHALLENGE").append(
context.chat_data.copy()
)
logger.info(f"Private: Saving question {context.chat_data}")
save_private(context, callback_query)
return DETAIL_VIEW
def cancel_private(update: Update, context: CallbackContext) -> int:
message = update.message
context.chat_data.clear()
message.reply_text(context.bot_data.get("config").get("CANCEL_PRIVATE"))
logger.info(f"Private: Cancel")
return ConversationHandler.END
def config_private(update: Update, context: CallbackContext) -> int:
message = update.message
with open(filename, "rb") as file:
message.reply_document(file)
logger.info(f"Private: Config")
return ConversationHandler.END
def config_file_private(update: Update, context: CallbackContext) -> None:
message = update.effective_message
file_id = message.document.file_id
filestream = updater.bot.get_file(file_id)
if filestream:
file = BytesIO()
filestream.download(out=file)
logger.info(f"Private: Config file successfully downloaded {file_id}")
try:
with file:
config = load_config(yaml.load(file.getvalue()), check_token=False)
save_config(config, filename)
message.reply_text(reload_config(context))
except Exception as err:
logger.error(err)
message.reply_text(
context.bot_data.get("config").get("CORRUPT").format(text=err.__str__())
)
def reload_config(context: CallbackContext) -> str:
for job in context.job_queue.get_jobs_by_name("reload"):
job.schedule_removal()
if jobs := [t.id for t in context.job_queue.scheduler.get_jobs()]:
context.job_queue.scheduler.add_job(
reload_config,
"date",
name="reload",
run_date=context.job_queue._tz_now()
+ datetime.timedelta(seconds=context.bot_data.get("config").get("TIME")),
replace_existing=True,
)
logger.info(f"Job reload: Waiting for {jobs}")
return context.bot_data.get("config").get("PENDING")
else:
try:
with open(filename, "r", encoding="utf-8") as file:
context.bot_data.update(
config=load_config(yaml.load(file), check_token=False)
)
logger.info(f"Job reload: Successfully reloaded {filename}")
return (
context.bot_data.get("config")
.get("RELOAD")
.format(num=len(context.bot_data.get("config").get("CHALLENGE")))
)
except Exception as err:
logger.error(err)
return (
context.bot_data.get("config").get("CORRUPT").format(text=err.__str__())
)
def save_config(config: dict, name: Optional[str] = None) -> None:
save = copy.deepcopy(config)
if not name:
name = f"{filename}.bak"
for flag in save.get("CHALLENGE"):
if flag.get("answer"):
flag.pop("answer")
if flag.get("wrong"):
flag.pop("wrong")
if flag.get("index"):
flag.pop("index")
save["TOKEN"] = updater.bot.token
with open(name, "w") as file:
yaml.dump(save, file)
logger.info(f"Config: Dumped {name}")
logger.debug(save)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Telegram Group Easy Auth.")
default_filename = (
f"{os.path.split(os.path.realpath(__file__))[0] + os.path.sep}config.yml"
)
parser.add_argument(
"file",
metavar="config",
default=default_filename,
help=f"path to config.yml, defaults to {default_filename}",
nargs="?",
type=str,
)
parser.add_argument(
"-d",
"--debug",
action="store_true",
help="enable logging to file",
)
args = parser.parse_args()
filename = os.path.abspath(args.file)
if not os.path.exists(filename):
parser.error(f"The file {filename} does not exist!")
log_to_stream()
if args.debug:
log_to_file(f"{filename}.log")
with open(filename, "r", encoding="utf-8") as file:
config = load_config(yaml.load(file))
logger.info(f"Yaml: Loaded {filename}")
command = list()
updater = Updater(config.get("TOKEN"))
save_config(config)
updater.dispatcher.bot_data.update(config=config)
updater.dispatcher.add_handler(
CommandHandler("start", start_command, filters=Filters.chat_type.groups)
)
chatfilter = Filters.chat(config.get("CHAT")) if config.get("CHAT") else None
updater.dispatcher.add_handler(
MessageHandler(
MergedFilter(Filters.status_update.new_chat_members, and_filter=chatfilter),
newmem,
run_async=True,
)
)
updater.dispatcher.add_handler(CallbackQueryHandler(query, pattern=r"^challenge\|"))
updater.dispatcher.add_handler(CallbackQueryHandler(admin, pattern=r"^admin\|"))
if config.get("CHAT"):
try:
updater.bot.get_chat_administrators(config.get("CHAT"))
except BadRequest as err:
logger.error(err)
else:
CHOOSING, LIST_VIEW, DETAIL_VIEW, QUESTION_EDIT = range(4)
conv_handler = ConversationHandler(
entry_points=[
CommandHandler(
"start", start_private, filters=Filters.chat_type.private
)
],
states={
CHOOSING: [
CallbackQueryHandler(save_question_private, pattern=r"^save$"),
CallbackQueryHandler(
edit_question_private, pattern=r"^edit_question_private"
),
CallbackQueryHandler(
list_question_private, pattern=r"^list_question_private"
),
],
LIST_VIEW: [
CallbackQueryHandler(start_private, pattern=r"^back$"),
CallbackQueryHandler(
detail_question_private, pattern=r"^detail_question_private"
),
],
DETAIL_VIEW: [
CallbackQueryHandler(save_question_private, pattern=r"^save$"),
CallbackQueryHandler(list_question_private, pattern=r"^back$"),
CallbackQueryHandler(
delete_question_private, pattern=r"^delete_question_private"
),
CallbackQueryHandler(
edit_question_private, pattern=r"^edit_question_private"
),
],
QUESTION_EDIT: [
MessageHandler(
Filters.text & ~Filters.command, edit_question_private
),
CommandHandler("finish", finish_edit_private),
],
},
fallbacks=[
CommandHandler("cancel", cancel_private),
CommandHandler("config", config_private),
CommandHandler("reload", reload_private),
MessageHandler(
Filters.document,
config_file_private,
),
],
name="setting",
allow_reentry=True,
# persistent=True,
)
updater.dispatcher.add_handler(conv_handler)
logger.info("Enhanced admin control enabled for private chat.")
if config.get("QUIZ"):
updater.dispatcher.add_handler(
CommandHandler("quiz", quiz_command, filters=chatfilter)
)
command.append(["quiz", config.get("QUIZ")])
logger.info("Quiz command registered.")
if config.get("ADMIN"):
updater.dispatcher.add_handler(
CommandHandler("admin", admin_command, filters=chatfilter)
)
command.append(["admin", config.get("ADMIN")])
logger.info("Admin command registered.")
if (DOMAIN := os.environ.get("DOMAIN")) and (TOKEN := config.get("TOKEN")):
updater.start_webhook(
listen="0.0.0.0",
port=int(os.environ.get("PORT", 8080)),
url_path=TOKEN,
webhook_url=DOMAIN + TOKEN,
)
else:
updater.start_polling()
bot_me = updater.bot.get_me()
rights = ChatAdministratorRights.no_rights()
rights.can_manage_chat=True
rights.can_delete_messages=True
rights.can_restrict_members=True
updater.bot.set_my_default_administrator_rights(rights=rights)
logger.info(f"Bot's default administrator rights modified: {updater.bot.get_my_default_administrator_rights()}")
if not bot_me.can_join_groups:
logger.error(f"Bot's [Allow groups] should be enabled.")
if bot_me.can_read_all_group_messages:
logger.warning(f"Bot's [Group privacy] could be enabled.")
updater.bot.set_my_commands(command)
logger.info(f"Bot @{bot_me.username} started.")
updater.idle()