]> jfr.im git - erebus.git/blob - modules/trivia.py
remove qid from question announcement
[erebus.git] / modules / trivia.py
1 # Erebus IRC bot - Author: Erebus Team
2 # trivia module
3 # This file is released into the public domain; see http://unlicense.org/
4
5 # module info
6 modinfo = {
7 'author': 'Erebus Team',
8 'license': 'public domain',
9 'compatible': [1], # compatible module API versions
10 'depends': ['userinfo'], # other modules required to work properly?
11 }
12
13 # preamble
14 import modlib
15 lib = modlib.modlib(__name__)
16 def modstart(parent, *args, **kwargs):
17 state.gotParent(parent)
18 lib.hookchan(state.db['chan'])(trivia_checkanswer) # we need parent for this. so it goes here.
19 return lib.modstart(parent, *args, **kwargs)
20 def modstop(*args, **kwargs):
21 global state
22 try:
23 stop()
24 state.closeshop()
25 del state
26 except Exception: pass
27 return lib.modstop(*args, **kwargs)
28
29 # module code
30 import json, random, threading, re, time, datetime
31
32 try:
33 import twitter
34 except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
35
36 def 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)
41
42 def person(num): return state.db['users'][state.db['ranks'][num]]['realnick']
43 def pts(num): return str(state.db['users'][state.db['ranks'][num]]['points'])
44 def country(num, default="??"): return lib.mod('userinfo')._get(person(num), 'country', default=default)
45
46 class TriviaState(object):
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):
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
63 self.revealpossibilities = None
64 self.gameover = False
65 self.missedquestions = 0
66 self.curqid = None
67 self.lastqid = None
68
69 if 'starttime' not in self.db or self.db['starttime'] is None:
70 self.db['starttime'] = time.time()
71
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
81 def __del__(self):
82 self.closeshop()
83 def closeshop(self):
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
90 if json is not None and json.dump is not None:
91 json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
92
93 def getchan(self):
94 return self.parent.channel(self.chan)
95 def getbot(self):
96 return self.getchan().bot
97
98 def nexthint(self, hintnum):
99 answer = self.hintanswer
100
101 if self.hintstr is None or self.revealpossibilities is None or self.reveal is None:
102 self.hintstr = list(re.sub(r'[a-zA-Z0-9]', '*', answer))
103 self.revealpossibilities = range(''.join(self.hintstr).count('*'))
104 self.reveal = int(''.join(self.hintstr).count('*') * (7/24.0))
105
106 for i in range(self.reveal):
107 revealcount = random.choice(self.revealpossibilities)
108 revealloc = findnth(''.join(self.hintstr), '*', revealcount)
109 self.revealpossibilities.remove(revealcount)
110 self.hintstr[revealloc] = answer[revealloc]
111 self.parent.channel(self.chan).bot.msg(self.chan, "\00304,01Here's a hint: %s" % (''.join(self.hintstr)))
112
113 self.hintsgiven += 1
114
115 if hintnum < self.db['hintnum']:
116 self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[hintnum+1])
117 self.steptimer.start()
118 else:
119 self.steptimer = threading.Timer(self.db['hinttimer'], self.nextquestion, args=[True])
120 self.steptimer.start()
121
122 def doGameOver(self):
123 msg = self.getchan().msg
124 winner = person(0)
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
132 except Exception as e: msg("DERP! %r" % (e))
133
134 if self.db['hofpath'] is not None and self.db['hofpath'] != '':
135 self.writeHof()
136
137 self.db['users'] = {}
138 self.db['ranks'] = []
139 stop()
140 self.closeshop()
141
142 try:
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))
148 except: pass #don't care if errors happen updating twitter.
149
150 self.__init__(self.parent, True)
151
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
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]))
193
194 self.db['target'] = votelist[-1][0]
195 self.pointvote = None
196
197 self.nextquestion() #start the game!
198
199 def nextquestion(self, qskipped=False, iteration=0, skipwait=False):
200 self.lastqid = self.curqid
201 self.curq = None
202 self.curqid = None
203 if self.gameover == True:
204 return self.doGameOver()
205 if qskipped:
206 self.getchan().msg("\00304Fail! The correct answer was: %s" % (self.hintanswer))
207 self.missedquestions += 1
208 else:
209 self.missedquestions = 0
210 if 'topicformat' in self.db and self.db['topicformat'] is not None:
211 self.getbot().conn.send("TOPIC %s" % (self.db['chan']))
212
213 if isinstance(self.steptimer, threading._Timer):
214 self.steptimer.cancel()
215 if isinstance(self.nextquestiontimer, threading._Timer):
216 self.nextquestiontimer.cancel()
217 self.nextquestiontimer = None
218
219 self.hintstr = None
220 self.hintsgiven = 0
221 self.revealpossibilities = None
222 self.reveal = None
223
224 if self.missedquestions > self.db['maxmissedquestions']:
225 stop()
226 self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game." % (self.missedquestions))
227 return
228
229 if skipwait:
230 self._nextquestion(iteration)
231 else:
232 self.nextquestiontimer = threading.Timer(self.db['questionpause'], self._nextquestion, args=[iteration])
233 self.nextquestiontimer.start()
234
235 def _nextquestion(self, iteration):
236 if self.nextq is not None:
237 nextqid = None
238 nextq = self.nextq
239 self.nextq = None
240 else:
241 nextqid = random.randrange(0, len(self.db['questions']))
242 nextq = self.db['questions'][nextqid]
243
244 if nextq[0][0] == "!":
245 nextqid = None
246 nextq = specialQuestion(nextq)
247
248 if len(nextq) > 2 and nextq[2] - time.time() < 7*24*60*60 and iteration < 10:
249 return self._nextquestion(iteration=iteration+1) #short-circuit to pick another question
250 if len(nextq) > 2:
251 nextq[2] = time.time()
252 else:
253 nextq.append(time.time())
254
255 nextq[1] = nextq[1].lower()
256
257 qtext = "\00304,01Next up: "
258 if nextqid is None:
259 qtext += "(DYNAMIC) "
260 qary = nextq[0].split(None)
261 for qword in qary:
262 qtext += "\00304,01"+qword+"\00301,01"+chr(random.randrange(0x61,0x7A)) #a-z
263 self.getbot().msg(self.chan, qtext)
264
265 self.curq = nextq
266 self.curqid = nextqid
267
268 if isinstance(self.curq[1], basestring): self.hintanswer = self.curq[1]
269 else: self.hintanswer = random.choice(self.curq[1])
270
271 self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[1])
272 self.steptimer.start()
273
274 def checkanswer(self, answer):
275 if self.curq is None:
276 return False
277 elif isinstance(self.curq[1], basestring):
278 return answer.lower() == self.curq[1]
279 else: # assume it's a list or something.
280 return answer.lower() in self.curq[1]
281
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
285 if user in self.db['users']:
286 self.db['users'][user]['points'] += count
287 else:
288 self.db['users'][user] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
289 self.db['ranks'].append(user)
290
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
292 for i in range(0, len(self.db['ranks'])):
293 nick = self.db['ranks'][i]
294 self.db['users'][nick]['rank'] = i
295
296 if self.db['users'][user]['points'] >= self.db['target']:
297 self.gameover = True
298
299 return self.db['users'][user]['points']
300
301 def points(self, user):
302 user = str(user).lower()
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):
309 user = str(user).lower()
310 if user in self.db['users']:
311 return self.db['users'][user]['rank']+1
312 else:
313 return len(self.db['users'])+1
314
315 def targetuser(self, user):
316 if len(self.db['ranks']) == 0: return "no one is ranked!"
317
318 user = str(user).lower()
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]
325 else:
326 return self.db['ranks'][-1]
327 def targetpoints(self, user):
328 if len(self.db['ranks']) == 0: return 0
329
330 user = str(user).lower()
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']
337 else:
338 return self.db['users'][self.db['ranks'][-1]]['points']
339
340 state = TriviaState()
341
342 # we have to hook this in modstart, since we don't know the channel until then.
343 def trivia_checkanswer(bot, user, chan, *args):
344 line = ' '.join([str(arg) for arg in args])
345 if state.checkanswer(line):
346 state.curq = None
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)))
348 if state.hintsgiven == 0:
349 bot.msg(chan, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user)))
350 state.nextquestion()
351
352 @lib.hook(needchan=False)
353 def points(bot, user, chan, realtarget, *args):
354 if chan is not None and realtarget == chan.name: replyto = chan
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
362 @lib.hook(glevel=lib.STAFF, needchan=False)
363 @lib.argsGE(1)
364 def give(bot, user, chan, realtarget, *args):
365 whoto = args[0]
366 if len(args) > 1:
367 numpoints = int(args[1])
368 else:
369 numpoints = 1
370 balance = state.addpoint(whoto, numpoints)
371
372 bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance))
373
374 @lib.hook(glevel=1, needchan=False)
375 def setnextid(bot, user, chan, realtarget, *args):
376 try:
377 qid = int(args[0])
378 state.nextq = state.db['questions'][qid]
379 bot.msg(user, "Done. Next question is: %s" % (state.nextq[0]))
380 except Exception as e:
381 bot.msg(user, "Error: %s" % (e))
382
383 @lib.hook(glevel=lib.STAFF, needchan=False)
384 @lib.argsGE(1)
385 def setnext(bot, user, chan, realtarget, *args):
386 line = ' '.join([str(arg) for arg in args])
387 linepieces = line.split('*')
388 if len(linepieces) < 2:
389 bot.msg(user, "Error: need <question>*<answer>")
390 return
391 question = linepieces[0].strip()
392 answer = linepieces[1].strip()
393 state.nextq = [question, answer]
394 bot.msg(user, "Done.")
395
396 @lib.hook(glevel=1, needchan=False)
397 def skip(bot, user, chan, realtarget, *args):
398 state.nextquestion(qskipped=True, skipwait=True)
399
400 @lib.hook(needchan=False)
401 def start(bot, user, chan, realtarget, *args):
402 if chan is not None and realtarget == chan.name: replyto = chan
403 else: replyto = user
404
405 if chan is not None and chan.name != state.db['chan']:
406 bot.msg(replyto, "That command isn't valid here.")
407 return
408
409 if state.curq is None and state.pointvote is None and state.nextquestiontimer is None:
410 bot.msg(state.db['chan'], "%s has started the game!" % (user))
411 state.nextquestion(skipwait=True)
412 elif state.pointvote is not None:
413 bot.msg(replyto, "There's a vote in progress!")
414 else:
415 bot.msg(replyto, "Game is already started!")
416
417 @lib.hook('stop', glevel=1, needchan=False)
418 def cmd_stop(bot, user, chan, realtarget, *args):
419 if stop():
420 bot.msg(state.chan, "Game stopped by %s" % (user))
421 else:
422 bot.msg(user, "Game isn't running.")
423
424 def stop():
425 try:
426 if state.curq is not None or state.nextq is not None:
427 state.curq = None
428 state.nextq = None
429 try:
430 state.steptimer.cancel()
431 except Exception as e:
432 print "!!! steptimer.cancel(): %s %r" % (e,e)
433 try:
434 state.nextquestiontimer.cancel()
435 state.nextquestiontimer = None
436 except Exception as e:
437 print "!!! nextquestiontimer.cancel(): %s %r" % (e,e)
438 return True
439 else:
440 return False
441 except NameError:
442 pass
443
444 @lib.hook(needchan=False)
445 @lib.argsGE(1)
446 def badq(bot, user, chan, realtarget, *args):
447 lastqid = state.lastqid
448 curqid = state.curqid
449
450 reason = ' '.join(args)
451 state.db['badqs'].append([lastqid, curqid, reason])
452 bot.msg(user, "Reported bad question.")
453
454 @lib.hook(glevel=lib.STAFF, needchan=False)
455 def badqs(bot, user, chan, realtarget, *args):
456 if len(state.db['badqs']) == 0:
457 bot.msg(user, "No reports.")
458
459 for i in range(len(state.db['badqs'])):
460 try:
461 report = state.db['badqs'][i]
462 bot.msg(user, "Report #%d: LastQ=%r CurQ=%r: %s" % (i, report[0], report[1], report[2]))
463 try: lq = state.db['questions'][int(report[0])]
464 except Exception as e: lq = (None,None)
465 try: cq = state.db['questions'][int(report[1])]
466 except Exception as e: cq = (None, None)
467 bot.msg(user, "- Last: %s*%s" % (lq[0], lq[1]))
468 bot.msg(user, "- Curr: %s*%s" % (cq[0], cq[1]))
469 except Exception as e:
470 bot.msg(user, "- Exception: %r" % (e))
471
472 @lib.hook(glevel=lib.STAFF, needchan=False)
473 def clearbadqs(bot, user, chan, realtarget, *args):
474 state.db['badqs'] = []
475 bot.msg(user, "Cleared reports.")
476
477 @lib.hook(glevel=lib.STAFF, needchan=False)
478 @lib.argsEQ(1)
479 def delbadq(bot, user, chan, realtarget, *args):
480 qid = int(args[0])
481 del state.db['badqs'][qid]
482 bot.msg(user, "Removed report #%d" % (qid))
483
484 @lib.hook(needchan=False)
485 def rank(bot, user, chan, realtarget, *args):
486 if chan is not None and realtarget == chan.name: replyto = chan
487 else: replyto = user
488
489 if len(args) != 0: who = args[0]
490 else: who = user
491
492 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)))
493
494 @lib.hook(needchan=False)
495 def top10(bot, user, chan, realtarget, *args):
496 if len(state.db['ranks']) == 0:
497 return bot.msg(state.db['chan'], "No one is ranked!")
498
499 max = len(state.db['ranks'])
500 if max > 10:
501 max = 10
502 replylist = ', '.join(["%s (%s) %s" % (person(x), country(x, "unknown"), pts(x)) for x in range(max)])
503 bot.msg(state.db['chan'], "Top %d: %s" % (max, replylist))
504
505 @lib.hook(glevel=lib.ADMIN, needchan=False)
506 def settarget(bot, user, chan, realtarget, *args):
507 try:
508 state.db['target'] = int(args[0])
509 bot.msg(state.db['chan'], "Target has been changed to %s points!" % (state.db['target']))
510
511 if state.pointvote is not None:
512 state.pointvote.cancel()
513 state.pointvote = None
514 bot.msg(state.db['chan'], "Vote has been cancelled!")
515 except Exception as e:
516 print e
517 bot.msg(user, "Failed to set target.")
518
519 @lib.hook(needchan=False)
520 def vote(bot, user, chan, realtarget, *args):
521 if state.pointvote is not None:
522 if int(args[0]) in state.voteamounts:
523 state.voteamounts[int(args[0])] += 1
524 bot.msg(user, "Your vote has been recorded.")
525 else:
526 bot.msg(user, "Sorry - that's not an option!")
527 else:
528 bot.msg(user, "There's no vote in progress.")
529
530 @lib.hook(glevel=lib.ADMIN, needchan=False)
531 def maxmissed(bot, user, chan, realtarget, *args):
532 try:
533 state.db['maxmissedquestions'] = int(args[0])
534 bot.msg(state.db['chan'], "Max missed questions before round ends has been changed to %s." % (state.db['maxmissedquestions']))
535 except:
536 bot.msg(user, "Failed to set maxmissed.")
537
538 @lib.hook(glevel=lib.ADMIN, needchan=False)
539 def hinttimer(bot, user, chan, realtarget, *args):
540 try:
541 state.db['hinttimer'] = float(args[0])
542 bot.msg(state.db['chan'], "Time between hints has been changed to %s." % (state.db['hinttimer']))
543 except:
544 bot.msg(user, "Failed to set hint timer.")
545
546 @lib.hook(glevel=lib.ADMIN, needchan=False)
547 def hintnum(bot, user, chan, realtarget, *args):
548 try:
549 state.db['hintnum'] = int(args[0])
550 bot.msg(state.db['chan'], "Max number of hints has been changed to %s." % (state.db['hintnum']))
551 except:
552 bot.msg(user, "Failed to set hintnum.")
553
554 @lib.hook(glevel=lib.ADMIN, needchan=False)
555 def questionpause(bot, user, chan, realtarget, *args):
556 try:
557 state.db['questionpause'] = float(args[0])
558 bot.msg(state.db['chan'], "Pause between questions has been changed to %s." % (state.db['questionpause']))
559 except:
560 bot.msg(user, "Failed to set questionpause.")
561
562 @lib.hook(glevel=1, needchan=False)
563 def findq(bot, user, chan, realtarget, *args):
564 searcher = re.compile(' '.join(args))
565 matches = [str(i) for i in range(len(state.db['questions'])) if searcher.search(state.db['questions'][i][0]) is not None]
566 if len(matches) > 1:
567 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
568 elif len(matches) == 1:
569 bot.msg(user, "One match: %s" % (matches[0]))
570 else:
571 bot.msg(user, "No match.")
572
573 @lib.hook(('delq', 'deleteq'), glevel=lib.STAFF, needchan=False)
574 def delq(bot, user, chan, realtarget, *args):
575 try:
576 backup = state.db['questions'][int(args[0])]
577 del state.db['questions'][int(args[0])]
578 bot.msg(user, "Deleted %s*%s" % (backup[0], backup[1]))
579 except:
580 bot.msg(user, "Couldn't delete that question.")
581
582 @lib.hook(glevel=lib.STAFF, needchan=False)
583 def addq(bot, user, chan, realtarget, *args):
584 line = ' '.join([str(arg) for arg in args])
585 linepieces = line.split('*')
586 if len(linepieces) < 2:
587 bot.msg(user, "Error: need <question>*<answer>")
588 return
589 question = linepieces[0].strip()
590 answer = linepieces[1].strip()
591 state.db['questions'].append([question, answer])
592 bot.msg(user, "Done. Question is #%s" % (len(state.db['questions'])-1))
593
594
595 @lib.hook(needchan=False)
596 def triviahelp(bot, user, chan, realtarget, *args):
597 bot.msg(user, "START")
598 bot.msg(user, "TOP10")
599 bot.msg(user, "POINTS [<user>]")
600 bot.msg(user, "RANK [<user>]")
601 bot.msg(user, "BADQ <id> <reason>")
602 if user.glevel >= 1:
603 bot.msg(user, "SKIP (>=KNOWN)")
604 bot.msg(user, "STOP (>=KNOWN)")
605 bot.msg(user, "FINDQ <question> (>=KNOWN)")
606 if user.glevel >= lib.STAFF:
607 bot.msg(user, "GIVE <user> [<points>] (>=STAFF)")
608 bot.msg(user, "SETNEXT <q>*<a> (>=STAFF)")
609 bot.msg(user, "ADDQ <q>*<a> (>=STAFF)")
610 bot.msg(user, "DELETEQ <q>*<a> (>=STAFF) [aka DELQ]")
611 bot.msg(user, "BADQS (>=STAFF)")
612 bot.msg(user, "CLEARBADQS (>=STAFF)")
613 bot.msg(user, "DELBADQ <reportid> (>=STAFF)")
614 if user.glevel >= lib.ADMIN:
615 bot.msg(user, "SETTARGET <points> (>=ADMIN)")
616 bot.msg(user, "MAXMISSED <questions> (>=ADMIN)")
617 bot.msg(user, "HINTTIMER <float seconds> (>=ADMIN)")
618 bot.msg(user, "HINTNUM <hints> (>=ADMIN)")
619 bot.msg(user, "QUESTIONPAUSE <float seconds> (>=ADMIN)")
620
621 @lib.hooknum(417)
622 def num_417(bot, textline):
623 bot.msg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
624 state.nextquestion(qskipped=False, skipwait=True)
625
626 @lib.hooknum(332)
627 def num_TOPIC(bot, textline):
628 pieces = textline.split(None, 4)
629 chan = pieces[3]
630 if chan != state.db['chan']:
631 return
632 gottopic = pieces[4][1:]
633
634 formatted = state.db['topicformat'] % {
635 'chan': state.db['chan'],
636 'top1': "%s (%s)" % (person(0), pts(0)),
637 'top3': '/'.join([
638 "%s (%s)" % (person(x), pts(x))
639 for x in range(3) if x < len(state.db['ranks'])
640 ]),
641 'top3c': ' '.join([
642 "%s (%s, %s)" % (person(x), pts(x), country(x))
643 for x in range(3) if x < len(state.db['ranks'])
644 ]),
645 'top10': ' '.join([
646 "%s (%s)" % (person(x), pts(x))
647 for x in range(10) if x < len(state.db['ranks'])
648 ]),
649 'top10c': ' '.join([
650 "%s (%s, %s)" % (person(x), pts(x), country(x))
651 for x in range(10) if x < len(state.db['ranks'])
652 ]),
653 'target': state.db['target'],
654 }
655 if gottopic != formatted:
656 state.getbot().conn.send("TOPIC %s :%s" % (state.db['chan'], formatted))
657
658
659 def specialQuestion(oldq):
660 newq = [oldq[0], oldq[1]]
661 qtype = oldq[0].upper()
662
663 if qtype == "!MONTH":
664 newq[0] = "What month is it currently (in UTC)?"
665 newq[1] = time.strftime("%B", time.gmtime()).lower()
666 elif qtype == "!MATH+":
667 randnum1 = random.randrange(0, 11)
668 randnum2 = random.randrange(0, 11)
669 newq[0] = "What is %d + %d?" % (randnum1, randnum2)
670 newq[1] = spellout(randnum1+randnum2)
671 return newq
672
673 def spellout(num):
674 return [
675 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
676 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
677 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"
678 ][num]