]> jfr.im git - erebus.git/blame - modules/trivia.py
COPYING -> LICENSE
[erebus.git] / modules / trivia.py
CommitLineData
80d02bd8 1# Erebus IRC bot - Author: Erebus Team
4477123d 2# vim: fileencoding=utf-8
c695f740 3# trivia module
80d02bd8 4# This file is released into the public domain; see http://unlicense.org/
5
a28e2ae9 6from __future__ import print_function
7
80d02bd8 8# module info
9modinfo = {
10 'author': 'Erebus Team',
11 'license': 'public domain',
fa93b933 12 'compatible': [0],
a62d0d18 13 'depends': ['userinfo'],
14 'softdeps': ['help'],
80d02bd8 15}
16
17# preamble
18import modlib
19lib = modlib.modlib(__name__)
20def modstart(parent, *args, **kwargs):
5871567f 21 state.gotParent(parent)
22 lib.hookchan(state.db['chan'])(trivia_checkanswer) # we need parent for this. so it goes here.
80d02bd8 23 return lib.modstart(parent, *args, **kwargs)
24def modstop(*args, **kwargs):
c0eee1b4 25 global state
8ef938d0 26 try:
27 stop()
28 state.closeshop()
29 del state
30 except Exception: pass
80d02bd8 31 return lib.modstop(*args, **kwargs)
32
33# module code
a28e2ae9 34import json, random, threading, re, time, datetime, os, sys
35
36if sys.version_info.major < 3:
37 timerbase = threading._Timer
38else:
39 timerbase = threading.Timer
40
b16b8c05 41
c0eee1b4 42try:
be8072b5 43 import twitter
c53f6514 44except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
c0eee1b4 45
b16b8c05 46def findnth(haystack, needle, n): #http://stackoverflow.com/a/1884151
47 parts = haystack.split(needle, n+1)
48 if len(parts)<=n+1:
49 return -1
50 return len(haystack)-len(parts[-1])-len(needle)
80d02bd8 51
00ccae72 52def person(num, throwindexerror=False):
53 try:
54 return state.db['users'][state.db['ranks'][num]]['realnick']
55 except IndexError:
56 if throwindexerror:
57 raise
58 else:
59 return ''
60
3b89ebff 61def pts(num):
00ccae72 62 try:
63 return str(state.db['users'][state.db['ranks'][num]]['points'])
64 except IndexError:
65 return 0
2bb267e0 66
00ccae72 67def country(num, default="??"):
aa582dd7 68 return lib.mod('userinfo').get(person(num), 'country', default=default).upper()
8ef938d0 69
a28e2ae9 70class MyTimer(timerbase):
be8072b5 71 def __init__(self, *args, **kwargs):
a28e2ae9 72 timerbase.__init__(self, *args, **kwargs)
be8072b5 73 self.daemon = True
74
80d02bd8 75class TriviaState(object):
5871567f 76 def __init__(self, parent=None, pointvote=False):
77 if parent is not None:
78 self.gotParent(parent, pointvote)
79
80 def gotParent(self, parent, pointvote=False):
bf8676ae 81 self.parent = parent
82 self.questionfile = self.parent.cfg.get('trivia', 'jsonpath', default="./modules/trivia.json")
83 self.db = json.load(open(self.questionfile, "r"))
8ad3a154 84 self.questions = self.db['questions'][self.db['category']]
bf8676ae 85 self.chan = self.db['chan']
86 self.curq = None
87 self.nextq = None
656dc5a4 88 self.nextqid = None
bf8676ae 89 self.nextquestiontimer = None
90 self.steptimer = None
91 self.hintstr = None
92 self.hintanswer = None
93 self.hintsgiven = 0
b16b8c05 94 self.revealpossibilities = None
bf8676ae 95 self.gameover = False
96 self.missedquestions = 0
97 self.curqid = None
98 self.lastqid = None
80d02bd8 99
00ccae72 100 if 'lastwon' not in self.db or self.db['lastwon'] is None:
101 self.db['lastwon'] = time.time()
7bd5e7d5 102
c53f6514 103 if pointvote:
bcb6dc21 104 self.getchan().fastmsg("Vote for the next round target points! Options: %s. Vote using !vote <choice>" % (', '.join([str(x) for x in self.db['targetoptions']])))
105 self.getchan().fastmsg("You have %s seconds." % (self.db['votetimer']))
c53f6514 106 self.voteamounts = dict([(x, 0) for x in self.db['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
be8072b5 107 self.pointvote = MyTimer(self.db['votetimer'], self.endPointVote)
c53f6514 108 self.pointvote.start()
109 else:
110 self.pointvote = None
111
8770f6ef 112# def __del__(self):
113# self.closeshop()
77c61775 114 def closeshop(self):
2bb487be 115 try:
116 self.steptimer.cancel()
117 self.steptimer = None
118 except: pass
119 try:
120 self.nextquestiontimer.cancel()
121 self.nextquestiontimer = None
122 except: pass
b9daa51a 123
67faf5d7 124 def savedb(self): #returns whether or not it was able to save
c695f740 125 if json is not None and json.dump is not None:
67faf5d7 126# json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
127 dbjson = json.dumps(self.db)
128 if len(dbjson) > 0:
3f04e466 129 os.rename(self.questionfile, self.questionfile+".auto.bak")
67faf5d7 130 tmpfn = os.tempnam('.', 'trivia')
131 try:
132 f = open(tmpfn, "w")
133 f.write(dbjson)
134 f.close()
135 os.rename(tmpfn, self.questionfile)
136 return True
137 except: #if something happens, restore the backup
3f04e466 138 os.rename(self.questionfile+".auto.bak", self.questionfile)
67faf5d7 139 try:
140 os.unlink(tmpfn)
141 except OSError: # temp file is already gone
142 pass
f5f2b592 143 raise # we may be better off just swallowing exceptions?
67faf5d7 144 return False
80d02bd8 145
fadbf980 146 def getchan(self):
147 return self.parent.channel(self.chan)
148 def getbot(self):
149 return self.getchan().bot
150
b16b8c05 151 def nexthint(self, hintnum):
b16b8c05 152 answer = self.hintanswer
153
b5c89dfb 154 if self.hintstr is None or self.revealpossibilities is None or self.reveal is None:
93ce52fd 155 oldhintstr = ""
b16b8c05 156 self.hintstr = list(re.sub(r'[a-zA-Z0-9]', '*', answer))
157 self.revealpossibilities = range(''.join(self.hintstr).count('*'))
93ce52fd 158 self.reveal = int(round(''.join(self.hintstr).count('*') * (7/24.0)))
159 else:
160 oldhintstr = ''.join(self.hintstr)
b16b8c05 161
b68479d7 162 try:
163 for i in range(self.reveal):
164 revealcount = random.choice(self.revealpossibilities)
165 revealloc = findnth(''.join(self.hintstr), '*', revealcount)
166 self.revealpossibilities.remove(revealcount)
167 self.hintstr[revealloc] = answer[revealloc]
168 except IndexError: pass # if everything is revealed, random.choice will IndexError
2bb267e0 169 if oldhintstr != ''.join(self.hintstr): self.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self.hintstr)))
b16b8c05 170
77c61775 171 self.hintsgiven += 1
172
c4763e66 173 if hintnum < self.db['hintnum']:
be8072b5 174 self.steptimer = MyTimer(self.db['hinttimer'], self.nexthint, args=[hintnum+1])
b16b8c05 175 self.steptimer.start()
176 else:
be8072b5 177 self.steptimer = MyTimer(self.db['hinttimer'], self.nextquestion, args=[True])
b16b8c05 178 self.steptimer.start()
179
77c61775 180 def doGameOver(self):
7bd5e7d5 181 msg = self.getchan().msg
c0eee1b4 182 winner = person(0)
77c61775 183 try:
184 msg("\00312THE GAME IS OVER!!!")
00ccae72 185 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
186 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
187 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
188 [msg("%dth place: %s (%s)" % (i+1, person(i, True), pts(i))) for i in range(3,10)]
77c61775 189 except IndexError: pass
09566235 190 except Exception as e:
191 msg("DERP! %r" % (e))
c0eee1b4 192
5f42c250 193 self.db['lastwinner'] = winner
194 self.db['lastwon'] = time.time()
195
7bd5e7d5 196 if self.db['hofpath'] is not None and self.db['hofpath'] != '':
197 self.writeHof()
198
77c61775 199 self.db['users'] = {}
200 self.db['ranks'] = []
b68479d7 201 self.savedb()
77c61775 202 stop()
203 self.closeshop()
c0eee1b4 204
c53f6514 205 try:
c0eee1b4 206 t = twitter.Twitter(auth=twitter.OAuth(self.getbot().parent.cfg.get('trivia', 'token'),
207 self.getbot().parent.cfg.get('trivia', 'token_sec'),
208 self.getbot().parent.cfg.get('trivia', 'con'),
209 self.getbot().parent.cfg.get('trivia', 'con_sec')))
210 t.statuses.update(status="Round is over! The winner was %s" % (winner))
c53f6514 211 except: pass #don't care if errors happen updating twitter.
212
5871567f 213 self.__init__(self.parent, True)
c53f6514 214
7bd5e7d5 215 def writeHof(self):
216 def person(num):
217 try: return self.db['users'][self.db['ranks'][num]]['realnick']
218 except: return "none"
219 def pts(num):
220 try: return str(self.db['users'][self.db['ranks'][num]]['points'])
221 except: return 0
222
aaf381b8 223 status = False
b68479d7 224 f = None
7bd5e7d5 225 try:
226 f = open(self.db['hofpath'], 'rb+')
227 for i in range(self.db['hoflines']): #skip this many lines
228 f.readline()
229 insertpos = f.tell()
230 fcontents = f.read()
231 f.seek(insertpos)
232 f.write((self.db['hofformat']+"\n") % {
233 'date': time.strftime("%F", time.gmtime()),
00ccae72 234 'duration': str(datetime.timedelta(seconds=time.time()-self.db['lastwon'])),
7bd5e7d5 235 'targetscore': self.db['target'],
236 'firstperson': person(0),
237 'firstscore': pts(0),
238 'secondperson': person(1),
239 'secondscore': pts(1),
240 'thirdperson': person(2),
241 'thirdscore': pts(2),
242 })
243 f.write(fcontents)
aaf381b8 244 status = True
7bd5e7d5 245 except Exception as e:
aaf381b8 246 status = False
7bd5e7d5 247 finally:
b68479d7 248 if f is not None:
249 f.close()
aaf381b8 250 return status
7bd5e7d5 251
c53f6514 252 def endPointVote(self):
253 self.getchan().msg("Voting has ended!")
254 votelist = sorted(self.voteamounts.items(), key=lambda item: item[1]) #sort into list of tuples: [(option, number_of_votes), ...]
255 for i in range(len(votelist)-1):
256 item = votelist[i]
257 self.getchan().msg("%s place: %s (%s votes)" % (len(votelist)-i, item[0], item[1]))
258 self.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist[-1][0], votelist[-1][1]))
c0eee1b4 259
c53f6514 260 self.db['target'] = votelist[-1][0]
261 self.pointvote = None
77c61775 262
38b29993 263 self.nextquestion() #start the game!
264
442ed923 265 def nextquestion(self, qskipped=False, iteration=0, skipwait=False):
7b832b55 266 self.lastqid = self.curqid
6bdfec48 267 self.curq = None
7b832b55 268 self.curqid = None
77c61775 269 if self.gameover == True:
270 return self.doGameOver()
fadbf980 271 if qskipped:
be8072b5 272 self.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self.hintanswer))
c0eee1b4 273 self.missedquestions += 1
274 else:
275 self.missedquestions = 0
f8cc0124 276 if 'topicformat' in self.db and self.db['topicformat'] is not None:
277 self.getbot().conn.send("TOPIC %s" % (self.db['chan']))
fadbf980 278
9138aa03 279 if isinstance(self.steptimer, MyTimer):
b16b8c05 280 self.steptimer.cancel()
9138aa03 281 if isinstance(self.nextquestiontimer, MyTimer):
442ed923 282 self.nextquestiontimer.cancel()
283 self.nextquestiontimer = None
c0eee1b4 284
b16b8c05 285 self.hintstr = None
77c61775 286 self.hintsgiven = 0
b16b8c05 287 self.revealpossibilities = None
b5c89dfb 288 self.reveal = None
b16b8c05 289
af349654 290 self.savedb()
291
c4763e66 292 if self.missedquestions > self.db['maxmissedquestions']:
c0eee1b4 293 stop()
ce03ceda 294 self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game." % (self.missedquestions))
295 return
b16b8c05 296
442ed923 297 if skipwait:
6bdfec48 298 self._nextquestion(iteration)
442ed923 299 else:
be8072b5 300 self.nextquestiontimer = MyTimer(self.db['questionpause'], self._nextquestion, args=[iteration])
442ed923 301 self.nextquestiontimer.start()
302
6bdfec48 303 def _nextquestion(self, iteration):
e5a3970b 304 if self.nextq is not None:
2520caee 305 nextqid = None
e5a3970b 306 nextq = self.nextq
307 self.nextq = None
656dc5a4 308 elif self.nextqid is not None:
309 nextqid = self.nextqid
310 nextq = self.questions[nextqid]
311 self.nextqid = None
c695f740 312 else:
8ad3a154 313 nextqid = random.randrange(0, len(self.questions))
314 nextq = self.questions[nextqid]
b5c89dfb 315
fd07173d 316 if nextq[0].startswith("!"):
2520caee 317 nextqid = None
b5c89dfb 318 nextq = specialQuestion(nextq)
319
aa0e4be4 320 if len(nextq) > 2 and time.time() - nextq[2] < 7*24*60*60 and iteration < 10:
442ed923 321 return self._nextquestion(iteration=iteration+1) #short-circuit to pick another question
ebee6edb 322 if len(nextq) > 2:
323 nextq[2] = time.time()
324 else:
325 nextq.append(time.time())
b5c89dfb 326
93ce52fd 327 if isinstance(nextq[1], basestring):
328 nextq[1] = nextq[1].lower()
329 else:
330 nextq[1] = [s.lower() for s in nextq[1]]
c695f740 331
00ccae72 332 qtext = "\00312,01Next up: "
bf8676ae 333 qtext += "(%5d)" % (random.randint(0,99999))
ebee6edb 334 qary = nextq[0].split(None)
71e0b5fb 335 qtext += " "
c695f740 336 for qword in qary:
af349654 337 spacer = random.choice(
338 range(0x61,0x7A) + ([0x20]*4)
339 )
340 qtext += "\00304,01"+qword+"\00301,01"+chr(spacer) #a-z
656dc5a4 341 if not self.getbot().fastmsg(self.chan, qtext): #if message is too long:
bcb6dc21 342 if not self.getbot().fastmsg(self.chan, "\00312,01Next up: " + ("(%5d)" % (random.randint(0,99999))) + "\00304,01" + nextq[0]):
343 if nextqid is None: nextqid = "manual"
344 self.getbot().slowmsg(self.chan, "(Unable to ask question #%s: line too long)" % (nextqid))
345 return self._nextquestion(iteration) #retry; don't increment the iteration
80d02bd8 346
b5c89dfb 347 self.curq = nextq
7b832b55 348 self.curqid = nextqid
b5c89dfb 349
ebee6edb 350 if isinstance(self.curq[1], basestring): self.hintanswer = self.curq[1]
351 else: self.hintanswer = random.choice(self.curq[1])
c0eee1b4 352
be8072b5 353 self.steptimer = MyTimer(self.db['hinttimer'], self.nexthint, args=[1])
b16b8c05 354 self.steptimer.start()
355
80d02bd8 356 def checkanswer(self, answer):
9557ee54 357 if self.curq is None:
358 return False
ebee6edb 359 elif isinstance(self.curq[1], basestring):
360 return answer.lower() == self.curq[1]
80d02bd8 361 else: # assume it's a list or something.
ebee6edb 362 return answer.lower() in self.curq[1]
77c61775 363
c53f6514 364 def addpoint(self, user_obj, count=1):
365 user_nick = str(user_obj)
366 user = user_nick.lower() # save this separately as we use both
80d02bd8 367 if user in self.db['users']:
368 self.db['users'][user]['points'] += count
369 else:
c53f6514 370 self.db['users'][user] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
9557ee54 371 self.db['ranks'].append(user)
80d02bd8 372
e5a3970b 373 self.db['ranks'].sort(key=lambda nick: self.db['users'][nick]['points'], reverse=True) #re-sort ranks, rather than dealing with anything more efficient
6374d61f 374 for i in range(0, len(self.db['ranks'])):
375 nick = self.db['ranks'][i]
376 self.db['users'][nick]['rank'] = i
77c61775 377
e5a3970b 378 if self.db['users'][user]['points'] >= self.db['target']:
77c61775 379 self.gameover = True
380
80d02bd8 381 return self.db['users'][user]['points']
382
383 def points(self, user):
9557ee54 384 user = str(user).lower()
80d02bd8 385 if user in self.db['users']:
386 return self.db['users'][user]['points']
387 else:
388 return 0
389
390 def rank(self, user):
c695f740 391 user = str(user).lower()
fadbf980 392 if user in self.db['users']:
393 return self.db['users'][user]['rank']+1
394 else:
395 return len(self.db['users'])+1
77c61775 396
c695f740 397 def targetuser(self, user):
77c61775 398 if len(self.db['ranks']) == 0: return "no one is ranked!"
399
c695f740 400 user = str(user).lower()
fadbf980 401 if user in self.db['users']:
402 rank = self.db['users'][user]['rank']
403 if rank == 0:
404 return "you're in the lead!"
405 else:
406 return self.db['ranks'][rank-1]
c695f740 407 else:
fadbf980 408 return self.db['ranks'][-1]
c695f740 409 def targetpoints(self, user):
77c61775 410 if len(self.db['ranks']) == 0: return 0
411
c695f740 412 user = str(user).lower()
fadbf980 413 if user in self.db['users']:
414 rank = self.db['users'][user]['rank']
415 if rank == 0:
af349654 416 return ""
fadbf980 417 else:
af349654 418 return "("+str(self.db['users'][self.db['ranks'][rank-1]]['points'])+")"
c695f740 419 else:
af349654 420 return "("+str(self.db['users'][self.db['ranks'][-1]]['points'])+")"
80d02bd8 421
5871567f 422state = TriviaState()
9557ee54 423
5871567f 424# we have to hook this in modstart, since we don't know the channel until then.
80d02bd8 425def trivia_checkanswer(bot, user, chan, *args):
80d02bd8 426 line = ' '.join([str(arg) for arg in args])
427 if state.checkanswer(line):
6bdfec48 428 state.curq = None
93ce52fd 429 if state.hintanswer.lower() == line.lower():
af349654 430 bot.fastmsg(chan, "\00312%s\003 has it! The answer was \00312%s\003. New score: %d. Rank: %d. Target: %s %s" % (user, line, state.addpoint(user), state.rank(user), state.targetuser(user), state.targetpoints(user)))
93ce52fd 431 else:
af349654 432 bot.fastmsg(chan, "\00312%s\003 has it! The answer was \00312%s\003 (hinted answer: %s). New score: %d. Rank: %d. Target: %s%s" % (user, line, state.hintanswer, state.addpoint(user), state.rank(user), state.targetuser(user), state.targetpoints(user)))
77c61775 433 if state.hintsgiven == 0:
6374d61f 434 bot.msg(chan, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user)))
9557ee54 435 state.nextquestion()
80d02bd8 436
f5aec865 437@lib.hook(glevel=1, needchan=False, wantchan=True)
67faf5d7 438@lib.help(None, "saves the trivia database")
439def save(bot, user, chan, realtarget, *args):
f5aec865 440 if chan is not None: replyto = chan
67faf5d7 441 else: replyto = user
442
443 if state.savedb():
444 bot.msg(replyto, "Save successful.")
445 else:
446 bot.msg(replyto, "Save failed!")
447
f5aec865 448@lib.hook(needchan=False, wantchan=True)
5f03d045 449@lib.help("[<user>]", "shows how many points you or someone has")
fb20be7c 450def points(bot, user, chan, realtarget, *args):
f5aec865 451 if chan is not None: eplyto = chan
80d02bd8 452 else: replyto = user
453
454 if len(args) != 0: who = args[0]
455 else: who = user
456
457 bot.msg(replyto, "%s has %d points." % (who, state.points(who)))
458
fb20be7c 459@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 460@lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
80d02bd8 461@lib.argsGE(1)
fb20be7c 462def give(bot, user, chan, realtarget, *args):
80d02bd8 463 whoto = args[0]
c695f740 464 if len(args) > 1:
465 numpoints = int(args[1])
466 else:
467 numpoints = 1
468 balance = state.addpoint(whoto, numpoints)
fadbf980 469
c695f740 470 bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance))
471
fb20be7c 472@lib.hook(glevel=1, needchan=False)
5f03d045 473@lib.help("<qid>", "sets next question to one in the database")
474@lib.argsEQ(1)
fb20be7c 475def setnextid(bot, user, chan, realtarget, *args):
9306587e 476 try:
477 qid = int(args[0])
656dc5a4 478 except ValueError:
479 bot.msg(user, "Error: QID must be a number.")
480 return
481 if qid >= len(state.questions):
482 bot.msg(user, "Error: no such QID.")
483 return
484 state.nextqid = qid
4d925ae3 485 bot.msg(user, "Done. Next question is %d: %s" % (qid, state.questions[qid][0]), truncate=True)
9306587e 486
fb20be7c 487@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 488@lib.help("<q>*<a>", "sets next question to one not in database")
c695f740 489@lib.argsGE(1)
fb20be7c 490def setnext(bot, user, chan, realtarget, *args):
c695f740 491 line = ' '.join([str(arg) for arg in args])
aa0e4be4 492 linepieces = line.split('*', 1)
b5c89dfb 493 if len(linepieces) < 2:
494 bot.msg(user, "Error: need <question>*<answer>")
495 return
c695f740 496 question = linepieces[0].strip()
497 answer = linepieces[1].strip()
ebee6edb 498 state.nextq = [question, answer]
c695f740 499 bot.msg(user, "Done.")
500
fb20be7c 501@lib.hook(glevel=1, needchan=False)
5f03d045 502@lib.help(None, "skips to next question")
fb20be7c 503def skip(bot, user, chan, realtarget, *args):
442ed923 504 state.nextquestion(qskipped=True, skipwait=True)
c695f740 505
492f66ea 506@lib.hook(('start','trivia'), needchan=False, wantchan=True)
5f03d045 507@lib.help(None, "starts the trivia game")
fb20be7c 508def start(bot, user, chan, realtarget, *args):
f5aec865 509 if chan is not None: replyto = chan
c695f740 510 else: replyto = user
511
77a265cd 512 if chan is not None and chan.name != state.db['chan']:
513 bot.msg(replyto, "That command isn't valid here.")
514 return
515
442ed923 516 if state.curq is None and state.pointvote is None and state.nextquestiontimer is None:
77a265cd 517 bot.msg(state.db['chan'], "%s has started the game!" % (user))
442ed923 518 state.nextquestion(skipwait=True)
c53f6514 519 elif state.pointvote is not None:
00ccae72 520 bot.msg(user, "There's a vote in progress!")
c695f740 521 else:
00ccae72 522 bot.msg(user, "Game is already started!")
c695f740 523
9306587e 524@lib.hook('stop', glevel=1, needchan=False)
5f03d045 525@lib.help(None, "stops the trivia game")
c695f740 526def cmd_stop(bot, user, chan, realtarget, *args):
fadbf980 527 if stop():
528 bot.msg(state.chan, "Game stopped by %s" % (user))
529 else:
530 bot.msg(user, "Game isn't running.")
c695f740 531
fadbf980 532def stop():
3b89ebff 533 state.curq = None
534 state.nextq = None
09566235 535 try:
536 state.steptimer.cancel()
537 except Exception as e:
a28e2ae9 538 print("!!! steptimer.cancel(): %s %r" % (e,e))
3b89ebff 539 state.steptimer = None
09566235 540 try:
541 state.nextquestiontimer.cancel()
542 except Exception as e:
a28e2ae9 543 print("!!! nextquestiontimer.cancel(): %s %r" % (e,e))
3b89ebff 544 state.nextquestiontimer = None
545 return True
80d02bd8 546
fb20be7c 547@lib.hook(needchan=False)
5f03d045 548@lib.help("<reason>", "reports a bad question to the admins")
7b832b55 549@lib.argsGE(1)
fb20be7c 550def badq(bot, user, chan, realtarget, *args):
7b832b55 551 lastqid = state.lastqid
552 curqid = state.curqid
553
554 reason = ' '.join(args)
8ad3a154 555 state.db['badqs'].append([state.db['category'], lastqid, curqid, reason])
7b832b55 556 bot.msg(user, "Reported bad question.")
2520caee 557
fb20be7c 558@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 559@lib.help(None, "shows a list of BADQ reports")
fb20be7c 560def badqs(bot, user, chan, realtarget, *args):
2520caee 561 if len(state.db['badqs']) == 0:
562 bot.msg(user, "No reports.")
563
564 for i in range(len(state.db['badqs'])):
565 try:
566 report = state.db['badqs'][i]
8ad3a154 567 bot.msg(user, "Report #%d: Cat=%s LastQ=%r CurQ=%r: %s" % (i, report[0], report[1], report[2], report[3]))
568 try: lq = state.db['questions'][report[0]][int(report[1])]
7b832b55 569 except Exception as e: lq = (None,None)
8ad3a154 570 try: cq = state.db['questions'][report[0]][int(report[2])]
7b832b55 571 except Exception as e: cq = (None, None)
572 bot.msg(user, "- Last: %s*%s" % (lq[0], lq[1]))
573 bot.msg(user, "- Curr: %s*%s" % (cq[0], cq[1]))
2520caee 574 except Exception as e:
575 bot.msg(user, "- Exception: %r" % (e))
576
fb20be7c 577@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 578@lib.hook(None, "clears list of BADQ reports")
fb20be7c 579def clearbadqs(bot, user, chan, realtarget, *args):
2520caee 580 state.db['badqs'] = []
581 bot.msg(user, "Cleared reports.")
582
fb20be7c 583@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 584@lib.hook("<badqid>", "removes a BADQ report")
2520caee 585@lib.argsEQ(1)
fb20be7c 586def delbadq(bot, user, chan, realtarget, *args):
4d98501a 587 try:
588 qid = int(args[0])
589 del state.db['badqs'][qid]
4d98501a 590 bot.msg(user, "Removed report #%d" % (qid))
591 except:
592 bot.msg(user, "Failed!")
2520caee 593
f5aec865 594@lib.hook(needchan=False, wantchan=True)
5f03d045 595@lib.help("[<user>]", "shows you or someone else's rank")
fb20be7c 596def rank(bot, user, chan, realtarget, *args):
f5aec865 597 if chan is not None: replyto = chan
80d02bd8 598 else: replyto = user
599
c695f740 600 if len(args) != 0: who = args[0]
601 else: who = user
602
af349654 603 bot.msg(replyto, "%s is in %d place (%s points). Target is: %s %s" % (who, state.rank(who), state.points(who), state.targetuser(who), state.targetpoints(who)))
fadbf980 604
fb20be7c 605@lib.hook(needchan=False)
5f03d045 606@lib.help(None, "shows top10 list")
fb20be7c 607def top10(bot, user, chan, realtarget, *args):
77c61775 608 if len(state.db['ranks']) == 0:
609 return bot.msg(state.db['chan'], "No one is ranked!")
fadbf980 610
8ef938d0 611 max = len(state.db['ranks'])
612 if max > 10:
613 max = 10
2bb267e0 614 replylist = ', '.join(["%s (%s) %s" % (person(x), country(x), pts(x)) for x in range(max)])
bcb6dc21 615 bot.msg(state.db['chan'], "Game is to %s! Top 10: %s" % (state.db['target'], replylist))
77c61775 616
fb20be7c 617@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 618@lib.help("<target score>", "changes the target score for this round")
fb20be7c 619def settarget(bot, user, chan, realtarget, *args):
77c61775 620 try:
621 state.db['target'] = int(args[0])
622 bot.msg(state.db['chan'], "Target has been changed to %s points!" % (state.db['target']))
38b29993 623
7bd5e7d5 624 if state.pointvote is not None:
625 state.pointvote.cancel()
626 state.pointvote = None
38b29993 627 bot.msg(state.db['chan'], "Vote has been cancelled!")
7bd5e7d5 628 except Exception as e:
a28e2ae9 629 print(e)
77c61775 630 bot.msg(user, "Failed to set target.")
631
fb20be7c 632@lib.hook(needchan=False)
5f03d045 633@lib.help("<option>", "votes for a trarget score for next round")
fb20be7c 634def vote(bot, user, chan, realtarget, *args):
7bd5e7d5 635 if state.pointvote is not None:
38b29993 636 if int(args[0]) in state.voteamounts:
637 state.voteamounts[int(args[0])] += 1
638 bot.msg(user, "Your vote has been recorded.")
639 else:
640 bot.msg(user, "Sorry - that's not an option!")
641 else:
642 bot.msg(user, "There's no vote in progress.")
643
fb20be7c 644@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 645@lib.help("<number>", "sets the max missed question before game stops")
fb20be7c 646def maxmissed(bot, user, chan, realtarget, *args):
c4763e66 647 try:
648 state.db['maxmissedquestions'] = int(args[0])
649 bot.msg(state.db['chan'], "Max missed questions before round ends has been changed to %s." % (state.db['maxmissedquestions']))
650 except:
651 bot.msg(user, "Failed to set maxmissed.")
652
fb20be7c 653@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 654@lib.help("<seconds>", "sets the time between hints")
fb20be7c 655def hinttimer(bot, user, chan, realtarget, *args):
c4763e66 656 try:
657 state.db['hinttimer'] = float(args[0])
658 bot.msg(state.db['chan'], "Time between hints has been changed to %s." % (state.db['hinttimer']))
659 except:
660 bot.msg(user, "Failed to set hint timer.")
661
fb20be7c 662@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 663@lib.help("<number>", "sets the number of hints given")
fb20be7c 664def hintnum(bot, user, chan, realtarget, *args):
c4763e66 665 try:
666 state.db['hintnum'] = int(args[0])
667 bot.msg(state.db['chan'], "Max number of hints has been changed to %s." % (state.db['hintnum']))
668 except:
669 bot.msg(user, "Failed to set hintnum.")
670
fb20be7c 671@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 672@lib.help("<seconds>", "sets the pause between questions")
fb20be7c 673def questionpause(bot, user, chan, realtarget, *args):
442ed923 674 try:
675 state.db['questionpause'] = float(args[0])
676 bot.msg(state.db['chan'], "Pause between questions has been changed to %s." % (state.db['questionpause']))
677 except:
678 bot.msg(user, "Failed to set questionpause.")
679
fb20be7c 680@lib.hook(glevel=1, needchan=False)
8e76c9bb 681@lib.help("[@category] <full question>", "finds a qid given a complete question")
682@lib.argsGE(1)
fb20be7c 683def findq(bot, user, chan, realtarget, *args):
8ad3a154 684 args = list(args)
fd07173d 685 if args[0].startswith("@"):
8ad3a154 686 cat = args.pop(0)[1:].lower()
687 questions = state.db['questions'][cat]
688 else:
689 questions = state.questions
690
4d98501a 691 if len(args) == 0:
692 bot.msg(user, "You need to specify the question.")
693 return
694
695 searchkey = ' '.join(args).lower()
8ad3a154 696 matches = [str(i) for i in range(len(questions)) if questions[i][0].lower() == searchkey]
4d98501a 697 if len(matches) > 1:
698 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
699 elif len(matches) == 1:
700 bot.msg(user, "One match: %s" % (matches[0]))
701 else:
702 bot.msg(user, "No match.")
703
704@lib.hook(glevel=1, needchan=False)
8ad3a154 705@lib.help("[@<category>] <regex>", "finds a qid given a regex or partial question")
8e76c9bb 706@lib.argsGE(1)
4d98501a 707def findqre(bot, user, chan, realtarget, *args):
8ad3a154 708 args = list(args)
fd07173d 709 if args[0].startswith("@"):
8ad3a154 710 cat = args.pop(0)[1:].lower()
711 questions = state.db['questions'][cat]
712 else:
713 questions = state.questions
714
bf8676ae 715 if len(args) == 0:
716 bot.msg(user, "You need to specify a search string.")
717 return
718
4d98501a 719 searcher = re.compile(' '.join(args), re.IGNORECASE)
8ad3a154 720 matches = [str(i) for i in range(len(questions)) if searcher.search(questions[i][0]) is not None]
bf8676ae 721 if len(matches) > 25:
722 bot.msg(user, "Too many matches! (>25)")
723 elif len(matches) > 1:
c4763e66 724 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
725 elif len(matches) == 1:
726 bot.msg(user, "One match: %s" % (matches[0]))
727 else:
728 bot.msg(user, "No match.")
729
b9daa51a 730@lib.hook(glevel=lib.STAFF, needchan=False)
8ad3a154 731@lib.help("[@<category>] <qid>", "displays the q*a for a qid", "category defaults to current")
b9daa51a 732def showq(bot, user, chan, realtarget, *args):
8ad3a154 733 args = list(args)
fd07173d 734 if args[0].startswith("@"):
8ad3a154 735 cat = args.pop(0)[1:].lower()
736 questions = state.db['questions'][cat]
737 else:
738 questions = state.questions
739
b9daa51a 740 try:
741 qid = int(args[0])
742 except:
743 bot.msg(user, "Specify a numeric question ID.")
744 return
745 try:
8ad3a154 746 q = questions[qid]
b9daa51a 747 except:
748 bot.msg(user, "ID not valid.")
749 return
750 bot.msg(user, "%s: %s*%s" % (qid, q[0], q[1]))
751
fb20be7c 752@lib.hook(('delq', 'deleteq'), glevel=lib.STAFF, needchan=False)
8ad3a154 753@lib.help("[@<category>] <qid>", "removes a question from the database")
fb20be7c 754def delq(bot, user, chan, realtarget, *args):
8ad3a154 755 args = list(args)
fd07173d 756 if args[0].startswith("@"):
8ad3a154 757 cat = args.pop(0)[1:].lower()
758 questions = state.db['questions'][cat]
759 else:
760 questions = state.questions
761
c4763e66 762 try:
8ad3a154 763 backup = questions[int(args[0])]
764 del questions[int(args[0])]
ebee6edb 765 bot.msg(user, "Deleted %s*%s" % (backup[0], backup[1]))
c4763e66 766 except:
b9daa51a 767 bot.msg(user, "Couldn't delete that question. %r" % (e))
c4763e66 768
fb20be7c 769@lib.hook(glevel=lib.STAFF, needchan=False)
8ad3a154 770@lib.help("[@<category>] <q>*<a>", "adds a question")
fb20be7c 771def addq(bot, user, chan, realtarget, *args):
8ad3a154 772 args = list(args)
fd07173d 773 if args[0].startswith("@"):
8ad3a154 774 cat = args.pop(0)[1:].lower()
775 questions = state.db['questions'][cat]
776 else:
777 questions = state.questions
778
c4763e66 779 line = ' '.join([str(arg) for arg in args])
aa0e4be4 780 linepieces = line.split('*', 1)
c4763e66 781 if len(linepieces) < 2:
782 bot.msg(user, "Error: need <question>*<answer>")
783 return
784 question = linepieces[0].strip()
785 answer = linepieces[1].strip()
8ad3a154 786 questions.append([question, answer])
787 bot.msg(user, "Done. Question is #%s" % (len(questions)-1))
c4763e66 788
8770f6ef 789@lib.hook(needchan=False)
790@lib.help(None, "show current category")
791def showcat(bot, user, chan, realtarget, *args):
792 bot.msg(user, "Current category: %s" % (state.db['category']))
793
8ad3a154 794@lib.hook(glevel=1, needchan=False)
795@lib.help("<category>", "change category")
796def setcat(bot, user, chan, realtarget, *args):
797 category = args[0].lower()
798 if category in state.db['questions']:
799 state.db['category'] = category
800 state.questions = state.db['questions'][category]
801 bot.msg(user, "Changed category to %s" % (category))
802 else:
803 bot.msg(user, "That category doesn't exist.")
804
805@lib.hook(needchan=False)
8770f6ef 806@lib.help(None, "list categories", "the current category will be marked with a *")
8ad3a154 807def listcats(bot, user, chan, realtarget, *args):
8770f6ef 808 cats = ["%s%s (%d)" % ("*" if c == state.db['category'] else "", c, len(state.db['questions'][c])) for c in state.db['questions'].keys()]
8ad3a154 809 bot.msg(user, "Categories: %s" % (', '.join(cats)))
810
811@lib.hook(glevel=lib.STAFF, needchan=False)
812@lib.help("<category>", "adds an empty category")
813def addcat(bot, user, chan, realtarget, *args):
814 category = args[0].lower()
815 if category not in state.db['questions']:
816 state.db['questions'][category] = []
817 bot.msg(user, "Added category %s" % (category))
818 else:
819 bot.msg(user, "Category already exists.")
820
821@lib.hook(glevel=lib.MANAGER, needchan=False)
822@lib.help("<category>", "deletes an entire category")
823def delcat(bot, user, chan, realtarget, *args):
824 category = args[0].lower()
825 if category == state.db['category']:
826 bot.msg(user, "Category currently in use!")
827 elif category in state.db['questions']:
828 length = len(state.db['questions'][category])
829 del state.db['questions'][category]
830 bot.msg(user, "Deleted category %s (%d questions)" % (category, length))
831 else:
832 bot.msg(user, "Category does not exist.")
c4763e66 833
fb20be7c 834@lib.hook(needchan=False)
835def triviahelp(bot, user, chan, realtarget, *args):
2bb267e0 836 bot.slowmsg(user, "START")
837 bot.slowmsg(user, "TOP10")
838 bot.slowmsg(user, "POINTS [<user>]")
839 bot.slowmsg(user, "RANK [<user>]")
840 bot.slowmsg(user, "BADQ <reason> (include info to identify question)")
9306587e 841 if user.glevel >= 1:
b9daa51a 842 bot.slowmsg(user, "SKIP (KNOWN)")
843 bot.slowmsg(user, "STOP (KNOWN)")
4d98501a 844 bot.slowmsg(user, "FINDQ <full question> (KNOWN)")
845 bot.slowmsg(user, "FINDQRE <regex> (KNOWN)")
b9daa51a 846 bot.slowmsg(user, "SETNEXTID <qid> (KNOWN)")
9306587e 847 if user.glevel >= lib.STAFF:
b9daa51a 848 bot.slowmsg(user, "GIVE <user> [<points>] (STAFF)")
849 bot.slowmsg(user, "SETNEXT <q>*<a> (STAFF)")
850 bot.slowmsg(user, "ADDQ <q>*<a> (STAFF)")
851 bot.slowmsg(user, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
852 bot.slowmsg(user, "SHOWQ <qid> (STAFF)")
853 bot.slowmsg(user, "BADQS (STAFF)")
854 bot.slowmsg(user, "CLEARBADQS (STAFF)")
855 bot.slowmsg(user, "DELBADQ <reportid> (STAFF)")
9306587e 856 if user.glevel >= lib.ADMIN:
b9daa51a 857 bot.slowmsg(user, "SETTARGET <points> (ADMIN)")
858 bot.slowmsg(user, "MAXMISSED <questions> (ADMIN)")
859 bot.slowmsg(user, "HINTTIMER <float seconds> (ADMIN)")
860 bot.slowmsg(user, "HINTNUM <hints> (ADMIN)")
861 bot.slowmsg(user, "QUESTIONPAUSE <float seconds> (ADMIN)")
b5c89dfb 862
a46e5e4d 863@lib.hooknum(332) # topic is...
864@lib.hooknum(331) # no topic set
f8cc0124 865def num_TOPIC(bot, textline):
866 pieces = textline.split(None, 4)
867 chan = pieces[3]
868 if chan != state.db['chan']:
869 return
870 gottopic = pieces[4][1:]
871
872 formatted = state.db['topicformat'] % {
873 'chan': state.db['chan'],
8ef938d0 874 'top1': "%s (%s)" % (person(0), pts(0)),
875 'top3': '/'.join([
876 "%s (%s)" % (person(x), pts(x))
877 for x in range(3) if x < len(state.db['ranks'])
878 ]),
e227969c 879 'top3c': ', '.join([
880 "%s (%s) %s" % (person(x), country(x), pts(x))
8ef938d0 881 for x in range(3) if x < len(state.db['ranks'])
882 ]),
883 'top10': ' '.join([
884 "%s (%s)" % (person(x), pts(x))
885 for x in range(10) if x < len(state.db['ranks'])
886 ]),
887 'top10c': ' '.join([
888 "%s (%s, %s)" % (person(x), pts(x), country(x))
889 for x in range(10) if x < len(state.db['ranks'])
890 ]),
5f42c250 891 'lastwinner': state.db['lastwinner'],
892 'lastwon': time.strftime("%b %d", time.gmtime(state.db['lastwon'])),
f8cc0124 893 'target': state.db['target'],
8770f6ef 894 'category': state.db['category'],
f8cc0124 895 }
896 if gottopic != formatted:
a46e5e4d 897 state.getbot().conn.send(bot.parent.cfg.get('trivia', 'topiccommand', default="TOPIC %(chan)s :%(topic)s") % {'chan': state.db['chan'], 'topic': formatted})
f8cc0124 898
b5c89dfb 899
900def specialQuestion(oldq):
ebee6edb 901 newq = [oldq[0], oldq[1]]
902 qtype = oldq[0].upper()
b5c89dfb 903
904 if qtype == "!MONTH":
ebee6edb 905 newq[0] = "What month is it currently (in UTC)?"
906 newq[1] = time.strftime("%B", time.gmtime()).lower()
b5c89dfb 907 elif qtype == "!MATH+":
5ed70e94 908 try:
909 maxnum = int(oldq[1])
910 except ValueError:
911 maxnum = 10
912 randnum1 = random.randrange(0, maxnum+1)
913 randnum2 = random.randrange(0, maxnum+1)
ebee6edb 914 newq[0] = "What is %d + %d?" % (randnum1, randnum2)
915 newq[1] = spellout(randnum1+randnum2)
5ed70e94 916 elif qtype == "!ALGEBRA+":
917 try:
918 num1, num2 = [int(i) for i in oldq[1].split('!')]
919 except ValueError:
920 num1, num2 = 10, 10
921 randnum1 = random.randrange(0, num1+1)
922 randnum2 = random.randrange(randnum1, num2+1)
923 newq[0] = "What is x? %d = %d + x" % (randnum2, randnum1)
924 newq[1] = spellout(randnum2-randnum1)
e227969c 925 else: pass #default to not modifying
b5c89dfb 926 return newq
927
928def spellout(num):
5ed70e94 929 ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
930 teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
931 tens = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
932
933 if num == 0:
934 return 'zero'
935
936 ihundreds = num / 100
937 itens = num % 100 / 10
938 iones = num % 10
939 buf = []
940
941 if ihundreds > 0:
942 buf.append("%s hundred" % (ones[ihundreds]))
943 if itens > 1:
944 buf.append(tens[itens])
945 if itens == 1:
946 buf.append(teens[iones])
947 elif iones > 0:
948 buf.append(ones[iones])
949 return ' '.join(buf)
950# return [
951# "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
952# "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
953# "sixteen", "seventeen", "eighteen", "nineteen", "twenty"
954# ][num]