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