-
Notifications
You must be signed in to change notification settings - Fork 0
/
boggle_telegram_bot.py
2031 lines (1687 loc) · 87.8 KB
/
boggle_telegram_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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
This bot was made by e-caste in 2020
"""
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.parsemode import ParseMode
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
CallbackQueryHandler, PicklePersistence)
from telegram.utils.helpers import mention_html
from telegram.error import Unauthorized, BadRequest
import logging
import os
import shutil
import sys
import traceback
from translations import get_string
from threading import Timer
from dice import get_shuffled_dice, letters_sets
from math import sqrt
from time import time
HTML = ParseMode.HTML
debug = sys.platform.startswith("darwin")
if debug:
from secret import token, castes_chat_id
else:
# import Docker environment variables
token = os.environ["TOKEN"]
castes_chat_id = os.environ["CST_CID"]
# Enable logging
level = logging.DEBUG if debug else logging.INFO
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=level)
logger = logging.getLogger(__name__)
timers = {
'newgame': {},
'ingame': {}
}
spam_interval = 4 # hours
def start(update, context):
__check_bot_data_is_initialized(context)
__check_bot_was_restarted(update, context)
reply = get_string(__get_chat_lang(context), 'welcome', update.message.from_user.first_name)
logger.info(f"User {__get_user_for_log(update)} started the bot.")
context.bot.send_message(chat_id=__get_chat_id(update),
text=reply,
parse_mode=HTML)
def bot_added_to_group(update, context):
if update.message.new_chat_members[0].username == context.bot.username:
logger.info(f"Added to group {__get_group_name(update)} - ID: {__get_chat_id(update)}")
context.bot.send_message(chat_id=__get_chat_id(update),
text=get_string(__get_chat_lang(context), 'bot_added_to_group'),
parse_mode=HTML)
def new(update, context):
__check_bot_data_is_initialized(context)
if not __check_chat_is_group(update):
update.message.reply_text(get_string(__get_chat_lang(context), msg='chat_is_not_group'))
return
__check_bot_was_restarted(update, context)
group_chat_id = __get_chat_id(update)
cd = context.chat_data
bd = context.bot_data
if bd['games'].get(group_chat_id):
if cd['timers'].get('newgame'):
context.bot.send_message(chat_id=__get_chat_id(update),
text=get_string(__get_chat_lang(context), 'game_already_created',
__get_username(update)),
parse_mode=HTML)
else:
context.bot.send_message(chat_id=__get_chat_id(update),
text=get_string(__get_chat_lang(context), 'game_already_started',
__get_username(update)),
parse_mode=HTML)
return
if 'timers' not in cd:
__init_chat_data(context)
if 'notify' not in cd:
cd['notify'] = {
'justonce': [],
'allgames': [],
'withoutspam': {},
}
if 'withoutspam' not in cd['notify']:
cd['notify']['withoutspam'] = {}
if not cd['timers']['newgame']:
t = Timer(interval=cd['timers']['durations']['newgame'],
function=__newgame_timer, args=(update, context))
t.start()
cd['timers']['newgame'] = t.name
timers['newgame'][group_chat_id] = t.cancel # pass callable
message = context.bot.send_message(chat_id=__get_chat_id(update),
text=get_string(__get_chat_lang(context), 'game_created',
__get_username(update),
cd['timers']['durations']['newgame'], ""),
parse_mode=HTML)
logger.info(f"User {__get_user_for_log(update)} created a game in group"
f" {__get_group_name(update)} - {__get_chat_id(update)}")
creator_id = __get_user_id(update)
if not cd.get('games'):
cd['games'] = []
cd['games'].append({
'unix_epoch': int(time()),
'creator': {
'id': creator_id,
'username': __get_username(update)
},
'participants': {},
'is_finished': False,
'ingame_timer': None,
'lang': __get_chat_lang(context),
'dim': cd['settings']['table_dimensions'],
'newgame_message': message
})
if cd['settings']['auto_join']:
join(update, context) # auto-join game creator
for user_id in cd['notify']['justonce']:
try:
if user_id != creator_id:
context.bot.send_message(chat_id=user_id,
text=get_string(__get_chat_lang(context), 'notify_newgame',
__get_group_name(update)),
parse_mode=HTML)
except BadRequest:
pass
cd['notify']['justonce'] = [] # remove all user_ids since they've been notified
for user_id in cd['notify']['allgames']:
try:
if user_id != creator_id:
context.bot.send_message(chat_id=user_id,
text=get_string(__get_chat_lang(context), 'notify_newgame',
__get_group_name(update)),
parse_mode=HTML)
except BadRequest:
pass
for user_id in cd['notify']['withoutspam']:
try:
if user_id != creator_id and time() > cd['notify']['withoutspam'][user_id] + spam_interval * 3600:
cd['notify']['withoutspam'][user_id] = time()
context.bot.send_message(chat_id=user_id,
text=get_string(__get_chat_lang(context), 'notify_newgame',
__get_group_name(update)),
parse_mode=HTML)
except BadRequest:
pass
else:
context.bot.send_message(chat_id=__get_chat_id(update),
text=get_string(__get_chat_lang(context), 'game_already_created',
__get_username(update)),
parse_mode=HTML)
def join(update, context):
__check_bot_data_is_initialized(context)
if not __check_chat_is_group(update):
update.message.reply_text(get_string(__get_chat_lang(context), msg='chat_is_not_group'))
return
__check_bot_was_restarted(update, context)
group_chat_id = __get_chat_id(update)
cd = context.chat_data
bd = context.bot_data
if bd['games'].get(group_chat_id):
if cd['timers'].get('newgame'):
context.bot.send_message(chat_id=__get_chat_id(update),
text=get_string(__get_chat_lang(context), 'game_already_created',
__get_username(update)),
parse_mode=HTML)
else:
context.bot.send_message(chat_id=__get_chat_id(update),
text=get_string(__get_chat_lang(context), 'game_already_started',
__get_username(update)),
parse_mode=HTML)
return
if not cd.get('timers'):
__init_chat_data(context)
context.bot.send_message(chat_id=__get_chat_id(update),
text=get_string(__get_chat_lang(context), msg='no_game_yet'))
return
current_game = __get_current_game(context)
if cd['timers']['newgame'] and current_game is not None:
user_id = __get_user_id(update)
if current_game['participants'].get(user_id):
context.bot.send_message(chat_id=group_chat_id,
text=get_string(__get_chat_lang(context), 'already_in_game',
__get_username(update),
current_game['creator']['username']),
parse_mode=HTML)
else:
if group_chat_id not in bd['stats']['groups']:
__init_group_stats(context, group_chat_id)
if not bd['stats']['users'].get(user_id): # user has never played
__init_user_stats(context, user_id, __get_username(update), group_chat_id, new_player=True)
elif not bd['stats']['groups'][group_chat_id].get(user_id): # user has already played in other groups
__init_user_stats(context, user_id, __get_username(update), group_chat_id, new_player=False)
__join_user_to_game(update, context)
context.bot.send_message(chat_id=group_chat_id,
text=get_string(__get_chat_lang(context), 'game_joined',
__get_username(update), current_game['creator']['username']),
parse_mode=HTML)
logger.info(f"User {__get_user_for_log(update)} joined a game in group"
f" {__get_group_name(update)} - {__get_chat_id(update)}")
usernames = ""
for user_id in current_game['participants']:
usernames += current_game['participants'][user_id]['username'] + ", "
usernames = f"<b>{usernames[:-2]}</b>"
context.bot.edit_message_text(chat_id=group_chat_id,
message_id=current_game['newgame_message']['message_id'],
text=get_string(__get_chat_lang(context), 'game_created',
current_game['creator']['username'],
cd['timers']['durations']['newgame'], usernames),
parse_mode=HTML)
else:
context.bot.send_message(chat_id=__get_chat_id(update),
text=get_string(__get_chat_lang(context), msg='no_game_yet'))
def leave(update, context):
__check_bot_data_is_initialized(context)
if not __check_chat_is_group(update):
update.message.reply_text(get_string(__get_chat_lang(context), msg='chat_is_not_group'))
return
__check_bot_was_restarted(update, context)
group_chat_id = __get_chat_id(update)
user_id = __get_user_id(update)
cd = context.chat_data
bd = context.bot_data
if bd['games'].get(group_chat_id):
game = bd['games'][group_chat_id]
if game['participants'].get(user_id):
if not game['is_finished']:
context.bot.send_message(chat_id=group_chat_id,
text=get_string(__get_chat_lang(context), 'game_left',
__get_username(update)),
parse_mode=HTML)
del game['participants'][user_id]
logger.info(f"User {__get_user_for_log(update)} left a game in group"
f" {__get_group_name(update)} - {__get_chat_id(update)}")
else:
context.bot.send_message(chat_id=group_chat_id,
text=get_string(__get_chat_lang(context), 'game_already_finished_leave',
bd['games'][group_chat_id]['creator']['username']),
parse_mode=HTML)
else:
context.bot.send_message(chat_id=group_chat_id,
text=get_string(__get_chat_lang(context), 'not_in_game',
__get_username(update)),
parse_mode=HTML)
return
if not cd.get('timers'):
__init_chat_data(context)
context.bot.send_message(chat_id=__get_chat_id(update),
text=get_string(__get_chat_lang(context), msg='no_game_yet'))
return
if cd['timers']['newgame']:
current_game = __get_current_game(context)
user_id = __get_user_id(update)
if current_game['participants'].get(user_id):
__remove_user_from_game(update, context)
context.bot.send_message(chat_id=group_chat_id,
text=get_string(__get_chat_lang(context), 'game_left',
__get_username(update)),
parse_mode=HTML)
logger.info(f"User {__get_user_for_log(update)} left a game in group"
f" {__get_group_name(update)} - {__get_chat_id(update)}")
usernames = ""
for user_id in current_game['participants']:
usernames += current_game['participants'][user_id]['username'] + ", "
usernames = f"<b>{usernames[:-2]}</b>"
context.bot.edit_message_text(chat_id=group_chat_id,
message_id=current_game['newgame_message']['message_id'],
text=get_string(__get_chat_lang(context), 'game_created',
current_game['creator']['username'],
cd['timers']['durations']['newgame'], usernames),
parse_mode=HTML)
else:
context.bot.send_message(chat_id=group_chat_id,
text=get_string(__get_chat_lang(context), 'not_yet_in_game',
__get_username(update)),
parse_mode=HTML)
else:
context.bot.send_message(chat_id=__get_chat_id(update),
text=get_string(__get_chat_lang(context), msg='no_game_yet'))
def start_game(update, context, timer: bool = False):
__check_bot_data_is_initialized(context)
cd = context.chat_data
bd = context.bot_data
current_game = __get_current_game(context)
group_chat_id = __get_chat_id(update)
if not __check_chat_is_group(update):
context.bot.send_message(chat_id=group_chat_id,
text=get_string(__get_chat_lang(context), 'chat_is_not_group'))
return
__check_bot_was_restarted(update, context)
if current_game is None:
context.bot.send_message(chat_id=group_chat_id,
text=get_string(__get_chat_lang(context), 'no_game_yet'))
return
if len(current_game['participants']) == 0:
context.bot.send_message(chat_id=group_chat_id,
text=get_string(__get_chat_lang(context), 'no_participants'))
return
if not timer:
if __forbid_not_game_creator(update, context, group_chat_id, command="/startgame"):
return
else:
if bd['games'].get(group_chat_id):
context.bot.send_message(chat_id=group_chat_id,
text=get_string(__get_chat_lang(context), 'game_already_started'))
return
cd['timers']['newgame'] = None
timers['newgame'][group_chat_id]() # cancel timer if started by game creator
table_list = get_shuffled_dice(cd['settings']['lang'], cd['settings']['table_dimensions'])
table_str = __get_formatted_table(table_list)
row_col_num = int(sqrt(len(table_list)))
table_list = [letter if letter != "Qu" else "Q" for letter in table_list]
table_grid = {(row, col): table_list[row * row_col_num + col].lower()
for row in range(row_col_num) for col in range(row_col_num)}
bd['games'][group_chat_id] = current_game
bd['games'][group_chat_id]['table_str'] = table_str
bd['games'][group_chat_id]['table_grid'] = table_grid
context.bot.send_message(chat_id=group_chat_id,
text=get_string(__get_chat_lang(context), 'game_started_group'))
logger.info(f"User {__get_user_for_log(update)} started a game in group"
f" {__get_group_name(update)} - {__get_chat_id(update)}")
text = get_string(__get_game_lang(context, group_chat_id), 'game_started_private',
cd['timers']['durations']['ingame']) + "\n\n\n" + table_str
kill_game = False
for player in current_game['participants']:
try:
context.bot.send_message(chat_id=player,
text=text,
parse_mode=HTML)
except Unauthorized:
context.bot.send_message(chat_id=group_chat_id,
text=get_string(__get_chat_lang(context), 'game_killed_user_did_not_start_the_bot',
current_game['participants'][player]['username']),
parse_mode=HTML)
kill_game = True
if kill_game:
kill(update, context, bot_not_started=True)
return
t = Timer(interval=cd['timers']['durations']['ingame'],
function=__ingame_timer, args=(update, context, group_chat_id))
t.start()
bd['games'][group_chat_id]['ingame_timer'] = t.name
timers['ingame'][group_chat_id] = t.cancel
def points_handler(update, context):
__check_bot_data_is_initialized(context)
chat_id = __get_chat_id(update)
user_id = __get_user_id(update)
bd = context.bot_data
not_finished = {}
for game in bd['games']:
if not bd['games'][game]['is_finished']:
not_finished[game] = bd['games'][game]
for group in not_finished:
participants = bd['games'][group]['participants']
for participant in participants:
if user_id == participant:
group_id = group
break
else:
continue
break
else:
context.bot.send_message(chat_id=chat_id,
text=get_string(__get_chat_lang(context), 'received_dm_but_user_not_in_game'))
return
word = update.message.text.lower()
for char in word:
if char not in letters_sets[bd['games'][group_id]['lang']]:
update.message.reply_text(get_string(__get_game_lang(context, group_id), 'received_dm_but_char_not_alpha'))
update.message.reply_text(text=bd['games'][group_id]['table_str'],
parse_mode=HTML)
return
game = bd['games'][group_id]
if (len(word) < 3 and game['dim'] == "4x4") \
or (len(word) < 4 and game['dim'] == "5x5"):
update.message.reply_text(get_string(__get_game_lang(context, group_id), 'received_dm_but_word_too_short'))
update.message.reply_text(text=game['table_str'],
parse_mode=HTML)
return
if "q" in word and "qu" not in word:
update.message.reply_text(get_string(__get_game_lang(context, group_id), 'received_dm_but_q_without_u'))
update.message.reply_text(text=game['table_str'],
parse_mode=HTML)
return
word = word.replace("qu", "q")
if not __validate_word_by_boggle_rules(word, game['table_grid']):
update.message.reply_text(get_string(__get_game_lang(context, group_id), 'received_dm_but_word_not_validated'))
update.message.reply_text(text=game['table_str'],
parse_mode=HTML)
return
word = word.replace("q", "qu")
words = bd['games'][group_id]['participants'][user_id]['words']
if not words.get(word):
words[word] = {
'points': __get_points_for_word(word, game['dim']),
'sent_by_other_players': False,
'deleted': False
}
update.message.reply_text(text=game['table_str'],
parse_mode=HTML)
else:
update.message.reply_text(get_string(__get_game_lang(context, group_id), 'received_dm_but_word_already_sent',
word))
update.message.reply_text(text=game['table_str'],
parse_mode=HTML)
def delete(update, context):
__check_bot_data_is_initialized(context)
if not __check_chat_is_group(update):
update.message.reply_text(get_string(__get_chat_lang(context), msg='chat_is_not_group'))
return
__check_bot_was_restarted(update, context)
# user_id = __get_user_id(update)
group_id = __get_chat_id(update)
bd = context.bot_data
if not bd['games'].get(group_id):
context.bot.send_message(chat_id=group_id,
text=get_string(__get_chat_lang(context), msg='no_game_yet'))
return
if __forbid_not_game_creator(update, context, group_id, command="/delete"):
return
game = bd['games'][group_id]
lang = game['lang']
if not game['is_finished']:
context.bot.send_message(chat_id=group_id,
text=get_string(lang, msg='game_not_yet_finished'))
return
words = update.message.text.lower().split()[1:] # skip /delete
if len(words) == 0:
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'no_words_after_delete_command'))
return
for word in words:
for char in word:
if char not in letters_sets[lang]:
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'char_not_alpha', word))
return
not_found = words
players = game['participants']
for user_id in players:
player_words = [w for w in players[user_id]['words']]
for player_word in player_words:
for word in words:
if player_word == word:
players[user_id]['words'][player_word]['deleted'] = True
not_found.remove(word)
if len(not_found) > 0:
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'words_not_found_in_players_words', not_found))
else:
# player_words_without_points = __get_formatted_words(context, group_id, with_points=False)
player_words_without_points = {}
for user_id in game['participants']:
player_words_without_points[user_id] = __get_formatted_words(context, group_id,
with_points=False, user_id=user_id)
try:
context.bot.edit_message_text(chat_id=group_id,
message_id=game['participants'][user_id]['result_message_id'],
text=player_words_without_points[user_id],
parse_mode=HTML)
except BadRequest: # message is not modified because it doesn't contain any of the deleted words
pass
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'all_words_deleted'),
parse_mode=HTML)
logger.info(f"User {__get_user_for_log(update)} deleted some words in group"
f" {__get_group_name(update)} - {__get_chat_id(update)}")
def isthere(update, context):
__check_bot_data_is_initialized(context)
if not __check_chat_is_group(update):
update.message.reply_text(get_string(__get_chat_lang(context), msg='chat_is_not_group'))
return
__check_bot_was_restarted(update, context)
group_id = __get_chat_id(update)
bd = context.bot_data
if not bd['games'].get(group_id):
context.bot.send_message(chat_id=group_id,
text=get_string(__get_chat_lang(context), msg='no_game_yet'))
return
game = bd['games'][group_id]
lang = game['lang']
if not game['is_finished']:
context.bot.send_message(chat_id=group_id,
text=get_string(lang, msg='game_not_yet_finished'))
return
words = update.message.text.lower().split()[1:] # skip /isthere
if len(words) == 0:
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'no_words_after_isthere_command'))
return
for word in words:
for char in word:
if char not in letters_sets[lang]:
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'char_not_alpha', word))
return
played = []
players = game['participants']
for user_id in players:
player_words = [w for w in players[user_id]['words']]
for player_word in player_words:
for word in words:
if player_word == word:
played.append(word)
played_str = "\n".join(played)
not_played_str = "\n".join([word for word in words if word not in played])
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'isthere_words', played_str, not_played_str),
parse_mode=HTML)
logger.info(f"User {__get_user_for_log(update)} checked which words were played in group"
f" {__get_group_name(update)} - {__get_chat_id(update)}")
def end_game(update, context):
__check_bot_data_is_initialized(context)
if not __check_chat_is_group(update):
update.message.reply_text(get_string(__get_chat_lang(context), msg='chat_is_not_group'))
return
__check_bot_was_restarted(update, context)
# user_id = __get_user_id(update)
group_id = __get_chat_id(update)
cd = context.chat_data
bd = context.bot_data
if not bd['games'].get(group_id):
context.bot.send_message(chat_id=group_id,
text=get_string(__get_chat_lang(context), msg='no_game_yet'))
return
game = bd['games'][group_id]
lang = game['lang']
if __forbid_not_game_creator(update, context, group_id, command="/endgame", allow_admins=True):
return
if not game['is_finished']:
context.bot.send_message(chat_id=group_id,
text=get_string(lang, msg='game_not_yet_finished'))
return
us = bd['stats']['users']
gs = bd['stats']['groups']
total_points = 0
players_points = {}
players = game['participants']
for user_id in players: # stats already initialized in join()
words = players[user_id]['words']
for word in words:
if not words[word]['sent_by_other_players'] and not words[word]['deleted']:
if not players_points.get(user_id):
players_points[user_id] = words[word]['points']
else:
players_points[user_id] += words[word]['points']
total_points += words[word]['points']
if not players_points.get(user_id): # hasn't made any points
players_points[user_id] = 0
max_points = -1
for user_id in players_points:
points = players_points[user_id]
max_points = points if points > max_points else max_points
winners = {}
for user_id in players_points:
if players_points[user_id] == max_points:
winners[user_id] = game['participants'][user_id]['username']
game['winners'] = winners
# update group stats
if not gs.get(group_id):
gs[group_id] = {
'matches': 0,
'points': 0,
'average': 0
}
gs[group_id]['points'] += total_points
gs[group_id]['matches'] += 1
gs[group_id]['average'] = int(gs[group_id]['points'] / gs[group_id]['matches'])
# update users stats
for user_id in players:
us[user_id]['matches']['played'] += 1
if winners.get(user_id) and len(winners) == 1: # won
us[user_id]['matches']['won']['value'] += 1
us[user_id]['matches']['latest']['won'] = "won"
elif winners.get(user_id) and len(winners) > 1: # even
us[user_id]['matches']['even']['value'] += 1
us[user_id]['matches']['latest']['won'] = "even"
elif not winners.get(user_id): # lost
us[user_id]['matches']['lost']['value'] += 1
us[user_id]['matches']['latest']['won'] = "lost"
for ending in ['won', 'even', 'lost']:
us[user_id]['matches'][ending]['percentage'] = round(us[user_id]['matches'][ending]['value']
/ us[user_id]['matches']['played'] * 100, 2)
us[user_id]['points']['max'] = players_points[user_id] if players_points[user_id] > us[user_id]['points']['max'] \
else us[user_id]['points']['max']
us[user_id]['points']['min'] = players_points[user_id] if players_points[user_id] < us[user_id]['points']['max'] \
else us[user_id]['points']['min']
us[user_id]['points']['total'] += players_points[user_id]
us[user_id]['points']['average'] = round(us[user_id]['points']['total'] / us[user_id]['matches']['played'], 2)
us[user_id]['matches']['latest']['points'] = players_points[user_id]
to_delete = []
for word in us[user_id]['matches']['latest']['words']:
to_delete.append(word)
for word in to_delete:
del us[user_id]['matches']['latest']['words'][word]
for word in game['participants'][user_id]['words']:
us[user_id]['matches']['latest']['words'][word] = game['participants'][user_id]['words'][word]['points']
for user_id in game['participants']:
try:
context.bot.edit_message_text(chat_id=group_id,
message_id=game['participants'][user_id]['result_message_id'],
text=__get_formatted_words(context, group_id, with_points=True, only_valid=True,
user_id=user_id),
parse_mode=HTML)
except BadRequest:
pass
chat_game = __get_latest_game(context)
cd['games'].remove(chat_game)
cd['games'].append(game)
del bd['games'][group_id]
lang = __get_chat_lang(context)
winner_str = ""
if len(winners) == 1:
winner_str = get_string(lang, 'game_winner_singular')
elif len(winners) > 1:
winner_str = get_string(lang, 'game_winners_plural')
winners_usernames = ', '.join([winners[uid] for uid in winners])
text = get_string(lang, 'game_finished', winner_str, winners_usernames, max_points) + "\n"
players_points = {k: v for k, v in sorted(players_points.items(), key=lambda item: item[1], reverse=True)}
for user_id in players_points:
if user_id not in winners:
text += f"<i>{game['participants'][user_id]['username']}: {players_points[user_id]}</i>\n"
context.bot.send_message(chat_id=group_id,
text=text,
parse_mode=HTML)
logger.info(f"User {__get_user_for_log(update)} ended a game in group"
f" {__get_group_name(update)} - {__get_chat_id(update)}")
def last(update, context):
__check_bot_data_is_initialized(context)
lang = __get_chat_lang(context)
if not __check_chat_is_group(update):
update.message.reply_text(get_string(lang, msg='chat_is_not_group'))
return
__check_bot_was_restarted(update, context)
group_id = __get_chat_id(update)
last_n = update.message.text.lower().split()[1:] # skip /last
if len(last_n) != 1 or (len(last_n) == 1 and not last_n[0].isdigit()): # handles negative integers, floats, strings
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'wrong_format_after_last_command'))
return
last_n = int(last_n[0])
cd = context.chat_data
tot_n_games = len(cd['games'])
if tot_n_games < last_n:
msg = get_string(lang, 'not_enough_games_for_last_command', last_n, tot_n_games)
last_n = tot_n_games
else:
msg = get_string(lang, 'last_n_games_ranking', last_n)
last_n_games = cd['games'][-last_n:]
players_points = {}
players_usernames = {}
for game in last_n_games:
for player in game['participants']:
game_score = 0
words = game['participants'][player]['words']
for word in words:
game_score += words[word]['points'] \
if not words[word]['deleted'] and not words[word]['sent_by_other_players'] else 0
if player in players_points:
players_points[player] += game_score
else:
players_points[player] = game_score
username = game['participants'][player]['username']
if '<a href="tg://user?id=' not in username: # not saved as mention_html
username = mention_html(player, username)
players_usernames[player] = username
players_points = {k: v for k, v in sorted(players_points.items(), key=lambda item: item[1], reverse=True)}
ranking = "\n".join([f"<code>#{i+1}</code> <b>{players_usernames[p]}</b>: "
f"<code>{players_points[p]}</code>"
for i, p in enumerate(players_points)])
context.bot.send_message(chat_id=group_id,
text=f"{msg}\n{ranking}",
parse_mode=HTML)
logger.info(f"User {__get_user_for_log(update)} asked for the ranking of the last {last_n} games in group"
f" {__get_group_name(update)} - {__get_chat_id(update)}")
def kick(update, context):
__check_bot_data_is_initialized(context)
if not __check_chat_is_group(update):
update.message.reply_text(get_string(__get_chat_lang(context), msg='chat_is_not_group'))
return
__check_bot_was_restarted(update, context)
bd = context.bot_data
# user_id = __get_user_id(update)
group_id = __get_chat_id(update)
current_game = __get_current_game(context)
if not bd['games'].get(group_id) and current_game is None:
context.bot.send_message(chat_id=group_id,
text=get_string(__get_chat_lang(context), msg='no_game_yet'))
return
elif not bd['games'].get(group_id) and current_game is not None:
context.bot.send_message(chat_id=group_id,
text=get_string(__get_chat_lang(context), msg='cant_kick_players_before_starting'))
return
game = bd['games'][group_id]
lang = game['lang']
if __forbid_not_game_creator(update, context, group_id, command="/kick"):
return
if game['is_finished']:
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'game_already_finished_kick', game['creator']['username']),
parse_mode=HTML)
return
reply_keyboard = [[]]
for user_id in game['participants']:
if user_id != game['creator']['id']:
button = InlineKeyboardButton(game['participants'][user_id]['username'],
callback_data=f"kick_{user_id}_from_{group_id}")
if len(reply_keyboard[-1]) == 2:
reply_keyboard.append([button])
else:
reply_keyboard[-1].append(button)
reply_keyboard.append([InlineKeyboardButton(get_string(lang, 'close_button'), callback_data="close")])
reply_markup = InlineKeyboardMarkup(reply_keyboard)
if len(reply_keyboard[-1]) == 0:
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'no_users_to_kick'))
return
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'kick_user_choice_group', game['creator']['username']),
reply_markup=reply_markup,
parse_mode=HTML)
def kill(update, context, bot_not_started: bool = False, bot_restarted: bool = False, group_id: int = None):
__check_bot_data_is_initialized(context)
if bot_not_started or bot_restarted:
bd = context.bot_data
cd = context.chat_data
if bot_not_started:
group_id = __get_chat_id(update)
del bd['games'][group_id]
latest_game = __get_latest_game(context)
cd['games'].remove(latest_game)
return
if not __check_chat_is_group(update):
update.message.reply_text(get_string(__get_chat_lang(context), msg='chat_is_not_group'))
return
if not bot_restarted:
__check_bot_was_restarted(update, context)
bd = context.bot_data
cd = context.chat_data
# user_id = __get_user_id(update)
group_id = __get_chat_id(update)
current_game = __get_current_game(context)
if not bd['games'].get(group_id) and current_game is None:
context.bot.send_message(chat_id=group_id,
text=get_string(__get_chat_lang(context), msg='no_game_yet'))
return
if bd['games'].get(group_id):
game = bd['games'][group_id]
delete_from_bd = True
else:
game = current_game
delete_from_bd = False
lang = game['lang']
if __forbid_not_game_creator(update, context, group_id, command="/kill"):
return
if game['is_finished']:
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'game_already_finished_kill', game['creator']['username']),
parse_mode=HTML)
return
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'game_killed_group'))
logger.info(f"User {__get_user_for_log(update)} killed a game in group"
f" {__get_group_name(update)} - {__get_chat_id(update)}")
for user_id in game['participants']:
context.bot.send_message(chat_id=user_id,
text=get_string(lang, 'game_killed_private', game['creator']['username']),
parse_mode=HTML)
if delete_from_bd:
del bd['games'][group_id]
timers['ingame'][group_id]()
timers['ingame'][group_id] = None
else:
cd['timers']['newgame'] = None
timers['newgame'][group_id]()
timers['newgame'][group_id] = None
latest_game = __get_latest_game(context)
cd['games'].remove(latest_game)
def show_statistics(update, context):
__check_bot_data_is_initialized(context)
__check_bot_was_restarted(update, context)
user_id = __get_user_id(update)
if __check_chat_is_group(update):
lang = __get_chat_lang(context)
group_id = __get_chat_id(update)
reply_keyboard = InlineKeyboardMarkup([
[InlineKeyboardButton(get_string(lang, 'stats_user_button'), callback_data=f"stats_user_{user_id}")],
[InlineKeyboardButton(get_string(lang, 'stats_group_button'), callback_data=f"stats_group_{group_id}")],
[InlineKeyboardButton(get_string(lang, 'close_button'), callback_data="close")]
])
context.bot.send_message(chat_id=group_id,
text=get_string(lang, 'stats_prompt'),
reply_markup=reply_keyboard)
else:
__show_user_stats(context, user_id, __get_username(update))
logger.info(f"User {__get_user_for_log(update)} asked for his stats in a private chat")
def settings(update, context):
__check_bot_data_is_initialized(context)
__check_bot_was_restarted(update, context)
chat_id = __get_chat_id(update)
lang = __get_chat_lang(context)
cd = context.chat_data
if not cd.get('settings'):
__init_chat_data(context, settings_only=True)
language = "Italiano" if cd['settings']['lang'] == 'ita' else "English"
table_dimensions = cd['settings']['table_dimensions']
if lang == "ita":
auto_join = "sì" if cd['settings']['auto_join'] else "no"
else:
auto_join = "yes" if cd['settings']['auto_join'] else "no"
pregame_timer = f"{cd['timers']['durations']['newgame']} second" + ("i" if lang == "ita" else "s")
ingame_timer = f"{cd['timers']['durations']['ingame']} second" + ("i" if lang == "ita" else "s")
reply_keyboard = __get_settings_keyboard(chat_id, lang)
context.bot.send_message(chat_id=chat_id,
text=get_string(lang, 'settings_prompt',
language, table_dimensions, auto_join, pregame_timer, ingame_timer),
reply_markup=reply_keyboard,
parse_mode=HTML)
def notify(update, context):
__check_bot_data_is_initialized(context)
__check_bot_was_restarted(update, context)
if not __check_chat_is_group(update):