-
Notifications
You must be signed in to change notification settings - Fork 1
/
ton_vs_bot.py
2932 lines (2360 loc) · 92 KB
/
ton_vs_bot.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
import datetime
import json
import os
import random
import re
import traceback
from time import sleep, time
import psycopg2
import telegram
from constants import *
from speaking import *
from subjects import *
SHIT_COUNTER = 0
CURRENT_UPDATE_ID = 0
BOT = None
CON = None
CUR = None
MAP_OF_CHANNEL_MESSAGE_ID_AND_USER_ID = {}
QUEUE_OF_MESSAGES_DICT = {}
QUEUE_OF_EDITED_MESSAGES_DICT = {}
LAST_TIME_OF_MESSAGE_FROM_BOT_TO_USER_DICT = {}
LAST_TIME_OF_MESSAGE_FROM_BOT_TO_CHAT_DICT = {}
LAST_TIME_OF_GREETING_MESSAGE_DICT = {}
LAST_TIME_OF_FLOOD_CONTROL_CAUTION_DICT = {}
separator = '\n\n' + '-' * 64 + '\n\n'
def gaga():
global SHIT_COUNTER
while True:
try:
main()
sleep(3)
except:
shit_message = f'SHIT...\n' \
f'SHIT_COUNTER: {SHIT_COUNTER}\n' \
f'time: {datetime.datetime.utcnow()}\n' \
f'\n' \
f'{traceback.format_exc()}'
print(shit_message + separator)
sleep(2 ** SHIT_COUNTER)
SHIT_COUNTER += 1
def main():
start_message = f'start {datetime.datetime.utcnow()}'
if SHIT_COUNTER:
start_message += f'\n\nSHIT_COUNTER: {SHIT_COUNTER}'
print(start_message + separator)
global BOT
global CON
global CUR
try:
if heroku:
bot_token = os.environ['bot_token']
db_uri = os.environ['DATABASE_URL']
sslmode = 'require'
else:
bot_token = __import__('gag_secrets').bot_token
db_uri = __import__('gag_secrets').db_uri
sslmode = None
BOT = telegram.Bot(bot_token)
tg_delay(log_chat_id)
BOT.send_message(log_chat_id, start_message, disable_notification=True)
with psycopg2.connect(db_uri, sslmode=sslmode) as CON:
with CON.cursor() as CUR:
while True:
run()
except:
my_traceback(1)
def run():
global CURRENT_UPDATE_ID
update = None
try:
try:
updates = BOT.get_updates(offset=CURRENT_UPDATE_ID, timeout=60)
except (telegram.error.TimedOut, telegram.error.Conflict) as exc:
minor_error(exc)
return
for update in updates:
if not CURRENT_UPDATE_ID:
CURRENT_UPDATE_ID = update.update_id
handle_update(update)
CURRENT_UPDATE_ID = update.update_id + 1
cleaning()
except telegram.error.RetryAfter as exc:
retry_after_message = f'sleep {exc.retry_after} seconds, because telegram.error.RetryAfter'
print(retry_after_message + separator)
sleep(exc.retry_after)
my_traceback(2, 'telegram.error.RetryAfter')
except psycopg2.Error:
CON.rollback()
my_traceback(2, 'psycopg2.Error', update)
CURRENT_UPDATE_ID += 1
except:
my_traceback(2, None, update)
CURRENT_UPDATE_ID += 1
def handle_update(update):
if update.message:
message = update.message
user = message.from_user
elif update.edited_message:
message = update.edited_message
user = message.from_user
elif update.callback_query:
message = update.callback_query.message
user = update.callback_query.from_user
elif update.channel_post or update.edited_channel_post:
if update.channel_post:
channel_post = update.channel_post
elif update.edited_channel_post:
channel_post = update.edited_channel_post
else:
assert False
if channel_post.chat.id == channel_chat_id or channel_post.chat.id in subjects_channels.values():
pass
else:
BOT.leave_chat(channel_post.chat.id)
return
else:
return
if not mute_control(user):
return
if not flood_control(update):
return
if message.chat.id < 0 and message.chat.id not in {channel_chat_id, group_chat_id, log_chat_id}:
if not message.left_chat_member:
BOT.leave_chat(message.chat.id)
return
CUR.execute(
'SELECT 1 FROM updates WHERE update_id = %s',
(update.update_id,)
)
query_result = CUR.fetchone()
if not query_result:
CUR.execute(
'INSERT INTO updates (update_id, "update") VALUES (%s, %s)',
(update.update_id, str(update))
)
CON.commit()
if update.message:
if message.from_user.id == 777000 and message.sender_chat.id == channel_chat_id:
message_from_channel(message)
elif message.chat.id == group_chat_id:
message_in_group(message)
elif message.chat.id > 0:
private_message(message)
elif update.edited_message:
handle_edited_message(message)
elif update.callback_query:
handle_callback_query(update)
CUR.execute(
'UPDATE updates SET passed = true WHERE update_id = %s',
(update.update_id,)
)
CON.commit()
def mute_control(tg_user):
CUR.execute(
'SELECT muted_until FROM muted_users WHERE user_id = %s',
(tg_user.id,)
)
query_result = CUR.fetchone()
if query_result:
muted_until = query_result[0]
if muted_until:
if datetime.datetime.utcnow() > muted_until:
CUR.execute(
'DELETE FROM muted_users WHERE user_id = %s',
(tg_user.id,)
)
CON.commit()
update_channel_posts(tg_user)
return True
else:
return False
else:
return False
else:
return True
def flood_control(update):
def count(user_id, date, seconds):
CUR.execute(
'''
select
count(*)
from
flood_control
where
user_id = %s
and "timestamp" < %s
and "timestamp" > %s
''',
(
user_id,
date,
date - datetime.timedelta(seconds=seconds)
)
)
query_result = CUR.fetchone()
return query_result[0]
def caution(message, date, reason):
def send_caution(date):
add_to_history(
timestamp=date,
type='bot_action',
user_id=message.from_user.id,
volunteer_id=None,
column_0='flood_control_caution',
column_1=reason,
column_2=None
)
date = date.replace(tzinfo=None)
report_message = 'flood control\n' \
'user caution\n' \
'\n' \
'user_id: {}\n' \
'reason: {}\n' \
'message time: {}\n' \
'bot time: {}'.format(
message.from_user.id,
reason,
date,
datetime.datetime.utcnow()
)
tg_delay(log_chat_id)
BOT.send_message(log_chat_id, report_message)
CUR.execute(
'SELECT group_message_id FROM message_ids WHERE user_id = %s',
(message.from_user.id,)
)
query_result = CUR.fetchone()
if query_result:
group_message_id = query_result[0]
message_to_comments = '`❗ Flood control. Caution. {}`'.format(reason)
tg_delay(group_chat_id)
BOT.send_message(
group_chat_id,
message_to_comments,
reply_to_message_id=group_message_id,
allow_sending_without_reply=True,
parse_mode='MarkdownV2'
)
speaking('flood_control_caution', message, reply=True, mono=True)
LAST_TIME_OF_FLOOD_CONTROL_CAUTION_DICT[message.from_user.id] = time()
if message.from_user.id in LAST_TIME_OF_FLOOD_CONTROL_CAUTION_DICT:
time_value = 60 * 5
if time() - LAST_TIME_OF_FLOOD_CONTROL_CAUTION_DICT[message.from_user.id] > time_value:
send_caution(date)
else:
send_caution(date)
def mute(message, date, reason):
CUR.execute(
'INSERT INTO muted_users (user_id) VALUES (%s)',
(message.from_user.id,)
)
CON.commit()
add_to_history(
timestamp=date,
type='bot_action',
user_id=message.from_user.id,
volunteer_id=None,
column_0='mute_user',
column_1='flood_control',
column_2=reason
)
date = date.replace(tzinfo=None)
report_message = f'flood control\n' \
f'mute user\n' \
f'\n' \
f'user_id: {message.from_user.id}\n' \
f'reason: {reason}\n' \
f'message time: {date}\n' \
f'bot time: {datetime.datetime.utcnow()}'
tg_delay(log_chat_id)
BOT.send_message(log_chat_id, report_message)
update_channel_posts(message.from_user)
CUR.execute(
'SELECT group_message_id FROM message_ids WHERE user_id = %s',
(message.from_user.id,)
)
query_result = CUR.fetchone()
if query_result:
group_message_id = query_result[0]
message_to_comments = '`❗ Flood control. {}. User was muted forever`'.format(reason)
tg_delay(group_chat_id)
BOT.send_message(
group_chat_id,
message_to_comments,
reply_to_message_id=group_message_id,
allow_sending_without_reply=True,
parse_mode='MarkdownV2'
)
speaking('flood_control_mute', message, reply=True, mono=True)
################
if update.message:
message = update.message
date = update.message.date
elif update.edited_message:
message = update.edited_message
date = update.edited_message.edit_date
elif update.callback_query:
return True
else:
assert False
if message.from_user.id == 777000:
return True
count_of_60_sec = count(message.from_user.id, date, 60)
if count_of_60_sec > 20:
mute(message, date, '> 20 messages per 60 sec')
return False
elif count_of_60_sec > 13:
caution(message, date, '> 13 messages per 60 sec')
count_of_3600_sec = count(message.from_user.id, date, 3600)
if count_of_3600_sec > 300:
mute(message, date, '> 300 messages per 3600 sec')
return False
elif count_of_3600_sec > 200:
caution(message, date, '> 200 messages per 3600 sec')
count_of_86400_sec = count(message.from_user.id, date, 86400)
if count_of_86400_sec > 1000:
mute(message, date, '> 1000 messages per 86400 sec')
return False
elif count_of_86400_sec > 900:
caution(message, date, '> 900 messages per 86400 sec')
CUR.execute(
'INSERT INTO flood_control ("timestamp", user_id) VALUES (%s, %s)',
(date, message.from_user.id)
)
CON.commit()
return True
def message_from_channel(message):
if message.forward_from_message_id in MAP_OF_CHANNEL_MESSAGE_ID_AND_USER_ID:
user_id = MAP_OF_CHANNEL_MESSAGE_ID_AND_USER_ID[message.forward_from_message_id]
CUR.execute(
'INSERT INTO message_ids (user_id, channel_message_id, group_message_id) VALUES (%s, %s, %s)',
(
user_id,
message.forward_from_message_id,
message.message_id
)
)
CON.commit()
queue_of_messages_list = QUEUE_OF_MESSAGES_DICT[user_id].copy()
queue_of_edited_messages_list = QUEUE_OF_EDITED_MESSAGES_DICT[user_id].copy()
del QUEUE_OF_EDITED_MESSAGES_DICT[user_id]
del QUEUE_OF_MESSAGES_DICT[user_id]
del MAP_OF_CHANNEL_MESSAGE_ID_AND_USER_ID[message.forward_from_message_id]
for message_from_queue in queue_of_messages_list:
if message_from_queue.__class__.__name__ == 'NotFirstChannelPostMarker':
tg_delay(group_chat_id)
BOT.send_message(
group_chat_id,
'`ℹ replied message not found, created new channel post`',
reply_to_message_id=message.message_id,
allow_sending_without_reply=True,
parse_mode='MarkdownV2'
)
continue
my_forward_message(group_chat_id, message_from_queue, message.message_id)
for edited_message_from_queue in queue_of_edited_messages_list:
handle_edited_message(edited_message_from_queue)
update_channel_posts(user_id, {channel_chat_id})
def message_in_group(message):
if message.reply_to_message:
if (message.text and len(message.text) >= 2 and message.text[0:2] in ['//', '\\\\']) \
or \
(message.reply_to_message.text and len(message.reply_to_message.text) >= 2
and message.reply_to_message.text[0:2] in ['//', '\\\\']):
return
if message.text == '/del':
# add_to_history troubles
CommandsInGroup.delete_message(message)
return
if message.reply_to_message.from_user.id == 777000:
message_id = message.reply_to_message.message_id
CUR.execute(
'SELECT user_id FROM message_ids WHERE group_message_id = %s',
(message_id,)
)
query_result = CUR.fetchone()
if query_result:
user_id = query_result[0]
if message.text and message.text[0] == '/':
command_in_group(message, user_id)
return
my_forward_message(user_id, message)
CUR.execute(
'UPDATE open_users SET time_of_last_message_by_volunteers = %s WHERE user_id = %s',
(message.date, user_id)
)
CON.commit()
else:
speaking('channel_post_is_inactive', message, reply=True, mono=True, eng=True)
else:
speaking('dont_use_reply_in_comments', message, reply=True, mono=True, eng=True)
else:
speaking('dont_send_messages_outside_comments', message, reply=True, mono=True, eng=True)
def private_message(message):
if message.text and message.text[0] == '/':
command_in_pm(message)
return
if message.from_user.id in QUEUE_OF_MESSAGES_DICT:
QUEUE_OF_MESSAGES_DICT[message.from_user.id].append(message)
return
#
CUR.execute(
'SELECT group_message_id FROM message_ids WHERE user_id = %s',
(message.from_user.id,)
)
message_ids_query_result = CUR.fetchone()
# user open status
CUR.execute(
'SELECT 1 FROM open_users WHERE user_id = %s',
(message.from_user.id,)
)
query_result = CUR.fetchone()
if not query_result:
CUR.execute(
'INSERT INTO open_users (user_id, opening_time) VALUES (%s, %s)',
(message.from_user.id, message.date)
)
CON.commit()
add_to_history(
timestamp=message.date,
type='bot_action',
user_id=message.from_user.id,
volunteer_id=None,
column_0='open_user',
column_1=None,
column_2=None
)
if message_ids_query_result:
group_message_id = message_ids_query_result[0]
tg_delay(group_chat_id)
sent_message = BOT.send_message(
group_chat_id,
'`🙋 user just opened`',
reply_to_message_id=group_message_id,
allow_sending_without_reply=True,
parse_mode='MarkdownV2'
)
opening_message_id = sent_message.message_id
else:
opening_message_id = None
update_channel_posts(message.from_user)
if message.from_user.id in LAST_TIME_OF_GREETING_MESSAGE_DICT:
time_value = 86400
if time() - LAST_TIME_OF_GREETING_MESSAGE_DICT[message.from_user.id] > time_value:
CommandsInPM.start(message)
else:
CommandsInPM.start(message)
LAST_TIME_OF_GREETING_MESSAGE_DICT[message.from_user.id] = time()
tg_delay(subjects_channels[''])
sent_message = BOT.send_message(
subjects_channels[''],
channel_post_text(message.from_user, mode=1),
parse_mode='MarkdownV2'
)
subject_cell = {
'opening_message_id': opening_message_id,
'menu_message_id': None,
'subject_path': '',
'posts_in_subject_channels': {
subjects_channels['']: sent_message.message_id
}
}
CUR.execute(
'UPDATE open_users SET subject = %s WHERE user_id = %s',
(json.dumps(subject_cell), message.from_user.id)
)
CON.commit()
# end of user open status
# other
CUR.execute(
'UPDATE open_users SET time_of_last_message_by_user = %s WHERE user_id = %s',
(message.date, message.from_user.id)
)
CON.commit()
#
if message_ids_query_result:
group_message_id = message_ids_query_result[0]
my_forward_message(group_chat_id, message, group_message_id)
else:
create_channel_post(message)
def handle_edited_message(edited_message):
if edited_message.chat.id in QUEUE_OF_EDITED_MESSAGES_DICT:
QUEUE_OF_EDITED_MESSAGES_DICT[edited_message.chat.id].append(edited_message)
return
CUR.execute(
'SELECT chat_id_1, message_id_1 FROM for_updating_messages WHERE chat_id_0 = %s AND message_id_0 = %s',
(edited_message.chat.id, edited_message.message_id)
)
query_result = CUR.fetchone()
if query_result:
try:
chat_id_1 = query_result[0]
message_id_1 = query_result[1]
tg_delay(chat_id_1)
# stickers and video_notes - not editable
# voices - editable only caption
if edited_message.text:
BOT.edit_message_text(
edited_message.text,
chat_id_1,
message_id_1,
entities=edited_message.entities
)
# history_column_1 = 'text'
# history_column_2 = edited_message.text
elif edited_message.photo:
file_id = edited_message.photo[-1].file_id
BOT.edit_message_media(
chat_id_1,
message_id_1,
media=telegram.InputMediaPhoto(
file_id,
caption=edited_message.caption,
caption_entities=edited_message.caption_entities
)
)
# history_column_1 = 'photo'
# history_column_2 = f'{file_id}\n{edited_message.caption}'
elif edited_message.video:
file_id = edited_message.video.file_id
BOT.edit_message_media(
chat_id_1,
message_id_1,
media=telegram.InputMediaVideo(
file_id,
caption=edited_message.caption,
caption_entities=edited_message.caption_entities
)
)
# history_column_1 = 'video'
# history_column_2 = f'{file_id}\n{edited_message.caption}'
elif edited_message.audio:
file_id = edited_message.audio.file_id
BOT.edit_message_media(
chat_id_1,
message_id_1,
media=telegram.InputMediaAudio(
file_id,
caption=edited_message.caption,
caption_entities=edited_message.caption_entities
)
)
# history_column_1 = 'audio'
# history_column_2 = f'{file_id}\n{edited_message.caption}'
elif edited_message.voice:
BOT.edit_message_caption(
chat_id_1,
message_id_1,
caption=edited_message.caption,
caption_entities=edited_message.caption_entities
)
# history_column_1 = 'voice'
# history_column_2 = edited_message.caption
elif edited_message.animation:
file_id = edited_message.animation.file_id
BOT.edit_message_media(
chat_id_1,
message_id_1,
media=telegram.InputMediaAnimation(
file_id,
caption=edited_message.caption,
caption_entities=edited_message.caption_entities
)
)
# history_column_1 = 'animation'
# history_column_2 = f'{file_id}\n{edited_message.caption}'
elif edited_message.document:
file_id = edited_message.document.file_id
BOT.edit_message_media(
chat_id_1,
message_id_1,
media=telegram.InputMediaDocument(
file_id,
caption=edited_message.caption,
caption_entities=edited_message.caption_entities
)
)
# history_column_1 = 'document'
# history_column_2 = f'{file_id}\n{edited_message.caption}'
else:
report = f'info\n' \
f'\n' \
f'unsupported message type in handling edited message\n' \
f'\n' \
f'{str(edited_message)}'
print(report + separator)
tg_delay(log_chat_id)
BOT.send_message(log_chat_id, truncate_big_text(0, report))
return
history_column_1, history_column_2 = get_column_1_and_column_2(edited_message)
if edited_message.chat.id == group_chat_id:
user_id = chat_id_1
volunteer_id = edited_message.from_user.id
history_column_0 = edited_message.message_id
elif edited_message.chat.id > 0:
user_id = edited_message.from_user.id
volunteer_id = None
history_column_0 = message_id_1
else:
assert False
add_to_history(
timestamp=edited_message.edit_date,
type='edited_message',
user_id=user_id,
volunteer_id=volunteer_id,
column_0=history_column_0,
column_1=history_column_1,
column_2=history_column_2
)
except telegram.error.BadRequest as exc:
error_0_text = 'Message is not modified: ' \
'specified new message content and reply markup are exactly the same ' \
'as a current content and reply markup of the message'
error_1_text = 'Message_id_invalid'
error_2_text = 'Message to edit not found'
if str(exc) in {error_0_text, error_1_text, error_2_text}:
pass
else:
raise exc
def handle_callback_query(update):
try:
callback_query = update.callback_query
data = callback_query.data
if not any((
data.startswith('subject:'),
data.startswith('close:'),
)):
return
add_to_history(
timestamp=datetime.datetime.utcnow(),
type='callback_query',
user_id=callback_query.from_user.id,
volunteer_id=None,
column_0=callback_query.id,
column_1=callback_query.data,
column_2=None
)
if data.startswith('subject:') or data.startswith('close:'):
subject_callback(update)
return
except telegram.error.BadRequest as exc:
if str(exc) == 'Query is too old and response timeout expired or query id is invalid':
report = f'info\n' \
f'\n' \
f'{str(exc)}' \
f'\n' \
f'callback_query.id: {update.callback_query.id}\n'
print(report + separator)
tg_delay(log_chat_id)
BOT.send_message(log_chat_id, report)
else:
raise exc
def command_in_pm(message):
text = message.text
add_to_history(
timestamp=message.date,
type='message',
user_id=message.from_user.id,
volunteer_id=None,
column_0=None,
column_1='text',
column_2=message.text
)
if message.from_user.id == DG_user_id:
DG_commands(message)
if text == '/start':
CommandsInPM.start(message)
return
# elif bool(re.match('/lang.*', text)):
# CommandsInPM.lang(message)
# return
if text in {'/l', '/list', '/t', '/taken'}:
volunteers_commands_in_pm(message)
return
def volunteers_commands_in_pm(message):
text = message.text
if is_volunteer(message.from_user):
if text in {'/l', '/list'}:
CommandsInPM.list(message)
return
elif text in {'/t', '/taken'}:
CommandsInPM.taken(message)
return
class CommandsInPM:
@staticmethod
def start(message):
speaking('greeting_message', message, markdown=True)
LAST_TIME_OF_GREETING_MESSAGE_DICT[message.from_user.id] = time()
@staticmethod
def lang(message):
text = message.text
split = re.split('_+', text)
if len(split) == 1:
speaking('lang_command', message, reply=True, cut_big_text=True)
elif len(split) == 2 and split[0] == '/lang' and split[1] in languages_dict:
enter_lang = split[1]
if enter_lang != get_user_language(message):
CUR.execute(
'UPDATE languages_of_users SET "language" = %s WHERE user_id = %s',
(enter_lang, message.from_user.id)
)
CON.commit()
update_channel_posts(message.from_user)
speaking('language_was_changed', message, reply=True, mono=True)
speaking('greeting_message', message, markdown=True)
LAST_TIME_OF_GREETING_MESSAGE_DICT[message.from_user.id] = time()
else:
speaking('you_enter_the_same_language', message, reply=True, mono=True)
else:
speaking('bad_entered_command', message, reply=True, mono=True)
@staticmethod
def list(message):
CUR.execute(
'''
select
ou.volunteer_id,
ou.user_id,
lou."language",
ou.opening_time,
ou.time_of_last_message_by_user,
ou.time_of_last_message_by_volunteers,
mi.channel_message_id
from
open_users ou
left join languages_of_users lou
on
ou.user_id = lou.user_id
left join message_ids mi
on
ou.user_id = mi.user_id
order by
ou.volunteer_id is null desc,
opening_time
'''
)
query_result = CUR.fetchall()
response_text = 'list of open users \({}\)'.format(len(query_result))
for row in query_result:
volunteer_id = row[0]
user_id = row[1]
user_language = row[2]
opening_time = row[3]
time_of_last_message_by_user = row[4]
time_of_last_message_by_volunteers = row[5]
channel_message_id = row[6]
text_opening_time = str(datetime.datetime.utcnow().replace(microsecond=0) - opening_time)
if time_of_last_message_by_user:
text_time_of_last_message_by_user = str(datetime.datetime.utcnow().replace(microsecond=0)
- time_of_last_message_by_user)
else:
text_time_of_last_message_by_user = 'no messages'
if time_of_last_message_by_volunteers:
text_time_of_last_message_by_volunteers = str(datetime.datetime.utcnow().replace(microsecond=0)
- time_of_last_message_by_volunteers)
else:
text_time_of_last_message_by_volunteers = 'no answer'
candidate_to_response_text = '\n' \
'\n' \
'{} {}\n' \
' {}\n' \
' {}\n' \
' {}\n' \
' {}\n' \
' {}'.format(
'🟡' if volunteer_id else '🔴',
escape_markdown(get_tg_user_info(user_id)),
user_language,
text_opening_time,
text_time_of_last_message_by_user,
text_time_of_last_message_by_volunteers,
f'[link to post]({channel_link}/{channel_message_id})'
)
if len(response_text + candidate_to_response_text) > 4096:
break
else:
response_text += candidate_to_response_text
if len(query_result) == 0:
response_text += '\n\nempty'
tg_delay(message.from_user.id)
BOT.send_message(
message.from_user.id,
response_text,
reply_to_message_id=message.message_id,
allow_sending_without_reply=True,
parse_mode='MarkdownV2'
)
@staticmethod
def taken(message):
CUR.execute(
'''
select
ou.user_id,
lou."language",
ou.opening_time,
ou.time_of_last_message_by_user,
ou.time_of_last_message_by_volunteers,
mi.channel_message_id
from
open_users ou
left join languages_of_users lou
on
ou.user_id = lou.user_id
left join message_ids mi
on
ou.user_id = mi.user_id
where
ou.volunteer_id = %s
order by
ou.opening_time
''',
(message.from_user.id,)
)
query_result = CUR.fetchall()
response_text = 'list of taken users by you \({}\)'.format(len(query_result))
for row in query_result: