forked from tannn/TriviaTime
-
Notifications
You must be signed in to change notification settings - Fork 2
/
plugin.py
4429 lines (3983 loc) · 179 KB
/
plugin.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
# -*- coding: utf-8 -*-
###
# Copyright (c) 2013, tann <[email protected]>
# All rights reserved.
#
#
###
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
import supybot.ircdb as ircdb
import supybot.ircmsgs as ircmsgs
import supybot.schedule as schedule
import supybot.log as log
import supybot.conf as conf
import os
import re
import sqlite3
import random
import time
import datetime
import unicodedata
import hashlib
#A list with items that are removed when timeout is reached, values must be unique
class TimeoutList:
"""
A dict wrapper used to store timeout values for unique usernames.
"""
def __init__(self, timeout):
self.timeout = timeout
self.dict = {}
def setTimeout(self, timeout):
self.timeout = timeout
def clearTimeout(self):
for k, t in list(self.dict.items()):
if t < (time.time() - self.timeout):
del self.dict[k]
def append(self, key):
self.clearTimeout()
self.dict[key] = time.time()
def has(self, key):
self.clearTimeout()
if key in self.dict:
return True
return False
def getTimeLeft(self, key):
return self.timeout - (time.time() - self.dict[key])
#Game instance
class Game:
"""
Main game logic, single game instance for each channel.
"""
def __init__(self, irc, channel, base):
# constants
self.unmaskedChars = " -'\"_=+&%$#@!~`()[]{}?.,<>|\\/:;"
# get utilities from base plugin
self.base = base
self.games = base.games
self.storage = base.storage
self.registryValue = base.registryValue
self.channel = channel
self.irc = irc
self.network = irc.network
# Initialize timeout lists
self.skipTimeoutList = TimeoutList(self.registryValue('skip.skipTime', channel))
self.hintTimeoutList = TimeoutList(self.registryValue('hints.extraHintTime', channel))
# Initialize state variables
self.state = 'no-question'
self.stopPending = False
self.shownHint = False
self.questionRepeated = False
# Initialize game properties
self.questionID = -1
self.questionType = ''
self.question = ''
self.answers = []
self.questionPoints = -1
self.correctPlayers = {}
self.guessedAnswers = []
self.skipList = []
self.streak = 0
self.lastWinner = ''
self.hintsCounter = 0
self.numAsked = 0
self.lastAnswer = time.time()
self.roundStartedAt = time.mktime(time.localtime())
# activate
self.loadGameState()
self.active = True
# Remove any old event and start the next question
self.removeEvent()
self.nextQuestion()
def checkAnswer(self, msg):
"""
Check users input to see if answer was given.
"""
channel = msg.args[0]
# is it a user?
username = self.base.getUsername(msg.nick, msg.prefix)
usernameCanonical = ircutils.toLower(username)
correctAnswerFound = False
correctAnswer = ''
attempt = self.normalizeString(msg.args[1])
# Check for a correct answer that hasn't already been guessed
for ans in self.answers:
normalizedAns = self.normalizeString(ans)
if normalizedAns == attempt and normalizedAns not in self.guessedAnswers:
correctAnswerFound = True
correctAnswer = ans
# Immediately return if not a correct answer
if not correctAnswerFound:
return
dbLocation = self.registryValue('admin.db')
threadStorage = Storage(dbLocation)
timeElapsed = float(time.time() - self.askedAt)
points = self.questionPoints
# Add answer to list so we can cross it out
if self.guessedAnswers.count(attempt) == 0:
self.guessedAnswers.append(attempt)
# Past first hint? deduct points
if self.hintsCounter > 1:
points /= 2 * (self.hintsCounter - 1)
# Handle a correct answer for a KAOS question
if self.questionType == 'kaos':
if usernameCanonical not in self.correctPlayers:
self.correctPlayers[usernameCanonical] = 0
self.correctPlayers[usernameCanonical] += 1
# KAOS? divide points and convert score to int
points = int(points / (len(self.answers) + 1))
self.totalAmountWon += points
# Update database with the correct guess for KAOS item
threadStorage.updateUserLog(username, self.channel, points, 0, 0)
self.lastAnswer = time.time()
self.sendMessage('\x02%s\x02 gets \x02%d\x02 points for: \x02%s\x02' % (username, points, correctAnswer))
# can show more hints now
self.shownHint = False
# Check if all answers have been answered
if len(self.guessedAnswers) == len(self.answers):
self.state = 'post-question'
self.removeEvent()
# Check if question qualifies for bonus points
bonusPointsText = ''
if len(self.correctPlayers) >= 2 and len(self.answers) >= 9:
bonusPoints = self.registryValue('kaos.payoutKAOS', self.channel)
if bonusPoints > 0:
for nick in self.correctPlayers:
threadStorage.updateUserLog(nick, self.channel, bonusPoints, 0, 0)
self.totalAmountWon += bonusPoints
bonusPointsText = 'Everyone gets a %d Point Bonus!!' % int(bonusPoints)
# Give a special KAOS message
self.sendMessage('All KAOS answered! %s' % bonusPointsText)
self.sendMessage('Total Awarded: \x02%d\x02 Points to \x02%d\x02 Players' % (int(self.totalAmountWon), len(self.correctPlayers)))
threadStorage.updateQuestionStats(self.questionID, 1, 0)
# Handle a correct answer for a regular question
else:
self.state = 'post-question'
self.removeEvent()
streakBonus = 0
minStreak = self.registryValue('general.minBreakStreak', channel)
# update streak info
if ircutils.toLower(self.lastWinner) != usernameCanonical:
#streakbreak
if self.streak > minStreak:
streakBonus = int(points * .25)
self.sendMessage('\x02%s\x02 broke \x02%s\x02\'s streak of \x02%d\x02!' % (username, self.lastWinner, self.streak))
self.lastWinner = username
self.streak = 1
else:
self.streak += 1
streakBonus = points * .25 * (self.streak-1)
streakBonus = int(min(streakBonus, points * .25))
# Update database
threadStorage.updateGameStreak(self.channel, self.lastWinner, self.streak)
threadStorage.updateUserHighestStreak(self.lastWinner, self.streak)
threadStorage.updateGameLongestStreak(self.channel, username, self.streak)
threadStorage.updateUserLog(username, self.channel, int(points + streakBonus), 1, timeElapsed)
threadStorage.updateQuestionStats(self.questionID, 1, 0)
# Show congratulatory message
self.lastAnswer = time.time()
self.sendMessage('YES, \x02%s\x02 got the correct answer, \x02%s\x02, in \x02%0.4f\x02 seconds for \x02%d(+%d)\x02 points!' % (username, correctAnswer, timeElapsed, points, streakBonus))
if self.registryValue('general.showStats', self.channel):
if self.registryValue('general.globalStats'):
stat = threadStorage.getUserStat(username, None)
else:
stat = threadStorage.getUserStat(username, self.channel)
if stat:
todaysScore = stat['points_day']
weekScore = stat['points_week']
monthScore = stat['points_month']
yearScore = stat['points_year']
totalScore = stat['points_total']
recapMessageList = ['\x02%s\x02 has won \x02%d\x02 in a row!' % (username, self.streak)]
recapMessageList.append(' Total Points')
recapMessageList.append(' TODAY: \x02%d\x02' % (todaysScore))
if weekScore > points:
recapMessageList.append(' this WEEK: \x02%d\x02' % (weekScore))
if monthScore > points:
recapMessageList.append(' this MONTH: \x02%d\x02' % (monthScore))
if yearScore > points:
recapMessageList.append(' this YEAR: \x02%d\x02' % (yearScore))
if totalScore > points:
recapMessageList.append(' & ALL TIME: \x02%d\x02' % (totalScore))
recapMessage = ''.join(recapMessageList)
self.sendMessage(recapMessage)
if self.state == 'post-question':
# Check for any pending stops, otherwise queue next question
if self.stopPending == True:
self.stop()
else:
waitTime = self.registryValue('general.waitTime',self.channel)
if waitTime < 2:
waitTime = 2
log.error('waitTime was set too low (<2 seconds). Setting to 2 seconds')
waitTime += time.time()
self.queueEvent(waitTime, self.nextQuestion)
self.state = 'no-question'
def getHintString(self, hintNum=None):
if hintNum == None:
hintNum = self.hintsCounter
hintRatio = self.registryValue('hints.hintRatio') # % to show each hint
hint = ''
ratio = float(hintRatio * .01)
charMask = self.registryValue('hints.charMask', self.channel)
# create a string with hints for all of the answers
if self.questionType == 'kaos':
for ans in self.answers:
if ircutils.toLower(ans) not in self.guessedAnswers:
ans = str(ans)
hintStr = ''
if hintNum == 0:
for char in ans:
if char in self.unmaskedChars:
hintStr += char
else:
hintStr += charMask
elif hintNum == 1:
divider = int(len(ans) * ratio)
divider = min(divider, 3)
divider = min(divider, len(ans)-1)
hintStr += ans[:divider]
masked = ans[divider:]
for char in masked:
if char in self.unmaskedChars:
hintStr += char
else:
hintStr += charMask
elif hintNum == 2:
divider = int(len(ans) * ratio)
divider = min(divider, 3)
divider = min(divider, len(ans)-1)
lettersInARow = divider-1
maskedInARow = 0
hintStr += ans[:divider]
ansend = ans[divider:]
hintsend = ''
unmasked = 0
if self.registryValue('hints.vowelsHint', self.channel):
hintStr += self.getMaskedVowels(ansend, divider-1)
else:
hintStr += self.getMaskedRandom(ansend, divider-1)
hint += ' [{0}]'.format(hintStr)
else:
ans = str(self.answers[0])
if hintNum == 0:
for char in ans:
if char in self.unmaskedChars:
hint += char
else:
hint += charMask
elif hintNum == 1:
divider = int(len(ans) * ratio)
divider = min(divider, 3)
divider = min(divider, len(ans)-1)
hint += ans[:divider]
masked = ans[divider:]
for char in masked:
if char in self.unmaskedChars:
hint += char
else:
hint += charMask
elif hintNum == 2:
divider = int(len(ans) * ratio)
divider = min(divider, 3)
divider = min(divider, len(ans)-1)
lettersInARow = divider-1
maskedInARow = 0
hint += ans[:divider]
ansend = ans[divider:]
hintsend = ''
unmasked = 0
if self.registryValue('hints.vowelsHint', self.channel):
hint += self.getMaskedVowels(ansend, divider-1)
else:
hint += self.getMaskedRandom(ansend, divider-1)
return hint.strip()
def getMaskedVowels(self, letters, sizeOfUnmasked):
charMask = self.registryValue('hints.charMask', self.channel)
hintsList = ['']
unmasked = 0
lettersInARow = sizeOfUnmasked
for char in letters:
if char in self.unmaskedChars:
hintsList.append(char)
elif str.lower(self.removeAccents(char)) in 'aeiou' and unmasked < (len(letters)-1) and lettersInARow < 3:
hintsList.append(char)
lettersInARow += 1
unmasked += 1
else:
hintsList.append(charMask)
lettersInARow = 0
hints = ''.join(hintsList)
return hints
def getMaskedRandom(self, letters, sizeOfUnmasked):
charMask = self.registryValue('hints.charMask', self.channel)
hintRatio = self.registryValue('hints.hintRatio') # % to show each hint
hints = ''
unmasked = 0
maskedInARow = 0
lettersInARow = sizeOfUnmasked
for char in letters:
if char in self.unmaskedChars:
hints += char
unmasked += 1
elif maskedInARow > 2 and unmasked < (len(letters)-1):
lettersInARow += 1
unmasked += 1
maskedInARow = 0
hints += char
elif lettersInARow < 3 and unmasked < (len(letters)-1) and random.randint(0,100) < hintRatio:
lettersInARow += 1
unmasked += 1
maskedInARow = 0
hints += char
else:
maskedInARow += 1
lettersInARow=0
hints += charMask
return hints
def getExtraHintString(self):
charMask = self.registryValue('hints.charMask', self.channel)
ans = self.answers[0]
hints = ' Extra Hint: \x02\x0312'
divider = 0
if len(ans) < 2:
divider = 0
elif self.hintsCounter == 1:
divider = 1
elif self.hintsCounter == 2:
divider = min(int((len(ans) * .25) + 1), 4)
elif self.hintsCounter == 3:
divider = min(int((len(ans) * .5) + 1), 6)
if divider == len(ans):
divider -= 1
if divider > 0:
hints += ans[:divider]
return hints
def getExtraHint(self):
if self.shownHint == False:
self.shownHint = True
self.sendMessage(self.getExtraHintString())
def getRemainingKAOS(self):
if self.shownHint == False:
self.shownHint = True
self.sendMessage('\x02\x0312%s' % (self.getHintString(self.hintsCounter-1)))
def loadGameState(self):
gameInfo = self.storage.getGame(self.channel)
if gameInfo is not None:
self.numAsked = gameInfo['num_asked']
self.roundStartedAt = gameInfo['round_started']
self.lastWinner = gameInfo['last_winner']
self.streak = int(gameInfo['streak'])
def loopEvent(self):
"""
Main game/question/hint loop called by event. Decides whether question or hint is needed.
"""
# out of hints to give?
if self.hintsCounter >= 3:
self.state = 'post-question'
if self.questionType == 'kaos':
# Create a string to show answers missed
missedAnswers = ''
for ans in self.answers:
if ircutils.toLower(ans) not in self.guessedAnswers:
missedAnswers += ' [{0}]'.format(ans)
self.sendMessage( """Time's up! No one got \x02%s\x02""" % missedAnswers.strip())
self.sendMessage("""Correctly Answered: \x02%d\x02 of \x02%d\x02 Total Awarded: \x02%d\x02 Points to \x02%d\x02 Players"""
% (len(self.guessedAnswers), len(self.answers), int(self.totalAmountWon), len(self.correctPlayers))
)
else:
self.sendMessage( """Time's up! The answer was \x02%s\x02.""" % self.answers[0])
self.storage.updateQuestionStats(self.questionID, 0, 1)
# Check for any pending stops, otherwise queue next question
if self.stopPending == True:
self.stop()
else:
waitTime = self.registryValue('general.waitTime', self.channel)
if waitTime < 2:
waitTime = 2
log.error('waitTime was set too low (<2 seconds). Setting to 2 seconds')
waitTime += time.time()
self.queueEvent(waitTime, self.nextQuestion)
self.state = 'no-question'
else:
# Give out next hint and queue this event again
self.showHint()
if self.questionType == 'kaos':
hintTime = self.registryValue('kaos.hintKAOS', self.channel)
else:
hintTime = self.registryValue('questions.hintTime', self.channel)
if hintTime < 2:
hintTime = 2
log.error('hintTime was set too low (<2 seconds). Setting to 2 seconds.')
hintTime += time.time()
self.queueEvent(hintTime, self.loopEvent)
def showHint(self):
"""
Max hints have not been reached, and no answer is found, need more hints
"""
hints = self.getHintString(self.hintsCounter)
self.hintsCounter += 1 #increment hints counter
self.shownHint = False #reset hint shown
self.sendMessage(' Hint %s: \x02\x0312%s' % (self.hintsCounter, hints), 1, 9)
def nextQuestion(self):
"""
Time for a new question
"""
inactivityTime = self.registryValue('general.timeout')
if self.lastAnswer < time.time() - inactivityTime:
self.sendMessage('Stopping due to inactivity')
self.stop()
return
elif self.stopPending == True:
self.stop()
return
# Reset and increment question properties
self.state = 'pre-question'
del self.skipList[:]
del self.guessedAnswers[:]
self.totalAmountWon = 0
self.correctPlayers.clear()
self.hintsCounter = 0
self.numAsked += 1
# grab the next question
numQuestion = self.storage.getNumQuestions()
if numQuestion == 0:
self.sendMessage('There are no questions. Stopping. If you are an admin, use the addfile command to add questions to the database.')
self.stop()
return
# Check if we've asked all questions
numQuestionsLeftInRound = self.storage.getNumQuestionsNotAsked(self.channel, self.roundStartedAt)
if numQuestionsLeftInRound == 0:
self.numAsked = 1
self.roundStartedAt = time.mktime(time.localtime())
self.storage.updateGameRoundStarted(self.channel, self.roundStartedAt)
self.sendMessage('All of the questions have been asked, shuffling and starting over')
# Update DB with new round number
self.storage.updateGame(self.channel, self.numAsked)
# Retrieve new question from DB
retrievedQuestion = self.retrieveQuestion()
self.questionID = retrievedQuestion['id']
self.questionType = retrievedQuestion['type']
self.question = retrievedQuestion['question']
self.answers = retrievedQuestion['answers']
self.questionPoints = retrievedQuestion['points']
# Store the question and round number so it can be reported
self.storage.insertGameLog(self.channel, self.numAsked, self.questionID, self.question)
# Send question to channel
self.sendQuestion()
# Set state variables after question has been sent
self.state = 'in-question'
self.questionRepeated = False
self.shownHint = False
self.askedAt = time.time()
# Start hint loop
self.loopEvent()
def normalizeString(self, s):
return str.lower(self.removeExtraSpaces(self.removeAccents(s)))
def queueEvent(self, time, event):
"""
Schedules a new event.
"""
# Schedule a new event to happen at the specified time
if self.active:
try:
schedule.addEvent(event, time, '%s.trivia' % self.channel)
except AssertionError as e:
log.error('Unable to queue {0} because another event is already scheduled.'.format(event.__name__))
def removeAccents(self, text):
text = str(text)
normalized = unicodedata.normalize('NFKD', text)
normalized = ''.join([c for c in normalized if not unicodedata.combining(c)])
return normalized
def removeExtraSpaces(self, text):
return utils.str.normalizeWhitespace(text)
def repeatQuestion(self):
if self.questionRepeated == False:
self.questionRepeated = True
self.sendQuestion()
def removeEvent(self):
"""
Remove/cancel trivia timer event
"""
# try and remove the current timer and thread, if we fail just carry on
try:
schedule.removeEvent('%s.trivia' % self.channel)
except KeyError:
pass
def retrieveQuestion(self):
# Retrieve and parse question data from database
rawData = self.storage.getRandomQuestionNotAsked(self.channel, self.roundStartedAt)
rawQuestion = rawData['question']
netTimesAnswered = rawData['num_answered'] - rawData['num_missed']
questionParts = rawQuestion.split('*')
if len(questionParts) > 1:
question = questionParts[0].strip()
answers = []
# Parse question for KAOS
if ircutils.toLower(question[:4]) == 'kaos':
questionType = 'kaos'
for ans in questionParts[1:]:
if answers.count(ans) == 0: # Filter out duplicate answers
answers.append(str(ans).strip())
# Parse question for Unscramble
elif ircutils.toLower(question[:5]) == 'uword':
questionType = 'uword'
ans = questionParts[1]
answers.append(str(ans).strip())
shuffledLetters = list(str(ans))
random.shuffle(shuffledLetters)
question = 'Unscramble the letters: {0}'.format(' '.join(shuffledLetters))
# Parse standard question
else:
questionType = 'regular'
for ans in questionParts[1:]:
answers.append(str(ans).strip())
# Calculate base points
if questionType == 'kaos':
points = self.registryValue('kaos.defaultKAOS', self.channel) * len(answers)
else:
points = self.registryValue('questions.defaultPoints', self.channel)
# Calculate additional points
addPoints = -5 * netTimesAnswered
addPoints = min(addPoints, 200)
addPoints = max(addPoints, -200)
return {'id': rawData['id'],
'type': questionType,
'points': points + addPoints,
'question': question,
'answers': answers
}
else:
log.info('Question #%d is invalid.' % rawData['id'])
# TODO report bad question
# default question, everything went wrong with grabbing question
return {'id': rawData['id'],
'type': 'kaos',
'points': 10,
'question': 'KAOS: The most awesome users in this channel? (This is a panic question, if you see this report this question. it is malformed. Please report immediately.)',
'answers': ['cars', 'some_weirdo', 'kessa', 'paimun']
}
def sendMessage(self, msg, color=None, bgcolor=None):
""" <msg>, [<color>], [<bgcolor>]
helper for game instance to send messages to channel
"""
# no color
self.irc.sendMsg(ircmsgs.privmsg(self.channel, '%s' % msg))
def sendQuestion(self):
question = self.question
if question[-1:] != '?':
question += '?'
# bold the q, add color
questionText = '\x02\x0303%s' % (question)
# KAOS? report # of answers
if self.questionType == 'kaos':
questionText += ' %d possible answers' % (len(self.answers))
questionMessageString = ' %s: %s' % (self.numAsked, questionText)
maxLength = 400
questionMesagePieces = [questionMessageString[i:i+maxLength] for i in range(0, len(questionMessageString), maxLength)]
multipleMessages=False
for msgPiece in questionMesagePieces:
if multipleMessages:
msgPiece = '\x02\x0303%s' % (msgPiece)
multipleMessages = True
self.sendMessage(msgPiece, 1, 9)
def stop(self):
"""
Stop a game in progress
"""
# responsible for stopping a timer/thread after being told to stop
self.active = False
self.stopPending = False
self.removeEvent()
self.sendMessage('Trivia stopped. :\'(')
channelCanonical = ircutils.toLower(self.channel)
if self.network in self.games:
if channelCanonical in self.games[self.network]:
del self.games[self.network][channelCanonical]
#Storage for users and points using sqlite3
class Storage:
"""
Storage class
"""
def __init__(self,loc):
self.loc = loc
self.conn = sqlite3.connect(loc, check_same_thread=False) # dont check threads
# otherwise errors
self.conn.text_factory = str
self.conn.row_factory = sqlite3.Row
def chunk(self, qs, rows=10000):
""" Divides the data into 10000 rows each """
for i in range(0, len(qs), rows):
yield qs[i:i+rows]
def countTemporaryQuestions(self, channel=None):
c = self.conn.cursor()
if channel is None:
c.execute('''SELECT COUNT(*)
FROM triviatemporaryquestion''')
else:
c.execute('''SELECT COUNT(*)
FROM triviatemporaryquestion
WHERE channel_canonical=?''',
(ircutils.toLower(channel),))
row = c.fetchone()
c.close()
return row[0]
def countDeletes(self, channel=None):
c = self.conn.cursor()
if channel is None:
c.execute('''SELECT COUNT(*)
FROM triviadelete''')
else:
c.execute('''SELECT COUNT(*)
FROM triviadelete
WHERE channel_canonical=?''',
(ircutils.toLower(channel),))
row = c.fetchone()
c.close()
return row[0]
def countEdits(self, channel=None):
c = self.conn.cursor()
if channel is None:
c.execute('''SELECT COUNT(*)
FROM triviaedit''')
else:
c.execute('''SELECT COUNT(*)
FROM triviaedit
WHERE channel_canonical=?''',
(ircutils.toLower(channel),))
row = c.fetchone()
c.close()
return row[0]
def countNotMyEdits(self, username, channel=None):
c = self.conn.cursor()
if channel is None:
c.execute('''SELECT COUNT(*)
FROM triviaedit
WHERE username<>?''',
(username,))
else:
c.execute('''SELECT COUNT(*)
FROM triviaedit
WHERE username<>?
AND channel_canonical=?''',
(username,
ircutils.toLower(channel),))
row = c.fetchone()
c.close()
return row[0]
def countMyEdits(self, username, channel=None):
c = self.conn.cursor()
if channel is None:
c.execute('''SELECT COUNT(*)
FROM triviaedit
WHERE username=?''',
(username,))
else:
c.execute('''SELECT COUNT(*)
FROM triviaedit
WHERE username=?
AND channel_canonical=?''',
(username,
ircutils.toLower(channel),))
row = c.fetchone()
c.close()
return row[0]
def countReports(self, channel=None):
c = self.conn.cursor()
if channel is None:
c.execute('''SELECT COUNT(*)
FROM triviareport''')
else:
c.execute('''SELECT COUNT(*)
FROM triviareport
WHERE channel_canonical=?''',
(ircutils.toLower(channel),))
row = c.fetchone()
c.close()
return row[0]
def deleteQuestion(self, questionId):
c = self.conn.cursor()
test = c.execute('''UPDATE triviaquestion
SET deleted=1
WHERE id=?''',
(questionId,))
self.conn.commit()
c.close()
def dropActivityTable(self):
c = self.conn.cursor()
try:
c.execute('''DROP TABLE triviaactivity''')
except:
pass
c.close()
def dropDeleteTable(self):
c = self.conn.cursor()
try:
c.execute('''DROP TABLE triviadelete''')
except:
pass
c.close()
def dropUserTable(self):
c = self.conn.cursor()
try:
c.execute('''DROP TABLE triviausers''')
except:
pass
c.close()
def dropLoginTable(self):
c = self.conn.cursor()
try:
c.execute('''DROP TABLE trivialogin''')
except:
pass
c.close()
def dropUserLogTable(self):
c = self.conn.cursor()
try:
c.execute('''DROP TABLE triviauserlog''')
except:
pass
c.close()
def dropGameTable(self):
c = self.conn.cursor()
try:
c.execute('''DROP table triviagames''')
except:
pass
c.close()
def dropGameLogTable(self):
c = self.conn.cursor()
try:
c.execute('''DROP TABLE triviagameslog''')
c.execute('''DROP INDEX gamelograndomindex''')
except:
pass
c.close()
def dropReportTable(self):
c = self.conn.cursor()
try:
c.execute('''DROP TABLE triviareport''')
except:
pass
c.close()
def dropQuestionTable(self):
c = self.conn.cursor()
try:
c.execute('''DROP TABLE triviaquestion''')
c.execute('''DROP INDEX questionrandomindex''')
except:
pass
c.close()
def dropTemporaryQuestionTable(self):
c = self.conn.cursor()
try:
c.execute('''DROP TABLE triviatemporaryquestion''')
except:
pass
c.close()
def dropEditTable(self):
c = self.conn.cursor()
try:
c.execute('''DROP TABLE triviaedit''')
except:
pass
c.close()
def dropLevelTable(self):
c = self.conn.cursor()
try:
c.execute('''DROP TABLE trivialevel''')
except:
pass
c.close()
def getRandomQuestionNotAsked(self, channel, roundStart):
c = self.conn.cursor()
c.execute('''SELECT *
FROM triviaquestion
WHERE deleted=0 AND
id NOT IN
(SELECT tl.line_num
FROM triviagameslog tl
WHERE tl.channel_canonical=? AND
tl.asked_at>=?)
ORDER BY random() LIMIT 1''',
(ircutils.toLower(channel),roundStart))
row = c.fetchone()
c.close()
return row
def getQuestionById(self, id):
c = self.conn.cursor()
c.execute('''SELECT *
FROM triviaquestion
WHERE id=? LIMIT 1''',
(id,))
row = c.fetchone()
c.close()
return row
def getQuestionByRound(self, roundNumber, channel):
channel=ircutils.toLower(channel)
c = self.conn.cursor()
c.execute('''SELECT *
FROM triviaquestion
WHERE id=(SELECT tgl.line_num
FROM triviagameslog tgl
WHERE tgl.round_num=? AND
tgl.channel_canonical=?
ORDER BY id DESC LIMIT 1)''',
(roundNumber,channel))
row = c.fetchone()
c.close()
return row
def getNumQuestionsNotAsked(self, channel, roundStart):
c = self.conn.cursor()
c.execute('''SELECT count(id)
FROM triviaquestion
WHERE deleted=0 AND
id NOT IN
(SELECT tl.line_num
FROM triviagameslog tl
WHERE tl.channel=? AND
tl.asked_at>=?)''',
(channel,roundStart))
row = c.fetchone()
c.close()
return row[0]
def getUserRank(self, username, channel):
usernameCanonical = ircutils.toLower(username)
channelCanonical = None
if channel is not None:
channelCanonical = ircutils.toLower(channel)
dateObject = datetime.date.today()
day = dateObject.day
month = dateObject.month
year = dateObject.year
data = {}
# Retrieve total rank
query = '''SELECT tr.rank
FROM (SELECT COUNT(tu2.id)+1 AS rank
FROM (SELECT id,
username,
sum(points_made) AS totalscore
FROM triviauserlog'''
arguments = []
if channel is not None:
query = '''%s WHERE channel_canonical=?''' % (query)
arguments.append(channelCanonical)
query = '''%s GROUP BY username_canonical) AS tu2
WHERE tu2.totalscore > (
SELECT SUM(points_made)
FROM triviauserlog
WHERE username_canonical=?''' % (query)
arguments.append(usernameCanonical)
if channel is not None:
query = '''%s AND channel_canonical=?''' % (query)
arguments.append(channelCanonical)
query = '''%s )) AS tr
WHERE EXISTS(
SELECT *
FROM triviauserlog
WHERE username_canonical=?''' % (query)
arguments.append(usernameCanonical)