-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuser.py
1229 lines (915 loc) · 49 KB
/
user.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 telegram import InlineKeyboardButton, Poll, ParseMode
from telegram.inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram import Bot
from database import execute_query
from urllib.request import urlopen
from urllib.parse import unquote
import json
import random
import time
import threading
import schedule
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from io import BytesIO
import cv2
import logging
# Enabling Logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
bot = Bot(token="SAMPLE")
message = {
"kh" : "<b>Are you <i>Knowledge Hungry</i></b>, What do you think?\nWhy not test your intellect with some brain teasing challenges💪🧠",
"mm" : " 🧐 Explore the sevices:",
"pnr": "Looks like you haven't set your name for the <i><b>multiplayer quiz competition</b></i>.\nPlease send your name which will be visible to other players.",
"mqc": "Welcome <b>{}</b>, \nI can also conduct multiplayer quizzes. Here you can check your position among your peers.\n\n 📌 <b>Rules for multiplayer quiz competition:</b>\n\n👉 Multiplayer quiz competition will last 7 minutes and contain 15 questions.\n👉 Questions will be asked in any field.\n👉 There will overall timer for the competition and no individual timer will be there.\n👉 Your leaderboard score will be calculated by keeping the time taken to answer the questions into consideration.\n👉 You can skip any question if you want to.\n\n<b>Are you ready for the challenge?</b>",
"qe" : "😁 Wanna try some more things?",
"ir" : "Please, accept my sincere apology for any technical problem. <b>Just write it out.</b>",
"help": "👋 Hello, Quiz Time is a chat bot able to conduct some amazing quizzes in single player as well as multiplayer mode.\n\n👉 The bot with the help of quizzes can promote deeper engagement and help in the development of important learning skills.\n\n👉 It's guidance and performance reports will help you to improve your performance.\n\n👉 It's appealing interface with great interactivity which will encourage the user to participate in quizzes.\n\nYou can also use different commands like:\n\n/start - <i>Start the bot</i>\n/services - <i>Services provided by bot</i>\n/help - <i>Usage guide of Bot</i>\n/solo_quiz - <i>Single player Quiz</i>\n/multiplyer_quiz - <i>Multiplayer Quiz</i>"
}
topics = {
18: "Computer",
21: "Sports",
10: "Books",
22: "Geography",
23: "History",
27: "Animals",
24: "Politics",
17: "Science & Nature",
9: "General Knowledge",
0: "Any Category"
}
# Used in graph generation of player progess report
bar_colors_topic_wise = {
18: "darkgreen",
21: "slategrey",
10: "yellow",
22: "navy",
23: "hotpink",
27: "orange",
24: "red",
17: "pink",
9: "aqua",
0: "saddlebrown"
}
inline_keyboards = {
"mm" : [
[
InlineKeyboardButton("Solo Quiz", callback_data=1) # Quick quiz - 'qq'
],
[
InlineKeyboardButton("Practice Arena", callback_data=2) # Customized quiz - 'cq'
],
[
InlineKeyboardButton("Multiplayer Quiz Competition", callback_data=3) # 'mqc'
],
[
InlineKeyboardButton("Progress Analysis", callback_data=4)
],
[
InlineKeyboardButton("Multiplayer Quiz Ranking", callback_data=5)
],
[
InlineKeyboardButton("Report any issue", callback_data=6)
]
],
# Callback data of following keyboard button are topic codes for API call
# Topic
"cq-1" : [
[
InlineKeyboardButton("Computer", callback_data=18),
InlineKeyboardButton("Sports", callback_data=21)
],
[
InlineKeyboardButton("Books", callback_data=10),
InlineKeyboardButton("Geography", callback_data=22)
],
[
InlineKeyboardButton("History", callback_data=23),
InlineKeyboardButton("Animals", callback_data=27)#15
],
[
InlineKeyboardButton("Politics", callback_data=24),#15
InlineKeyboardButton("Science & Nature", callback_data=17)
],
[
InlineKeyboardButton("General Knowledge", callback_data=9),
InlineKeyboardButton("ANY CATEGORY", callback_data="None")
],
[
InlineKeyboardButton("Terminate Quiz Session", callback_data=0)
]
],
# Number of questions
"cq-2":[
[
InlineKeyboardButton("5", callback_data=5),
InlineKeyboardButton("10", callback_data=10),
InlineKeyboardButton("15", callback_data=15)
]
],
# Difficulty level
"cq-3":[
[
InlineKeyboardButton("🟩 Easy", callback_data="easy"),
InlineKeyboardButton("🟧 Medium", callback_data="medium"),
InlineKeyboardButton("🟥 Hard", callback_data="hard")
],
[
InlineKeyboardButton("Any Difficulty", callback_data="None")
]
],
# Time limit in seconds
"cq-4":[
[
InlineKeyboardButton("15", callback_data=15),
InlineKeyboardButton("30", callback_data=30),
InlineKeyboardButton("45", callback_data=45),
InlineKeyboardButton("60", callback_data=60)
],
[
InlineKeyboardButton("Unlimited Time", callback_data="None")
]
],
# Starting multiplayer quiz battle
'mqc':[
[
InlineKeyboardButton("Start multiplayer quiz", callback_data=1)
],
[
InlineKeyboardButton("🔙 to main menu", callback_data=0)
]
],
'qe':[
[
InlineKeyboardButton("🔙 to main menu", callback_data=0)
]
]
}
# previous_message_sent keeps the record of the last sent message for futher processing of the responses
previous_message_sent = {}
####### Single player object containing variables ##########
parameters = {}
single_player_quiz_objects = {}
####### Multiplayer object keeping variables ###############
opened_window_multiplayer_object = None # Multiplayer object whoose joining window is open
ongoing_multiplayer_quiz_objects = {} # {multiplayer_quiz_id : Ongoing multiplayer quiz objects }
previous_question_message_id = {}
#################### MULTI THREADING - Creating seprate thread for scheduling function ###################
#dummy scheduled function()
def dummy_fun():
return
schedule.every(24).hours.do(dummy_fun)
def scheduled_functions_handler():
while len(schedule.get_jobs())>0:
time.sleep(1)
try:
schedule.run_pending()
except Exception as exp:
logger.info("exception occured - ".format(exp))
# Killing the thread intentionally
try:
raise BaseException("\n\nKilling the window cloasing thread")
except:
pass
scheduler_thread = threading.Thread(target=scheduled_functions_handler)
scheduler_thread.setName("SchedulerThread")
scheduler_thread.start()
logger.info("SchedulerThread initiated")
################### PLAYER CLASS #############################
class Player:
"""Player class will keep all the player relevant data and
processing methods instead directly saving this on the
Quiz class and its Child classes """
def __init__(self, chat_id, not_answered_ques):
self.chat_id = chat_id
self.total_questions = None
self.not_answered_ques = not_answered_ques
self.correct_answers = 0
self.time_per_que = None
self.stop_time = None
self.que_idx = 0
self.is_result_generated = False
self.flag = None
def pie_chart_generator(self):
######## Saving raw pie chart in Buffer ####################
# Sizes = [Incorrect Percentage, Correct Percentage]
correct = (self.correct_answers/self.total_questions) * 100
sizes = [100-correct, correct]
self.flag = 0
def filler(sizes):
"""Used to label wedges of pie chart with their numeric value via a lambda function"""
if correct.is_integer():
if self.flag == 0:
self.flag += 1
return "{:d}%\n Incorrect".format(int(sizes[0]))
else:
return "{:d}%\n Correct".format(int(sizes[1]))
else:
if self.flag == 0:
self.flag += 1
return "{:.2f}%\n Incorrect".format(sizes[0])
else:
return "{:.2f}%\n Correct".format(sizes[1])
# Generating pie chart image
plt.figure(figsize=(512/150,512/150), dpi=150)
plt.pie(sizes, colors=['red', 'forestgreen'], autopct=lambda pct: filler(sizes), startangle=90,
wedgeprops = {'linewidth': 15},
textprops = {'fontsize': 15, 'fontfamily': 'sans-serif', 'weight': 'bold'})
plt.title('Result', fontdict={'fontsize':25, 'fontfamily': 'sans-serif', 'weight': 'bold'})
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
# Saving 'RGB' image into IO Buffer
bio = BytesIO()
bio.name = "pie_chart"
plt.savefig(bio, transparent=True, dpi=150)
# Sending the sticker to the Player
bio.seek(0)
bot.send_sticker(self.chat_id, bio)
bio.flush()
bio.close()
def result_generator(self, start_time, topic_id, is_single_player_result = True):
# Logging
logger.info("{} - generating and sending result".format(self.chat_id))
if self.is_result_generated:
return schedule.CancelJob
self.is_result_generated = True
self.time_per_que = (time.time() - start_time) / self.que_idx # time per total attempted question
if topic_id is None:
topic_id = 0
# Sending pie chart
self.pie_chart_generator()
# Sending message regarding the performance of user
message = bot.send_message(
self.chat_id,
"<b>Here is your performance in above quiz: </b>\n\n<i>Total questions attempted : </i><b> {:d}\n</b><i>Missed/skipped questions : </i><b> {:d}\n</b><i>Time per question (sec) : </i><b> {:.2f}\n</b>".format(self.total_questions, self.not_answered_ques, self.time_per_que),
parse_mode=ParseMode.HTML
)
# Updating the record on database
if is_single_player_result:
bot.editMessageReplyMarkup(self.chat_id, message.message_id, reply_markup = InlineKeyboardMarkup(inline_keyboards['qe']))
execute_query("insert into SINGLE_PLAYER_QUIZ_RECORDS values({:d}, {:f}, {:f}, {:d}, CURRENT_timestamp);".format(self.chat_id,
(self.correct_answers/self.total_questions) * 100,
self.time_per_que,
topic_id))
global single_player_quiz_objects
del single_player_quiz_objects[self.chat_id]
else:
bot.send_message(self.chat_id, "Generating leaderboard please wait.")
# Logic of database updation
global previous_message_sent
del previous_question_message_id[self.chat_id]
previous_message_sent[self.chat_id] = 'qe'
return schedule.CancelJob
###############################################################
################### QUIZ CONDUCTING CLASSES #############################
class Quiz:
def __init__(self, parameters):
# list with four parameters [topic(int), no of ques(int), difficulty(string/none), in sec per que]
self.parameters = parameters
# questions = {"question": [[correctanswer], [incorrect answers]] }
self.questions = {}
self.start_time = time.time()
def generate_questions(self):
#"https://opentdb.com/api.php?amount=10&category=23&difficulty=medium&encode=url3986"
# Url formatting as per users choice
url = "https://opentdb.com/api.php?amount=" + str(self.parameters[1])
if self.parameters[0] is not None:
url += "&category=" + str(self.parameters[0])
if self.parameters[2] is not None:
url += "&difficulty=" + str(self.parameters[2])
url += "&encode=url3986"
# Logging
logger.info("generating questions from Open Trivia API")
# Open Trivia Database API
r = urlopen(url)
data = r.read()
data = json.loads(data)
if data["response_code"] != 0:
logger.info("unable to generate questions from Open Trivia API")
return
data = data["results"]
for que_dict in data:
options = [unquote(opt) for opt in que_dict.get('incorrect_answers')]
correct_answer = unquote(que_dict.get('correct_answer'))
options.append(correct_answer)
random.shuffle(options)
self.questions[unquote(que_dict.get('question'))] =[options, options.index(correct_answer)]
def check_answer(self, que_idx, answered_idx):
"""ans_idx is the index of answered question by the user of bot"""
que = list(self.questions.keys())[que_idx-1] # decremented by 1 because current que_idx is of next question.
if self.questions[que][1] == answered_idx:
return True
else:
return False
def send_question(self, player, context):
pass
class SinglePlayer(Quiz):
def __init__(self, parameters, chat_id):
super().__init__(parameters)
super().generate_questions()
self.player = Player(chat_id, self.parameters[1])
self.timer_thread = None
self.player.total_questions = self.parameters[1]
#self.is_result_sent = False
def send_question(self, context, next_que_idx=None):
if next_que_idx is not None:
if next_que_idx < self.player.que_idx:
# When user already answered the question and
# scheduled send question need not to be executed
return schedule.CancelJob
if next_que_idx == self.parameters[1] and self.player.is_result_generated is False:
# Last question answered and result is to be generated
self.player.result_generator(self.start_time, self.parameters[0])
return schedule.CancelJob
# Logging
logger.info("{} - sending multiplayer quiz question".format(self.player.chat_id))
que = list(self.questions.keys())[self.player.que_idx]
if self.parameters[3] is None:
# Unlimited time limit question
message = bot.send_poll(
self.player.chat_id,
question = "({}) ".format(self.player.que_idx + 1) + que,
options = self.questions[que][0],
is_anonymous = True,
type = Poll.QUIZ,
correct_option_id = self.questions[que][1]
)
else:
# Limited time limt question ( With Timer)
message = bot.send_poll(
self.player.chat_id,
question = "({}) ".format(self.player.que_idx + 1) + que,
options = self.questions[que][0],
is_anonymous = True,
type = Poll.QUIZ,
correct_option_id = self.questions[que][1],
open_period = self.parameters[3]
)
self.timer_scheduler(context, self.player.que_idx + 1)
payload = {
message.poll.id: {"chat_id": self.player.chat_id, "message_id": message.message_id}
}
context.bot_data.update(payload)
self.player.que_idx += 1
return schedule.CancelJob
def recieved_answer_processor(self, answered_idx, context):
# Reducing not_answered_ques by 1 b/c initially not_answered_ques stores total no of questions
self.player.not_answered_ques -= 1
try:
if super().check_answer(self.player.que_idx, answered_idx):
self.player.correct_answers += 1
self.send_question(context)
except IndexError: # Index of list out of range when all questions are sent
# Implementing RESULT GENERATION
self.player.result_generator(self.start_time, self.parameters[0])
except Exception as exp:
logger.info("exception occured - ".format(exp))
def timer_scheduler(self, context, next_que_idx):
if next_que_idx == self.parameters[1]:
# Scheduling result generator instead of send question for last question
schedule.every(self.parameters[3]).seconds.do(self.player.result_generator, self.start_time, self.parameters[0])
else:
schedule.every(self.parameters[3]).seconds.do(self.send_question, context, next_que_idx)
##########################################################################################
class Multiplayer(Quiz):
def __init__(self):
super().__init__([9, 15, None])
super().generate_questions()
self.multiplayer_quiz_id = None
# self.players = {chat_id : obj of Players class}
self.players = {}
self.players_score = []
self.is_window_open = True
self.players_quiz_completed_count = 0
self.window_thread = None
self.competition_thread = None
self.start_time = None
self.is_leaderboard_generated = False
# Flags for countering multi calling due to multiple threads
self.is_window_closed = False
self.is_quiz_compeleted = False
self.id_generator()
self.skip_button = [[InlineKeyboardButton("SKIP QUESTION", callback_data="{}-{}".format(self.multiplayer_quiz_id, 2))]]
def id_generator(self):
data = execute_query("select max(multiplayer_quiz_id) from MULTIPLAYER_QUIZ_RECORDS;")
if len(data) == 0:
self.multiplayer_quiz_id = 1
else:
global ongoing_multiplayer_quiz_objects
self.multiplayer_quiz_id = int(data[0]["max"] + 1) + len(ongoing_multiplayer_quiz_objects.keys())
def joining_request_reciever(self, chat_id, context):
if chat_id in self.players.keys():
# When user clicks start multplayer battle switch multiple time so just returning with any operation
return
self.players[chat_id] = Player(chat_id, 15)
self.players[chat_id].total_questions = 15
if len(self.players.keys()) == 20: # max 20 players in a multiplayer battle
self.window_closer(context)
# Sending success message and telling to wait b/c other players are still joining
bot.send_message(chat_id, "Congrats, you are in 🙂. Please wait for some time let other users join.")
def leaderboard_generator(self):
self.is_leaderboard_generated = True
# Logging
logger.info("generating leaderboard of multiplayer quiz with id = {}".format(self.multiplayer_quiz_id))
# Rank wise sorting of players
for chat_id, player in self.players.items():
self.players_score.append((chat_id, player.correct_answers / player.time_per_que * 300))
self.players_score = sorted(self.players_score, key=lambda x:x[1], reverse=True)
# Name extraction from database of top 3 players
top_players_name = []
for chat_id, _ in self.players_score[:3]:
data = execute_query("select player_name from MULTIPLAYER_QUIZ_PARTICIPANTS_NAME where chat_id={};".format(chat_id))
top_players_name.append(data[0]["player_name"])
# Reading the podium image anding adding the name of top three player's on it
bgr = cv2.imread("Resources/podium.jpg")
rgb = cv2.cvtColor(bgr, cv2.COLOR_RGB2BGR)
# FIRST Player name editing
font_style = cv2.FONT_HERSHEY_TRIPLEX
text_size = cv2.getTextSize(top_players_name[0], font_style, 2, 3)[0]
X = int((rgb.shape[0] - text_size[0])/2)
image_arr = cv2.putText(rgb, top_players_name[0], (X, 180), font_style, 2, (0,0,0), 3, cv2.LINE_AA, False)
# SECOND Player name editing
text_size = cv2.getTextSize(top_players_name[1], font_style, 2, 3)[0]
X = int(4/5 * rgb.shape[0] - 1/2 * text_size[0])
image_arr = cv2.putText(rgb, top_players_name[1], (X, 285), font_style, 2, (0,0,0), 3, cv2.LINE_AA, False)
# Third Player name editing ---> Need to edit it
text_size = cv2.getTextSize(top_players_name[2], font_style, 2, 3)[0]
X = int(1/5 * rgb.shape[0] - 1/2 * text_size[0])
image_arr = cv2.putText(rgb, top_players_name[2], (X, 335), font_style, 2, (0,0,0), 3, cv2.LINE_AA, False)
#buffer write
image = Image.fromarray(image_arr)
from io import BytesIO
bio = BytesIO()
bio.name = 'edited_podium_buffer.jpeg'
# If image is other than RGB than converting it to RGB format
if image.mode != 'RGB':
image = image.convert('RGB')
# Generating ranklist to participants of multiplayer quiz bot
rank_list = "<b>Leaderboard of above quiz</b>\n\nFollowing list contain players score:\n\n"
rank = 1
medals = {
1: "🥇",
2: "🥈",
3: "🥉"
}
rank_alloter = lambda rank:"(" + str(rank) + ")" if rank > 3 else medals[rank]
for chat_id, score in self.players_score:
data = execute_query("select player_name from MULTIPLAYER_QUIZ_PARTICIPANTS_NAME where chat_id={};".format(chat_id))
rank_list += "<b>{} <i>{}</i> - {:.2f}</b>\n".format(rank_alloter(rank), data[0]["player_name"], score)
rank += 1
# Sending the image and leaderboard to all participants of the bot
for chat_id, _ in self.players_score:
# Logging
logger.info("{} - sending leaderboard of multiplayer quiz with id - {}".format(chat_id, self.multiplayer_quiz_id))
image.save(bio, 'PNG')
bio.seek(0)
bot.send_photo(chat_id, photo=bio)
if previous_message_sent[chat_id] == 'qe':
bot.send_message(chat_id, rank_list, reply_markup = InlineKeyboardMarkup(inline_keyboards['qe']) ,parse_mode=ParseMode.HTML)
else:
bot.send_message(chat_id, rank_list, parse_mode=ParseMode.HTML)
def multiplayer_quiz_closer(self):
"""Quiz closing function"""
if self.is_quiz_compeleted or len(self.players.keys()) < 3:
return schedule.CancelJob
self.is_quiz_compeleted = True
# Logging
logger.info("ending mutilplayer quiz with id - {}".format(self.multiplayer_quiz_id))
for chat_id in self.players.keys():
if self.players[chat_id].is_result_generated is False:
with open("Resources/Stickers/clock_showing_crab.tgs", "rb") as sticker:
bot.send_sticker(chat_id, sticker)
bot.send_message(chat_id, "<b>TIMES UP</b>", parse_mode=ParseMode.HTML)
self.players[chat_id].result_generator(self.start_time, 0, is_single_player_result = False)
if self.is_leaderboard_generated is False:
# Generating leaderboard podium image and the rank list
self.leaderboard_generator()
# Logging
logger.info("updating multiplayer record on database with id - {}".format(self.multiplayer_quiz_id))
# Updating database
execute_query("insert into MULTIPLAYER_QUIZ_RECORDS values({:d}, {:d}, current_timestamp);".format(self.multiplayer_quiz_id, len(self.players.keys())))
try:
for chat_id, score in self.players_score:
execute_query("insert into MULTIPLAYER_QUIZ_PLAYERS_PERFORMANCE values ({}, {:d}, {:.2f}, {:.2f}, {:d});".format(
chat_id,
self.multiplayer_quiz_id,
score,
self.players[chat_id].time_per_que,
self.players_score.index((chat_id, score)) + 1
))
except Exception as exp:
logger.info("exception occurred - ".format(exp))
# Deletion of multiplayer object
global ongoing_multiplayer_quiz_objects
del ongoing_multiplayer_quiz_objects[self.multiplayer_quiz_id]
return schedule.CancelJob
def remaining_time_alter(self):
if self.is_quiz_compeleted or len(self.players.keys()) < 3:
return schedule.CancelJob
for chat_id in self.players.keys():
if self.players[chat_id].is_result_generated is False:
# Logging
logger.info("{} - sending last minute alter of multiplayer quiz battle".format(chat_id))
bot.send_message(chat_id, "<b>Last 1 minute remaining</b>", parse_mode = ParseMode.HTML)
return schedule.CancelJob
def send_question(self, chat_id, context):
if self.is_quiz_compeleted:
return
try:
question = list(self.questions.keys())[self.players[chat_id].que_idx]
except Exception as E: # Array index out of bounds
# Generating result
self.players[chat_id].result_generator(self.start_time, 0, is_single_player_result = False)
self.players_quiz_completed_count += 1
# Cheking if all the user has compeleted the quiz for closing the quiz
if self.players_quiz_completed_count == len(self.players.keys()):
#logic of leaderboard sending
if self.is_quiz_compeleted is False:
self.multiplayer_quiz_closer()
return
# Logging
logger.info("{} - sending multiplayer quiz question".format(chat_id))
message = bot.send_poll(
chat_id,
question = "({}) ".format(self.players[chat_id].que_idx + 1) + question,
options = self.questions[question][0],
is_anonymous = True,
type = Poll.QUIZ,
correct_option_id = self.questions[question][1],
reply_markup = InlineKeyboardMarkup(self.skip_button)
)
payload = {
message.poll.id: {"chat_id": chat_id, "message_id": message.message_id, "multiplayer_quiz_id": self.multiplayer_quiz_id}
}
context.bot_data.update(payload)
# Setting message for checking whether the answer recieved by the user is of recently asked question or not
global previous_question_message_id
previous_question_message_id[chat_id] = message.message_id
self.players[chat_id].que_idx += 1
def recieved_answer_processor(self, answered_idx, chat_id, context):
self.players[chat_id].not_answered_ques -= 1
if super().check_answer(self.players[chat_id].que_idx, answered_idx):
self.players[chat_id].correct_answers += 1
self.send_question(chat_id, context)
def window_closer(self, context):
if self.is_window_closed:
return schedule.CancelJob
global opened_window_multiplayer_object
# Constraint of minimum 3 players to start a multiplayer quiz battle
if len(self.players.keys()) < 3:
logger.info("terminaiting multiplayer quiz(id - {}) due to insufficient players".format(self.multiplayer_quiz_id))
for chat_id in self.players.keys():
bot.send_message(chat_id, "Sorry, Insuficient no of players.You can take single player quiz.\n<b>Click - /solo_quiz</b>", parse_mode = ParseMode.HTML)
previous_message_sent[chat_id] = 'qe'
opened_window_multiplayer_object = None
return schedule.CancelJob
self.is_window_closed = True
self.is_window_open = False
self.start_time = time.time()
for chat_id in self.players.keys():
self.send_question(chat_id, context)
global ongoing_multiplayer_quiz_objects
ongoing_multiplayer_quiz_objects[self.multiplayer_quiz_id] = opened_window_multiplayer_object
opened_window_multiplayer_object = None
return schedule.CancelJob
def window_closer_scheduler(self, context):
# Scheduling the functions
# Window closer
schedule.every(7).seconds.do(self.window_closer, context)
# reamining time alert when 2 minutes left
schedule.every(7 + 6*60).seconds.do(self.remaining_time_alter)
# Leaderboard generator
schedule.every(7 + 6*60 + 60).seconds.do(self.multiplayer_quiz_closer)
def window_opener(self, chat_id, context):
# Joining the first player of the multiplayer quiz competition
logger.info("initiating multiplayer quiz with id - {}".format(self.multiplayer_quiz_id))
self.joining_request_reciever(chat_id, context)
self.window_closer_scheduler(context)
###############################################################
############ Single Player quiz handling functions ##################
def parameters_accepter(chat_id, parameter):
# if user want to terminate the quiz session(parameter = 0)
if parameter == "0":
# resend the "mm" label message
bot.send_message(chat_id, get_message("mm"), reply_markup=InlineKeyboardMarkup(inline_keyboards['mm']))
previous_message_sent[chat_id] = "mm"
logger.info("{} - terminating quiz session".format(chat_id))
return None, None
try:
if parameter == "None":
parameters[chat_id].append(None)
elif parameter.isnumeric():
parameters[chat_id].append(int(parameter))
else:
parameters[chat_id].append(parameter)
except Exception as exp:
# Just for security purpose exception will not arise
logger.info("{} - exception occurred - {}".format(chat_id, exp))
if len(parameters[chat_id]) == 1:
###### Solo Quiz only takes one parameter of topic so rest will be given here #########
if previous_message_sent[chat_id] == 'qq':
parameters[chat_id].append(10) # 10 Questions
parameters[chat_id].append(None) # any difficulty
parameters[chat_id].append(60) # 60 seconds per question
##### Summary of Solo Quiz(Quick Quiz) #######
if parameters[chat_id][0] is not None:
return "<i><b>{}</b> category is selected.</i>".format(topics[parameters[chat_id][0]]), None
else:
return "<i>All category questions will be asked.</i>", None
return "Select no of questions", InlineKeyboardMarkup(inline_keyboards['cq-2'])
elif len(parameters[chat_id]) == 2:
return "Select difficulty of questions", InlineKeyboardMarkup(inline_keyboards['cq-3'])
elif len(parameters[chat_id]) == 3:
return "How much time do you need per question(sec)? ⏰ ", InlineKeyboardMarkup(inline_keyboards['cq-4'])
elif len(parameters[chat_id]) == 4:
##### Summary of Practice Arena(Custom Quiz) #######
if previous_message_sent[chat_id] == 'cq':
return summary_generator(chat_id), None
def single_player_quiz_initiator(chat_id, context):
###### The "object creation" for QUICK/CUSTOM QUIZ ########
single_player_quiz_objects[chat_id] = SinglePlayer(parameters[chat_id], chat_id)
single_player_quiz_objects[chat_id].send_question(context)
del parameters[chat_id]
def summary_generator(chat_id):
summary = "<b>Selected parameter of the quiz</b>\n\n<i>Topic : </i> "
logger.info("{} - generating summary".format(chat_id))
if parameters[chat_id][0] is not None:
summary += "<b>{}</b>\n".format(topics[parameters[chat_id][0]])
else:
summary += "<b>Any Category</b>\n"
if parameters[chat_id][2] is not None:
summary += "<i>Difficulty : </i> <b>{}</b>\n".format(parameters[chat_id][2].upper())
else:
summary += "<i>Difficulty : </i> <b>Any Difficulty</b>\n"
summary += "<i>Number of questions : </i> <b>{}</b>".format(parameters[chat_id][1])
if parameters[chat_id][3] is not None:
summary += "\n<i>Time per question(sec) : </i> <b>{}</b>".format(parameters[chat_id][3])
else:
summary += "\n<i>Time per question : </i> <b>Unlimited</b>"
return summary
############ Multiplayer Player quiz handling functions ##################
def set_player_name(chat_id, name):
"""Saves the users alias(Player name - Public) to the database and,
send the option to start multiplayer battle with rules."""
for letter in name:
if letter.isalnum() or letter in ['@', '-', '_']:
continue
else:
bot.send_message(chat_id, "<b>Invalid Name</b>", parse_mode=ParseMode.HTML)
bot.send_message(chat_id, "Please send valid name. Refer above 👆 instructions")
return
logger.info("{} - adding player name to database".format(chat_id))
execute_query("insert into MULTIPLAYER_QUIZ_PARTICIPANTS_NAME values({:d}, \'{}\');".format(chat_id, name))
bot.send_message(chat_id, "Name added successfully 😃")
# Multiplayer quiz starting message with instructions
bot.send_message(
chat_id, get_message('mqc').format(name),
reply_markup = InlineKeyboardMarkup(inline_keyboards['mqc']),
parse_mode = ParseMode.HTML
)
previous_message_sent[chat_id] = 'mqc'
def multiplayer_quiz_initiator(chat_id, context):
global opened_window_multiplayer_object
if opened_window_multiplayer_object is None:
logger.info("{} - creating multiplayer window".format(chat_id))
opened_window_multiplayer_object = Multiplayer()
opened_window_multiplayer_object.window_opener(chat_id, context)
else:
logger.info("{} - adding player to existing window".format(chat_id))
opened_window_multiplayer_object.joining_request_reciever(chat_id, context)
############ User Interation handling functions ###################
def get_message(label):
return message[label]
def update_chat_id(chat_id):
data = execute_query("select * from ARRIVED_USERS where chat_id={};".format(chat_id))
if len(data) > 0:
return
data = execute_query("insert into ARRIVED_USERS values({});".format(chat_id))
logger.info("{} - new user arrived".format(chat_id))
########### Progress analysis generating funcions #################
def graph_generator(chat_id, marks, quiz_index, topic_wise_bar_colors):
########### Creating the graph - Bar plot #############
plt.figure(figsize=(18, 12))
plt.style.use("fivethirtyeight")
# Bar graph of marks
if len(quiz_index) >= 8:
plt.bar(quiz_index, marks, tick_label=quiz_index, width=0.8, color=topic_wise_bar_colors)
elif len(quiz_index) >=4:
plt.bar(quiz_index, marks, tick_label=quiz_index, width=0.6, color=topic_wise_bar_colors)
elif len(quiz_index) >=2:
plt.bar(quiz_index, marks, tick_label=quiz_index, width=0.4, color=topic_wise_bar_colors)
else: # when length will be 1
plt.bar(quiz_index, marks, tick_label=quiz_index, width=0.2, color=topic_wise_bar_colors)
# Horizontal line representing average marks
plt.plot(quiz_index, [sum(marks)/len(quiz_index) for x in range(len(quiz_index))], label="Average = {:.2f}%".format(sum(marks)/len(quiz_index)), color = "black")
plt.tick_params(axis='x', labelsize=20)
plt.tick_params(axis='y', labelsize=20)
plt.title("Graph containing marks of your last {} single-player quizzes\nBar colour corresponds to quiz topics".format(len(quiz_index)), fontsize=35)
plt.xlabel("Quiz Sessions", fontsize=30)
plt.ylabel("Marks Obtained (%)", fontsize=30)
plt.ylim(0, 100)
plt.xlim(quiz_index[0]-0.5, quiz_index[-1]+0.5)
plt.legend(fontsize=25)
for index, value in enumerate(marks):
if value<=97:
plt.text(int(quiz_index[0])+index, value+1, "{:.1f}".format(value), fontsize=20, ha='center')
elif value<=99:
plt.text(int(quiz_index[0])+index, value-4, "{:.1f}".format(value), fontsize=20, ha='center')
else:
plt.text(int(quiz_index[0])+index, value-4, "{:.1f}".format(value), fontsize=19, ha='center')
# Saving the plot image in buffer
bio = BytesIO()
bio.name = "marks_graph"
plt.savefig(bio, dpi=50)
#plt.savefig("marks graph.png", figsize=(2400/300, 3600/300), dpi=300)
###################################################################################################
# Reading image from buffer and converting to numpy array
graph = Image.open(bio)
graph = np.array(graph.getdata()).reshape(graph.size[1], graph.size[0], 4)
graph = graph[:, :, :3]
bio.flush()
bio.close()
# Reading the color coded blocks image from Resouces and resizing it to attach to the graph
blocks = cv2.imread("Resources/color_graph.jpg")
blocks = cv2.cvtColor(blocks, cv2.COLOR_RGB2BGR)
blocks = cv2.resize(blocks, (900, 510))
# Combining the two images and convertin to float type and then make it a Image object
combined_image = np.vstack([graph, blocks])
combined_image = combined_image.astype(np.uint8)
combined_image = Image.fromarray(combined_image)
# Saving the final Image to the Buffer memory
bio = BytesIO()
bio.name = "combined_image"
combined_image.save(bio, 'PNG')
# Sending the Image to the user
bio.seek(0)
bot.send_photo(chat_id, bio)
bio.flush()
bio.close()
def players_pa_generator(chat_id):
"""Generate the graph and report of player's perform """
global bar_colors_topic_wise
data = execute_query("select marks, time_per_que, topic from SINGLE_PLAYER_QUIZ_RECORDS where chat_id = {} order by timestamp;".format(chat_id))