]> jfr.im git - erebus.git/blame - modules/trivia.py
code style and minor bug fixes
[erebus.git] / modules / trivia.py
CommitLineData
80d02bd8 1# Erebus IRC bot - Author: Erebus Team
c695f740 2# trivia module
80d02bd8 3# This file is released into the public domain; see http://unlicense.org/
4
5# module info
6modinfo = {
7 'author': 'Erebus Team',
8 'license': 'public domain',
9 'compatible': [1], # compatible module API versions
fb20be7c 10 'depends': ['userinfo'], # other modules required to work properly?
80d02bd8 11}
12
13# preamble
14import modlib
15lib = modlib.modlib(__name__)
16def modstart(parent, *args, **kwargs):
5871567f 17 state.gotParent(parent)
18 lib.hookchan(state.db['chan'])(trivia_checkanswer) # we need parent for this. so it goes here.
80d02bd8 19 return lib.modstart(parent, *args, **kwargs)
20def modstop(*args, **kwargs):
c0eee1b4 21 global state
8ef938d0 22 try:
23 stop()
24 state.closeshop()
25 del state
26 except Exception: pass
80d02bd8 27 return lib.modstop(*args, **kwargs)
28
29# module code
7bd5e7d5 30import json, random, threading, re, time, datetime
b16b8c05 31
c0eee1b4 32try:
c53f6514 33 import twitter
34except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
c0eee1b4 35
b16b8c05 36def findnth(haystack, needle, n): #http://stackoverflow.com/a/1884151
37 parts = haystack.split(needle, n+1)
38 if len(parts)<=n+1:
39 return -1
40 return len(haystack)-len(parts[-1])-len(needle)
80d02bd8 41
8ef938d0 42def person(num): return state.db['users'][state.db['ranks'][num]]['realnick']
43def pts(num): return str(state.db['users'][state.db['ranks'][num]]['points'])
fb20be7c 44def country(num, default="??"): return lib.mod('userinfo')._get(person(num), 'country', default=default)
8ef938d0 45
80d02bd8 46class TriviaState(object):
5871567f 47 def __init__(self, parent=None, pointvote=False):
48 if parent is not None:
49 self.gotParent(parent, pointvote)
50
51 def gotParent(self, parent, pointvote=False):
bf8676ae 52 self.parent = parent
53 self.questionfile = self.parent.cfg.get('trivia', 'jsonpath', default="./modules/trivia.json")
54 self.db = json.load(open(self.questionfile, "r"))
55 self.chan = self.db['chan']
56 self.curq = None
57 self.nextq = None
58 self.nextquestiontimer = None
59 self.steptimer = None
60 self.hintstr = None
61 self.hintanswer = None
62 self.hintsgiven = 0
b16b8c05 63 self.revealpossibilities = None
bf8676ae 64 self.gameover = False
65 self.missedquestions = 0
66 self.curqid = None
67 self.lastqid = None
80d02bd8 68
7bd5e7d5 69 if 'starttime' not in self.db or self.db['starttime'] is None:
70 self.db['starttime'] = time.time()
71
c53f6514 72 if pointvote:
73 self.getchan().msg("Vote for the next round target points! Options: %s. Vote using !vote <choice>" % (', '.join([str(x) for x in self.db['targetoptions']])))
74 self.getchan().msg("You have %s seconds." % (self.db['votetimer']))
75 self.voteamounts = dict([(x, 0) for x in self.db['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
76 self.pointvote = threading.Timer(self.db['votetimer'], self.endPointVote)
77 self.pointvote.start()
78 else:
79 self.pointvote = None
80
80d02bd8 81 def __del__(self):
77c61775 82 self.closeshop()
83 def closeshop(self):
442ed923 84 if threading is not None and threading._Timer is not None:
85 if isinstance(self.steptimer, threading._Timer):
86 self.steptimer.cancel()
87 if isinstance(self.nextquestiontimer, threading._Timer):
88 self.nextquestiontimer.cancel()
89 self.nextquestiontimer = None
c695f740 90 if json is not None and json.dump is not None:
6374d61f 91 json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
80d02bd8 92
fadbf980 93 def getchan(self):
94 return self.parent.channel(self.chan)
95 def getbot(self):
96 return self.getchan().bot
97
b16b8c05 98 def nexthint(self, hintnum):
b16b8c05 99 answer = self.hintanswer
100
b5c89dfb 101 if self.hintstr is None or self.revealpossibilities is None or self.reveal is None:
b16b8c05 102 self.hintstr = list(re.sub(r'[a-zA-Z0-9]', '*', answer))
103 self.revealpossibilities = range(''.join(self.hintstr).count('*'))
b5c89dfb 104 self.reveal = int(''.join(self.hintstr).count('*') * (7/24.0))
b16b8c05 105
b5c89dfb 106 for i in range(self.reveal):
b16b8c05 107 revealcount = random.choice(self.revealpossibilities)
108 revealloc = findnth(''.join(self.hintstr), '*', revealcount)
109 self.revealpossibilities.remove(revealcount)
110 self.hintstr[revealloc] = answer[revealloc]
6374d61f 111 self.parent.channel(self.chan).bot.msg(self.chan, "\00304,01Here's a hint: %s" % (''.join(self.hintstr)))
b16b8c05 112
77c61775 113 self.hintsgiven += 1
114
c4763e66 115 if hintnum < self.db['hintnum']:
116 self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[hintnum+1])
b16b8c05 117 self.steptimer.start()
118 else:
c4763e66 119 self.steptimer = threading.Timer(self.db['hinttimer'], self.nextquestion, args=[True])
b16b8c05 120 self.steptimer.start()
121
77c61775 122 def doGameOver(self):
7bd5e7d5 123 msg = self.getchan().msg
c0eee1b4 124 winner = person(0)
77c61775 125 try:
126 msg("\00312THE GAME IS OVER!!!")
127 msg("THE WINNER IS: %s (%s)" % (person(0), pts(0)))
128 msg("2ND PLACE: %s (%s)" % (person(1), pts(1)))
129 msg("3RD PLACE: %s (%s)" % (person(2), pts(2)))
130 [msg("%dth place: %s (%s)" % (i+1, person(i), pts(i))) for i in range(3,10)]
131 except IndexError: pass
c0eee1b4 132 except Exception as e: msg("DERP! %r" % (e))
133
7bd5e7d5 134 if self.db['hofpath'] is not None and self.db['hofpath'] != '':
135 self.writeHof()
136
77c61775 137 self.db['users'] = {}
138 self.db['ranks'] = []
139 stop()
140 self.closeshop()
c0eee1b4 141
c53f6514 142 try:
c0eee1b4 143 t = twitter.Twitter(auth=twitter.OAuth(self.getbot().parent.cfg.get('trivia', 'token'),
144 self.getbot().parent.cfg.get('trivia', 'token_sec'),
145 self.getbot().parent.cfg.get('trivia', 'con'),
146 self.getbot().parent.cfg.get('trivia', 'con_sec')))
147 t.statuses.update(status="Round is over! The winner was %s" % (winner))
c53f6514 148 except: pass #don't care if errors happen updating twitter.
149
5871567f 150 self.__init__(self.parent, True)
c53f6514 151
7bd5e7d5 152 def writeHof(self):
153 def person(num):
154 try: return self.db['users'][self.db['ranks'][num]]['realnick']
155 except: return "none"
156 def pts(num):
157 try: return str(self.db['users'][self.db['ranks'][num]]['points'])
158 except: return 0
159
160 try:
161 f = open(self.db['hofpath'], 'rb+')
162 for i in range(self.db['hoflines']): #skip this many lines
163 f.readline()
164 insertpos = f.tell()
165 fcontents = f.read()
166 f.seek(insertpos)
167 f.write((self.db['hofformat']+"\n") % {
168 'date': time.strftime("%F", time.gmtime()),
169 'duration': str(datetime.timedelta(seconds=time.time()-self.db['starttime'])),
170 'targetscore': self.db['target'],
171 'firstperson': person(0),
172 'firstscore': pts(0),
173 'secondperson': person(1),
174 'secondscore': pts(1),
175 'thirdperson': person(2),
176 'thirdscore': pts(2),
177 })
178 f.write(fcontents)
179 return True
180 except Exception as e:
181 raise e
182 return False
183 finally:
184 f.close()
185
c53f6514 186 def endPointVote(self):
187 self.getchan().msg("Voting has ended!")
188 votelist = sorted(self.voteamounts.items(), key=lambda item: item[1]) #sort into list of tuples: [(option, number_of_votes), ...]
189 for i in range(len(votelist)-1):
190 item = votelist[i]
191 self.getchan().msg("%s place: %s (%s votes)" % (len(votelist)-i, item[0], item[1]))
192 self.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist[-1][0], votelist[-1][1]))
c0eee1b4 193
c53f6514 194 self.db['target'] = votelist[-1][0]
195 self.pointvote = None
77c61775 196
38b29993 197 self.nextquestion() #start the game!
198
442ed923 199 def nextquestion(self, qskipped=False, iteration=0, skipwait=False):
7b832b55 200 self.lastqid = self.curqid
6bdfec48 201 self.curq = None
7b832b55 202 self.curqid = None
77c61775 203 if self.gameover == True:
204 return self.doGameOver()
fadbf980 205 if qskipped:
c53f6514 206 self.getchan().msg("\00304Fail! The correct answer was: %s" % (self.hintanswer))
c0eee1b4 207 self.missedquestions += 1
208 else:
209 self.missedquestions = 0
f8cc0124 210 if 'topicformat' in self.db and self.db['topicformat'] is not None:
211 self.getbot().conn.send("TOPIC %s" % (self.db['chan']))
fadbf980 212
b16b8c05 213 if isinstance(self.steptimer, threading._Timer):
214 self.steptimer.cancel()
442ed923 215 if isinstance(self.nextquestiontimer, threading._Timer):
216 self.nextquestiontimer.cancel()
217 self.nextquestiontimer = None
c0eee1b4 218
b16b8c05 219 self.hintstr = None
77c61775 220 self.hintsgiven = 0
b16b8c05 221 self.revealpossibilities = None
b5c89dfb 222 self.reveal = None
b16b8c05 223
c4763e66 224 if self.missedquestions > self.db['maxmissedquestions']:
c0eee1b4 225 stop()
ce03ceda 226 self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game." % (self.missedquestions))
227 return
b16b8c05 228
442ed923 229 if skipwait:
6bdfec48 230 self._nextquestion(iteration)
442ed923 231 else:
6bdfec48 232 self.nextquestiontimer = threading.Timer(self.db['questionpause'], self._nextquestion, args=[iteration])
442ed923 233 self.nextquestiontimer.start()
234
6bdfec48 235 def _nextquestion(self, iteration):
e5a3970b 236 if self.nextq is not None:
2520caee 237 nextqid = None
e5a3970b 238 nextq = self.nextq
239 self.nextq = None
c695f740 240 else:
2520caee 241 nextqid = random.randrange(0, len(self.db['questions']))
242 nextq = self.db['questions'][nextqid]
b5c89dfb 243
ebee6edb 244 if nextq[0][0] == "!":
2520caee 245 nextqid = None
b5c89dfb 246 nextq = specialQuestion(nextq)
247
ebee6edb 248 if len(nextq) > 2 and nextq[2] - time.time() < 7*24*60*60 and iteration < 10:
442ed923 249 return self._nextquestion(iteration=iteration+1) #short-circuit to pick another question
ebee6edb 250 if len(nextq) > 2:
251 nextq[2] = time.time()
252 else:
253 nextq.append(time.time())
b5c89dfb 254
ebee6edb 255 nextq[1] = nextq[1].lower()
c695f740 256
6374d61f 257 qtext = "\00304,01Next up: "
bf8676ae 258 qtext += "(%5d)" % (random.randint(0,99999))
ebee6edb 259 qary = nextq[0].split(None)
71e0b5fb 260 qtext += " "
c695f740 261 for qword in qary:
6374d61f 262 qtext += "\00304,01"+qword+"\00301,01"+chr(random.randrange(0x61,0x7A)) #a-z
fadbf980 263 self.getbot().msg(self.chan, qtext)
80d02bd8 264
b5c89dfb 265 self.curq = nextq
7b832b55 266 self.curqid = nextqid
b5c89dfb 267
ebee6edb 268 if isinstance(self.curq[1], basestring): self.hintanswer = self.curq[1]
269 else: self.hintanswer = random.choice(self.curq[1])
c0eee1b4 270
c4763e66 271 self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[1])
b16b8c05 272 self.steptimer.start()
273
80d02bd8 274 def checkanswer(self, answer):
9557ee54 275 if self.curq is None:
276 return False
ebee6edb 277 elif isinstance(self.curq[1], basestring):
278 return answer.lower() == self.curq[1]
80d02bd8 279 else: # assume it's a list or something.
ebee6edb 280 return answer.lower() in self.curq[1]
77c61775 281
c53f6514 282 def addpoint(self, user_obj, count=1):
283 user_nick = str(user_obj)
284 user = user_nick.lower() # save this separately as we use both
80d02bd8 285 if user in self.db['users']:
286 self.db['users'][user]['points'] += count
287 else:
c53f6514 288 self.db['users'][user] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
9557ee54 289 self.db['ranks'].append(user)
80d02bd8 290
e5a3970b 291 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 292 for i in range(0, len(self.db['ranks'])):
293 nick = self.db['ranks'][i]
294 self.db['users'][nick]['rank'] = i
77c61775 295
e5a3970b 296 if self.db['users'][user]['points'] >= self.db['target']:
77c61775 297 self.gameover = True
298
80d02bd8 299 return self.db['users'][user]['points']
300
301 def points(self, user):
9557ee54 302 user = str(user).lower()
80d02bd8 303 if user in self.db['users']:
304 return self.db['users'][user]['points']
305 else:
306 return 0
307
308 def rank(self, user):
c695f740 309 user = str(user).lower()
fadbf980 310 if user in self.db['users']:
311 return self.db['users'][user]['rank']+1
312 else:
313 return len(self.db['users'])+1
77c61775 314
c695f740 315 def targetuser(self, user):
77c61775 316 if len(self.db['ranks']) == 0: return "no one is ranked!"
317
c695f740 318 user = str(user).lower()
fadbf980 319 if user in self.db['users']:
320 rank = self.db['users'][user]['rank']
321 if rank == 0:
322 return "you're in the lead!"
323 else:
324 return self.db['ranks'][rank-1]
c695f740 325 else:
fadbf980 326 return self.db['ranks'][-1]
c695f740 327 def targetpoints(self, user):
77c61775 328 if len(self.db['ranks']) == 0: return 0
329
c695f740 330 user = str(user).lower()
fadbf980 331 if user in self.db['users']:
332 rank = self.db['users'][user]['rank']
333 if rank == 0:
334 return "N/A"
335 else:
336 return self.db['users'][self.db['ranks'][rank-1]]['points']
c695f740 337 else:
fadbf980 338 return self.db['users'][self.db['ranks'][-1]]['points']
80d02bd8 339
5871567f 340state = TriviaState()
9557ee54 341
5871567f 342# we have to hook this in modstart, since we don't know the channel until then.
80d02bd8 343def trivia_checkanswer(bot, user, chan, *args):
80d02bd8 344 line = ' '.join([str(arg) for arg in args])
345 if state.checkanswer(line):
6bdfec48 346 state.curq = None
6374d61f 347 bot.msg(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)))
77c61775 348 if state.hintsgiven == 0:
6374d61f 349 bot.msg(chan, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user)))
9557ee54 350 state.nextquestion()
80d02bd8 351
fb20be7c 352@lib.hook(needchan=False)
353def points(bot, user, chan, realtarget, *args):
6bdfec48 354 if chan is not None and realtarget == chan.name: replyto = chan
80d02bd8 355 else: replyto = user
356
357 if len(args) != 0: who = args[0]
358 else: who = user
359
360 bot.msg(replyto, "%s has %d points." % (who, state.points(who)))
361
fb20be7c 362@lib.hook(glevel=lib.STAFF, needchan=False)
80d02bd8 363@lib.argsGE(1)
fb20be7c 364def give(bot, user, chan, realtarget, *args):
80d02bd8 365 whoto = args[0]
c695f740 366 if len(args) > 1:
367 numpoints = int(args[1])
368 else:
369 numpoints = 1
370 balance = state.addpoint(whoto, numpoints)
fadbf980 371
c695f740 372 bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance))
373
fb20be7c 374@lib.hook(glevel=1, needchan=False)
375def setnextid(bot, user, chan, realtarget, *args):
9306587e 376 try:
377 qid = int(args[0])
378 state.nextq = state.db['questions'][qid]
71e0b5fb 379 if user.glevel >= lib.STAFF:
380 respstr = "Done. Next question is: %s" % (state.nextq[0])
381 else:
382 respstr = "Done."
383 bot.msg(user, respstr)
9306587e 384 except Exception as e:
385 bot.msg(user, "Error: %s" % (e))
386
fb20be7c 387@lib.hook(glevel=lib.STAFF, needchan=False)
c695f740 388@lib.argsGE(1)
fb20be7c 389def setnext(bot, user, chan, realtarget, *args):
c695f740 390 line = ' '.join([str(arg) for arg in args])
391 linepieces = line.split('*')
b5c89dfb 392 if len(linepieces) < 2:
393 bot.msg(user, "Error: need <question>*<answer>")
394 return
c695f740 395 question = linepieces[0].strip()
396 answer = linepieces[1].strip()
ebee6edb 397 state.nextq = [question, answer]
c695f740 398 bot.msg(user, "Done.")
399
fb20be7c 400@lib.hook(glevel=1, needchan=False)
401def skip(bot, user, chan, realtarget, *args):
442ed923 402 state.nextquestion(qskipped=True, skipwait=True)
c695f740 403
fb20be7c 404@lib.hook(needchan=False)
405def start(bot, user, chan, realtarget, *args):
6bdfec48 406 if chan is not None and realtarget == chan.name: replyto = chan
c695f740 407 else: replyto = user
408
77a265cd 409 if chan is not None and chan.name != state.db['chan']:
410 bot.msg(replyto, "That command isn't valid here.")
411 return
412
442ed923 413 if state.curq is None and state.pointvote is None and state.nextquestiontimer is None:
77a265cd 414 bot.msg(state.db['chan'], "%s has started the game!" % (user))
442ed923 415 state.nextquestion(skipwait=True)
c53f6514 416 elif state.pointvote is not None:
417 bot.msg(replyto, "There's a vote in progress!")
c695f740 418 else:
419 bot.msg(replyto, "Game is already started!")
420
9306587e 421@lib.hook('stop', glevel=1, needchan=False)
c695f740 422def cmd_stop(bot, user, chan, realtarget, *args):
fadbf980 423 if stop():
424 bot.msg(state.chan, "Game stopped by %s" % (user))
425 else:
426 bot.msg(user, "Game isn't running.")
c695f740 427
fadbf980 428def stop():
9306587e 429 try:
ce03ceda 430 if state.curq is not None or state.nextq is not None:
9306587e 431 state.curq = None
ce03ceda 432 state.nextq = None
9306587e 433 try:
434 state.steptimer.cancel()
435 except Exception as e:
436 print "!!! steptimer.cancel(): %s %r" % (e,e)
442ed923 437 try:
438 state.nextquestiontimer.cancel()
439 state.nextquestiontimer = None
440 except Exception as e:
441 print "!!! nextquestiontimer.cancel(): %s %r" % (e,e)
9306587e 442 return True
443 else:
444 return False
445 except NameError:
446 pass
80d02bd8 447
fb20be7c 448@lib.hook(needchan=False)
7b832b55 449@lib.argsGE(1)
fb20be7c 450def badq(bot, user, chan, realtarget, *args):
7b832b55 451 lastqid = state.lastqid
452 curqid = state.curqid
453
454 reason = ' '.join(args)
455 state.db['badqs'].append([lastqid, curqid, reason])
456 bot.msg(user, "Reported bad question.")
2520caee 457
fb20be7c 458@lib.hook(glevel=lib.STAFF, needchan=False)
459def badqs(bot, user, chan, realtarget, *args):
2520caee 460 if len(state.db['badqs']) == 0:
461 bot.msg(user, "No reports.")
462
463 for i in range(len(state.db['badqs'])):
464 try:
465 report = state.db['badqs'][i]
7b832b55 466 bot.msg(user, "Report #%d: LastQ=%r CurQ=%r: %s" % (i, report[0], report[1], report[2]))
467 try: lq = state.db['questions'][int(report[0])]
468 except Exception as e: lq = (None,None)
469 try: cq = state.db['questions'][int(report[1])]
470 except Exception as e: cq = (None, None)
471 bot.msg(user, "- Last: %s*%s" % (lq[0], lq[1]))
472 bot.msg(user, "- Curr: %s*%s" % (cq[0], cq[1]))
2520caee 473 except Exception as e:
474 bot.msg(user, "- Exception: %r" % (e))
475
fb20be7c 476@lib.hook(glevel=lib.STAFF, needchan=False)
477def clearbadqs(bot, user, chan, realtarget, *args):
2520caee 478 state.db['badqs'] = []
479 bot.msg(user, "Cleared reports.")
480
fb20be7c 481@lib.hook(glevel=lib.STAFF, needchan=False)
2520caee 482@lib.argsEQ(1)
fb20be7c 483def delbadq(bot, user, chan, realtarget, *args):
2520caee 484 qid = int(args[0])
485 del state.db['badqs'][qid]
486 bot.msg(user, "Removed report #%d" % (qid))
487
fb20be7c 488@lib.hook(needchan=False)
489def rank(bot, user, chan, realtarget, *args):
6bdfec48 490 if chan is not None and realtarget == chan.name: replyto = chan
80d02bd8 491 else: replyto = user
492
c695f740 493 if len(args) != 0: who = args[0]
494 else: who = user
495
77c61775 496 bot.msg(replyto, "%s is in %d place (%s points). Target is: %s (%s points)." % (who, state.rank(who), state.points(who), state.targetuser(who), state.targetpoints(who)))
fadbf980 497
fb20be7c 498@lib.hook(needchan=False)
499def top10(bot, user, chan, realtarget, *args):
77c61775 500 if len(state.db['ranks']) == 0:
501 return bot.msg(state.db['chan'], "No one is ranked!")
fadbf980 502
8ef938d0 503 max = len(state.db['ranks'])
504 if max > 10:
505 max = 10
506 replylist = ', '.join(["%s (%s) %s" % (person(x), country(x, "unknown"), pts(x)) for x in range(max)])
507 bot.msg(state.db['chan'], "Top %d: %s" % (max, replylist))
77c61775 508
fb20be7c 509@lib.hook(glevel=lib.ADMIN, needchan=False)
510def settarget(bot, user, chan, realtarget, *args):
77c61775 511 try:
512 state.db['target'] = int(args[0])
513 bot.msg(state.db['chan'], "Target has been changed to %s points!" % (state.db['target']))
38b29993 514
7bd5e7d5 515 if state.pointvote is not None:
516 state.pointvote.cancel()
517 state.pointvote = None
38b29993 518 bot.msg(state.db['chan'], "Vote has been cancelled!")
7bd5e7d5 519 except Exception as e:
520 print e
77c61775 521 bot.msg(user, "Failed to set target.")
522
fb20be7c 523@lib.hook(needchan=False)
524def vote(bot, user, chan, realtarget, *args):
7bd5e7d5 525 if state.pointvote is not None:
38b29993 526 if int(args[0]) in state.voteamounts:
527 state.voteamounts[int(args[0])] += 1
528 bot.msg(user, "Your vote has been recorded.")
529 else:
530 bot.msg(user, "Sorry - that's not an option!")
531 else:
532 bot.msg(user, "There's no vote in progress.")
533
fb20be7c 534@lib.hook(glevel=lib.ADMIN, needchan=False)
535def maxmissed(bot, user, chan, realtarget, *args):
c4763e66 536 try:
537 state.db['maxmissedquestions'] = int(args[0])
538 bot.msg(state.db['chan'], "Max missed questions before round ends has been changed to %s." % (state.db['maxmissedquestions']))
539 except:
540 bot.msg(user, "Failed to set maxmissed.")
541
fb20be7c 542@lib.hook(glevel=lib.ADMIN, needchan=False)
543def hinttimer(bot, user, chan, realtarget, *args):
c4763e66 544 try:
545 state.db['hinttimer'] = float(args[0])
546 bot.msg(state.db['chan'], "Time between hints has been changed to %s." % (state.db['hinttimer']))
547 except:
548 bot.msg(user, "Failed to set hint timer.")
549
fb20be7c 550@lib.hook(glevel=lib.ADMIN, needchan=False)
551def hintnum(bot, user, chan, realtarget, *args):
c4763e66 552 try:
553 state.db['hintnum'] = int(args[0])
554 bot.msg(state.db['chan'], "Max number of hints has been changed to %s." % (state.db['hintnum']))
555 except:
556 bot.msg(user, "Failed to set hintnum.")
557
fb20be7c 558@lib.hook(glevel=lib.ADMIN, needchan=False)
559def questionpause(bot, user, chan, realtarget, *args):
442ed923 560 try:
561 state.db['questionpause'] = float(args[0])
562 bot.msg(state.db['chan'], "Pause between questions has been changed to %s." % (state.db['questionpause']))
563 except:
564 bot.msg(user, "Failed to set questionpause.")
565
fb20be7c 566@lib.hook(glevel=1, needchan=False)
567def findq(bot, user, chan, realtarget, *args):
bf8676ae 568 if len(args) == 0:
569 bot.msg(user, "You need to specify a search string.")
570 return
571
aaa67e6d 572 searcher = re.compile(' '.join(args))
573 matches = [str(i) for i in range(len(state.db['questions'])) if searcher.search(state.db['questions'][i][0]) is not None]
bf8676ae 574 if len(matches) > 25:
575 bot.msg(user, "Too many matches! (>25)")
576 elif len(matches) > 1:
c4763e66 577 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
578 elif len(matches) == 1:
579 bot.msg(user, "One match: %s" % (matches[0]))
580 else:
581 bot.msg(user, "No match.")
582
fb20be7c 583@lib.hook(('delq', 'deleteq'), glevel=lib.STAFF, needchan=False)
584def delq(bot, user, chan, realtarget, *args):
c4763e66 585 try:
586 backup = state.db['questions'][int(args[0])]
587 del state.db['questions'][int(args[0])]
ebee6edb 588 bot.msg(user, "Deleted %s*%s" % (backup[0], backup[1]))
c4763e66 589 except:
590 bot.msg(user, "Couldn't delete that question.")
591
fb20be7c 592@lib.hook(glevel=lib.STAFF, needchan=False)
593def addq(bot, user, chan, realtarget, *args):
c4763e66 594 line = ' '.join([str(arg) for arg in args])
595 linepieces = line.split('*')
596 if len(linepieces) < 2:
597 bot.msg(user, "Error: need <question>*<answer>")
598 return
599 question = linepieces[0].strip()
600 answer = linepieces[1].strip()
ebee6edb 601 state.db['questions'].append([question, answer])
c4763e66 602 bot.msg(user, "Done. Question is #%s" % (len(state.db['questions'])-1))
603
604
fb20be7c 605@lib.hook(needchan=False)
606def triviahelp(bot, user, chan, realtarget, *args):
2520caee 607 bot.msg(user, "START")
608 bot.msg(user, "TOP10")
609 bot.msg(user, "POINTS [<user>]")
610 bot.msg(user, "RANK [<user>]")
bf8676ae 611 bot.msg(user, "BADQ <reason> (include info to identify question)")
9306587e 612 if user.glevel >= 1:
442ed923 613 bot.msg(user, "SKIP (>=KNOWN)")
614 bot.msg(user, "STOP (>=KNOWN)")
615 bot.msg(user, "FINDQ <question> (>=KNOWN)")
9306587e 616 if user.glevel >= lib.STAFF:
442ed923 617 bot.msg(user, "GIVE <user> [<points>] (>=STAFF)")
618 bot.msg(user, "SETNEXT <q>*<a> (>=STAFF)")
619 bot.msg(user, "ADDQ <q>*<a> (>=STAFF)")
620 bot.msg(user, "DELETEQ <q>*<a> (>=STAFF) [aka DELQ]")
2520caee 621 bot.msg(user, "BADQS (>=STAFF)")
622 bot.msg(user, "CLEARBADQS (>=STAFF)")
623 bot.msg(user, "DELBADQ <reportid> (>=STAFF)")
9306587e 624 if user.glevel >= lib.ADMIN:
442ed923 625 bot.msg(user, "SETTARGET <points> (>=ADMIN)")
626 bot.msg(user, "MAXMISSED <questions> (>=ADMIN)")
627 bot.msg(user, "HINTTIMER <float seconds> (>=ADMIN)")
628 bot.msg(user, "HINTNUM <hints> (>=ADMIN)")
629 bot.msg(user, "QUESTIONPAUSE <float seconds> (>=ADMIN)")
b5c89dfb 630
6374d61f 631@lib.hooknum(417)
632def num_417(bot, textline):
633 bot.msg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
442ed923 634 state.nextquestion(qskipped=False, skipwait=True)
6374d61f 635
f8cc0124 636@lib.hooknum(332)
637def num_TOPIC(bot, textline):
638 pieces = textline.split(None, 4)
639 chan = pieces[3]
640 if chan != state.db['chan']:
641 return
642 gottopic = pieces[4][1:]
643
644 formatted = state.db['topicformat'] % {
645 'chan': state.db['chan'],
8ef938d0 646 'top1': "%s (%s)" % (person(0), pts(0)),
647 'top3': '/'.join([
648 "%s (%s)" % (person(x), pts(x))
649 for x in range(3) if x < len(state.db['ranks'])
650 ]),
651 'top3c': ' '.join([
652 "%s (%s, %s)" % (person(x), pts(x), country(x))
653 for x in range(3) if x < len(state.db['ranks'])
654 ]),
655 'top10': ' '.join([
656 "%s (%s)" % (person(x), pts(x))
657 for x in range(10) if x < len(state.db['ranks'])
658 ]),
659 'top10c': ' '.join([
660 "%s (%s, %s)" % (person(x), pts(x), country(x))
661 for x in range(10) if x < len(state.db['ranks'])
662 ]),
f8cc0124 663 'target': state.db['target'],
664 }
665 if gottopic != formatted:
666 state.getbot().conn.send("TOPIC %s :%s" % (state.db['chan'], formatted))
667
b5c89dfb 668
669def specialQuestion(oldq):
ebee6edb 670 newq = [oldq[0], oldq[1]]
671 qtype = oldq[0].upper()
b5c89dfb 672
673 if qtype == "!MONTH":
ebee6edb 674 newq[0] = "What month is it currently (in UTC)?"
675 newq[1] = time.strftime("%B", time.gmtime()).lower()
b5c89dfb 676 elif qtype == "!MATH+":
677 randnum1 = random.randrange(0, 11)
678 randnum2 = random.randrange(0, 11)
ebee6edb 679 newq[0] = "What is %d + %d?" % (randnum1, randnum2)
680 newq[1] = spellout(randnum1+randnum2)
b5c89dfb 681 return newq
682
683def spellout(num):
684 return [
685 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
686 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
687 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"
688 ][num]