]> jfr.im git - erebus.git/blobdiff - modules/trivia.py
add watchdog timer. fixes #12
[erebus.git] / modules / trivia.py
index f7e6a698716b7d269add3234bec586cd72440102..cb77be77d990a2388e03415ed6b0b1b1e74f8379 100644 (file)
@@ -6,8 +6,9 @@
 modinfo = {
        'author': 'Erebus Team',
        'license': 'public domain',
-       'compatible': [1], # compatible module API versions
-       'depends': [], # other modules required to work properly?
+       'compatible': [1,2],
+       'depends': ['userinfo'],
+       'softdeps': ['help'],
 }
 
 # preamble
@@ -27,10 +28,10 @@ def modstop(*args, **kwargs):
        return lib.modstop(*args, **kwargs)
 
 # module code
-import json, random, threading, re, time, datetime
+import json, random, threading, re, time, datetime, os
 
 try:
-       import twitter 
+       import twitter
 except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
 
 def findnth(haystack, needle, n): #http://stackoverflow.com/a/1884151
@@ -39,9 +40,28 @@ def findnth(haystack, needle, n): #http://stackoverflow.com/a/1884151
                return -1
        return len(haystack)-len(parts[-1])-len(needle)
 
-def person(num): return state.db['users'][state.db['ranks'][num]]['realnick']
-def pts(num): return str(state.db['users'][state.db['ranks'][num]]['points'])
-def country(num, default="??"): return lib.mod('userinfo').get(person(num), 'country', default=default)
+def person(num, throwindexerror=False):
+       try:
+               return state.db['users'][state.db['ranks'][num]]['realnick']
+       except IndexError:
+               if throwindexerror:
+                       raise
+               else:
+                       return ''
+
+def pts(num):
+       try:
+               return str(state.db['users'][state.db['ranks'][num]]['points'])
+       except IndexError:
+               return 0
+
+def country(num, default="??"):
+       return lib.mod('userinfo')._get(person(num), 'country', default=default).upper()
+
+class MyTimer(threading._Timer):
+       def __init__(self, *args, **kwargs):
+               threading._Timer.__init__(self, *args, **kwargs)
+               self.daemon = True
 
 class TriviaState(object):
        def __init__(self, parent=None, pointvote=False):
@@ -49,29 +69,32 @@ class TriviaState(object):
                        self.gotParent(parent, pointvote)
 
        def gotParent(self, parent, pointvote=False):
-               self.parent = parent
-               self.questionfile = self.parent.cfg.get('trivia', 'jsonpath', default="./modules/trivia.json")
-               self.db = json.load(open(self.questionfile, "r"))
-               self.chan = self.db['chan']
-               self.curq = None
-               self.nextq = None
-               self.nextquestiontimer = None
-               self.steptimer = None
-               self.hintstr = None
-               self.hintanswer = None
-               self.hintsgiven = 0
+               self.parent              = parent
+               self.questionfile        = self.parent.cfg.get('trivia', 'jsonpath', default="./modules/trivia.json")
+               self.db                  = json.load(open(self.questionfile, "r"))
+               self.questions           = self.db['questions'][self.db['category']]
+               self.chan                = self.db['chan']
+               self.curq                = None
+               self.nextq               = None
+               self.nextquestiontimer   = None
+               self.steptimer           = None
+               self.hintstr             = None
+               self.hintanswer          = None
+               self.hintsgiven          = 0
                self.revealpossibilities = None
-               self.gameover = False
-               self.missedquestions = 0
+               self.gameover            = False
+               self.missedquestions     = 0
+               self.curqid              = None
+               self.lastqid             = None
 
-               if 'starttime' not in self.db or self.db['starttime'] is None:
-                       self.db['starttime'] = time.time()
+               if 'lastwon' not in self.db or self.db['lastwon'] is None:
+                       self.db['lastwon'] = time.time()
 
                if pointvote:
                        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']])))
                        self.getchan().msg("You have %s seconds." % (self.db['votetimer']))
                        self.voteamounts = dict([(x, 0) for x in self.db['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
-                       self.pointvote = threading.Timer(self.db['votetimer'], self.endPointVote)
+                       self.pointvote = MyTimer(self.db['votetimer'], self.endPointVote)
                        self.pointvote.start()
                else:
                        self.pointvote = None
@@ -79,14 +102,36 @@ class TriviaState(object):
        def __del__(self):
                self.closeshop()
        def closeshop(self):
-               if threading is not None and threading._Timer is not None:
-                       if isinstance(self.steptimer, threading._Timer):
-                               self.steptimer.cancel()
-                       if isinstance(self.nextquestiontimer, threading._Timer):
-                               self.nextquestiontimer.cancel()
-                               self.nextquestiontimer = None
+               try:
+                       self.steptimer.cancel()
+                       self.steptimer = None
+               except: pass
+               try:
+                       self.nextquestiontimer.cancel()
+                       self.nextquestiontimer = None
+               except: pass
+
+       def savedb(self): #returns whether or not it was able to save
                if json is not None and json.dump is not None:
-                       json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
+#                      json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
+                       dbjson = json.dumps(self.db)
+                       if len(dbjson) > 0:
+                               os.rename(self.questionfile, self.questionfile+".auto.bak")
+                               tmpfn = os.tempnam('.', 'trivia')
+                               try:
+                                       f = open(tmpfn, "w")
+                                       f.write(dbjson)
+                                       f.close()
+                                       os.rename(tmpfn, self.questionfile)
+                                       return True
+                               except: #if something happens, restore the backup
+                                       os.rename(self.questionfile+".auto.bak", self.questionfile)
+                                       try:
+                                               os.unlink(tmpfn)
+                                       except OSError: # temp file is already gone
+                                               pass
+                                       raise # we may be better off just swallowing exceptions?
+               return False
 
        def getchan(self):
                return self.parent.channel(self.chan)
@@ -97,24 +142,27 @@ class TriviaState(object):
                answer = self.hintanswer
 
                if self.hintstr is None or self.revealpossibilities is None or self.reveal is None:
+                       oldhintstr = ""
                        self.hintstr = list(re.sub(r'[a-zA-Z0-9]', '*', answer))
                        self.revealpossibilities = range(''.join(self.hintstr).count('*'))
-                       self.reveal = int(''.join(self.hintstr).count('*') * (7/24.0))
+                       self.reveal = int(round(''.join(self.hintstr).count('*') * (7/24.0)))
+               else:
+                       oldhintstr = ''.join(self.hintstr)
 
                for i in range(self.reveal):
                        revealcount = random.choice(self.revealpossibilities)
                        revealloc = findnth(''.join(self.hintstr), '*', revealcount)
                        self.revealpossibilities.remove(revealcount)
                        self.hintstr[revealloc] = answer[revealloc]
-               self.parent.channel(self.chan).bot.msg(self.chan, "\00304,01Here's a hint: %s" % (''.join(self.hintstr)))
+               if oldhintstr != ''.join(self.hintstr): self.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self.hintstr)))
 
                self.hintsgiven += 1
 
                if hintnum < self.db['hintnum']:
-                       self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[hintnum+1])
+                       self.steptimer = MyTimer(self.db['hinttimer'], self.nexthint, args=[hintnum+1])
                        self.steptimer.start()
                else:
-                       self.steptimer = threading.Timer(self.db['hinttimer'], self.nextquestion, args=[True])
+                       self.steptimer = MyTimer(self.db['hinttimer'], self.nextquestion, args=[True])
                        self.steptimer.start()
 
        def doGameOver(self):
@@ -122,12 +170,16 @@ class TriviaState(object):
                winner = person(0)
                try:
                        msg("\00312THE GAME IS OVER!!!")
-                       msg("THE WINNER IS: %s (%s)" % (person(0), pts(0)))
-                       msg("2ND PLACE: %s (%s)" % (person(1), pts(1)))
-                       msg("3RD PLACE: %s (%s)" % (person(2), pts(2)))
-                       [msg("%dth place: %s (%s)" % (i+1, person(i), pts(i))) for i in range(3,10)]
+                       msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
+                       msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
+                       msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
+                       [msg("%dth place: %s (%s)" % (i+1, person(i, True), pts(i))) for i in range(3,10)]
                except IndexError: pass
-               except Exception as e: msg("DERP! %r" % (e))
+               except Exception as e:
+                       msg("DERP! %r" % (e))
+
+               self.db['lastwinner'] = winner
+               self.db['lastwon'] = time.time()
 
                if self.db['hofpath'] is not None and self.db['hofpath'] != '':
                        self.writeHof()
@@ -155,6 +207,7 @@ class TriviaState(object):
                        try: return str(self.db['users'][self.db['ranks'][num]]['points'])
                        except: return 0
 
+               status = False
                try:
                        f = open(self.db['hofpath'], 'rb+')
                        for i in range(self.db['hoflines']): #skip this many lines
@@ -164,7 +217,7 @@ class TriviaState(object):
                        f.seek(insertpos)
                        f.write((self.db['hofformat']+"\n") % {
                                'date': time.strftime("%F", time.gmtime()),
-                               'duration': str(datetime.timedelta(seconds=time.time()-self.db['starttime'])),
+                               'duration': str(datetime.timedelta(seconds=time.time()-self.db['lastwon'])),
                                'targetscore': self.db['target'],
                                'firstperson': person(0),
                                'firstscore': pts(0),
@@ -174,12 +227,12 @@ class TriviaState(object):
                                'thirdscore': pts(2),
                        })
                        f.write(fcontents)
-                       return True
+                       status = True
                except Exception as e:
-                       raise e
-                       return False
+                       status = False
                finally:
                        f.close()
+                       return status
 
        def endPointVote(self):
                self.getchan().msg("Voting has ended!")
@@ -195,20 +248,22 @@ class TriviaState(object):
                self.nextquestion() #start the game!
 
        def nextquestion(self, qskipped=False, iteration=0, skipwait=False):
+               self.lastqid = self.curqid
                self.curq = None
+               self.curqid = None
                if self.gameover == True:
                        return self.doGameOver()
                if qskipped:
-                       self.getchan().msg("\00304Fail! The correct answer was: %s" % (self.hintanswer))
+                       self.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self.hintanswer))
                        self.missedquestions += 1
                else:
                        self.missedquestions = 0
                        if 'topicformat' in self.db and self.db['topicformat'] is not None:
                                self.getbot().conn.send("TOPIC %s" % (self.db['chan']))
 
-               if isinstance(self.steptimer, threading._Timer):
+               if isinstance(self.steptimer, MyTimer):
                        self.steptimer.cancel()
-               if isinstance(self.nextquestiontimer, threading._Timer):
+               if isinstance(self.nextquestiontimer, MyTimer):
                        self.nextquestiontimer.cancel()
                        self.nextquestiontimer = None
 
@@ -217,6 +272,8 @@ class TriviaState(object):
                self.revealpossibilities = None
                self.reveal = None
 
+               self.savedb()
+
                if self.missedquestions > self.db['maxmissedquestions']:
                        stop()
                        self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game." % (self.missedquestions))
@@ -225,7 +282,7 @@ class TriviaState(object):
                if skipwait:
                        self._nextquestion(iteration)
                else:
-                       self.nextquestiontimer = threading.Timer(self.db['questionpause'], self._nextquestion, args=[iteration])
+                       self.nextquestiontimer = MyTimer(self.db['questionpause'], self._nextquestion, args=[iteration])
                        self.nextquestiontimer.start()
 
        def _nextquestion(self, iteration):
@@ -234,8 +291,8 @@ class TriviaState(object):
                        nextq = self.nextq
                        self.nextq = None
                else:
-                       nextqid = random.randrange(0, len(self.db['questions']))
-                       nextq = self.db['questions'][nextqid]
+                       nextqid = random.randrange(0, len(self.questions))
+                       nextq = self.questions[nextqid]
 
                if nextq[0][0] == "!":
                        nextqid = None
@@ -248,22 +305,29 @@ class TriviaState(object):
                else:
                        nextq.append(time.time())
 
-               nextq[1] = nextq[1].lower()
+               if isinstance(nextq[1], basestring):
+                       nextq[1] = nextq[1].lower()
+               else:
+                       nextq[1] = [s.lower() for s in nextq[1]]
 
-               qtext = "\00304,01Next up: "
-               if nextqid is not None:
-                       qtext += "(%d) " % (nextqid)
+               qtext = "\00312,01Next up: "
+               qtext += "(%5d)" % (random.randint(0,99999))
                qary = nextq[0].split(None)
+               qtext += " "
                for qword in qary:
-                       qtext += "\00304,01"+qword+"\00301,01"+chr(random.randrange(0x61,0x7A)) #a-z
-               self.getbot().msg(self.chan, qtext)
+                       spacer = random.choice(
+                               range(0x61,0x7A) + ([0x20]*4)
+                       )
+                       qtext += "\00304,01"+qword+"\00301,01"+chr(spacer) #a-z
+               self.getbot().fastmsg(self.chan, qtext)
 
                self.curq = nextq
+               self.curqid = nextqid
 
                if isinstance(self.curq[1], basestring): self.hintanswer = self.curq[1]
                else: self.hintanswer = random.choice(self.curq[1])
 
-               self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[1])
+               self.steptimer = MyTimer(self.db['hinttimer'], self.nexthint, args=[1])
                self.steptimer.start()
 
        def checkanswer(self, answer):
@@ -326,11 +390,11 @@ class TriviaState(object):
                if user in self.db['users']:
                        rank = self.db['users'][user]['rank']
                        if rank == 0:
-                               return "N/A"
+                               return ""
                        else:
-                               return self.db['users'][self.db['ranks'][rank-1]]['points']
+                               return "("+str(self.db['users'][self.db['ranks'][rank-1]]['points'])+")"
                else:
-                       return self.db['users'][self.db['ranks'][-1]]['points']
+                       return "("+str(self.db['users'][self.db['ranks'][-1]]['points'])+")"
 
 state = TriviaState()
 
@@ -339,13 +403,28 @@ def trivia_checkanswer(bot, user, chan, *args):
        line = ' '.join([str(arg) for arg in args])
        if state.checkanswer(line):
                state.curq = None
-               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)))
+               if state.hintanswer.lower() == line.lower():
+                       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)))
+               else:
+                       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)))
                if state.hintsgiven == 0:
                        bot.msg(chan, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user)))
                state.nextquestion()
 
-@lib.hook('points', needchan=False)
-def cmd_points(bot, user, chan, realtarget, *args):
+@lib.hook(glevel=1, needchan=False)
+@lib.help(None, "saves the trivia database")
+def save(bot, user, chan, realtarget, *args):
+       if chan is not None and realtarget == chan.name: replyto = chan
+       else: replyto = user
+
+       if state.savedb():
+               bot.msg(replyto, "Save successful.")
+       else:
+               bot.msg(replyto, "Save failed!")
+
+@lib.hook(needchan=False)
+@lib.help("[<user>]", "shows how many points you or someone has")
+def points(bot, user, chan, realtarget, *args):
        if chan is not None and realtarget == chan.name: replyto = chan
        else: replyto = user
 
@@ -354,9 +433,10 @@ def cmd_points(bot, user, chan, realtarget, *args):
 
        bot.msg(replyto, "%s has %d points." % (who, state.points(who)))
 
-@lib.hook('give', glevel=lib.STAFF, needchan=False)
+@lib.hook(glevel=lib.STAFF, needchan=False)
+@lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
 @lib.argsGE(1)
-def cmd_give(bot, user, chan, realtarget, *args):
+def give(bot, user, chan, realtarget, *args):
        whoto = args[0]
        if len(args) > 1:
                numpoints = int(args[1])
@@ -366,18 +446,25 @@ def cmd_give(bot, user, chan, realtarget, *args):
 
        bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance))
 
-@lib.hook('setnextid', glevel=1, needchan=False)
-def cmd_setnextid(bot, user, chan, realtarget, *args):
+@lib.hook(glevel=1, needchan=False)
+@lib.help("<qid>", "sets next question to one in the database")
+@lib.argsEQ(1)
+def setnextid(bot, user, chan, realtarget, *args):
        try:
                qid = int(args[0])
-               state.nextq = state.db['questions'][qid]
-               bot.msg(user, "Done. Next question is: %s" % (state.nextq[0]))
+               state.nextq = state.questions[qid]
+               if user.glevel >= lib.STAFF:
+                       respstr = "Done. Next question is: %s" % (state.nextq[0])
+               else:
+                       respstr = "Done."
+               bot.msg(user, respstr)
        except Exception as e:
                bot.msg(user, "Error: %s" % (e))
 
-@lib.hook('setnext', glevel=lib.STAFF, needchan=False)
+@lib.hook(glevel=lib.STAFF, needchan=False)
+@lib.help("<q>*<a>", "sets next question to one not in database")
 @lib.argsGE(1)
-def cmd_setnext(bot, user, chan, realtarget, *args):
+def setnext(bot, user, chan, realtarget, *args):
        line = ' '.join([str(arg) for arg in args])
        linepieces = line.split('*')
        if len(linepieces) < 2:
@@ -388,12 +475,14 @@ def cmd_setnext(bot, user, chan, realtarget, *args):
        state.nextq = [question, answer]
        bot.msg(user, "Done.")
 
-@lib.hook('skip', glevel=1, needchan=False)
-def cmd_skip(bot, user, chan, realtarget, *args):
+@lib.hook(glevel=1, needchan=False)
+@lib.help(None, "skips to next question")
+def skip(bot, user, chan, realtarget, *args):
        state.nextquestion(qskipped=True, skipwait=True)
 
-@lib.hook('start', needchan=False)
-def cmd_start(bot, user, chan, realtarget, *args):
+@lib.hook(needchan=False)
+@lib.help(None, "starts the trivia game")
+def start(bot, user, chan, realtarget, *args):
        if chan is not None and realtarget == chan.name: replyto = chan
        else: replyto = user
 
@@ -405,11 +494,12 @@ def cmd_start(bot, user, chan, realtarget, *args):
                bot.msg(state.db['chan'], "%s has started the game!" % (user))
                state.nextquestion(skipwait=True)
        elif state.pointvote is not None:
-               bot.msg(replyto, "There's a vote in progress!")
+               bot.msg(user, "There's a vote in progress!")
        else:
-               bot.msg(replyto, "Game is already started!")
+               bot.msg(user, "Game is already started!")
 
 @lib.hook('stop', glevel=1, needchan=False)
+@lib.help(None, "stops the trivia game")
 def cmd_stop(bot, user, chan, realtarget, *args):
        if stop():
                bot.msg(state.chan, "Game stopped by %s" % (user))
@@ -417,83 +507,93 @@ def cmd_stop(bot, user, chan, realtarget, *args):
                bot.msg(user, "Game isn't running.")
 
 def stop():
+       state.curq = None
+       state.nextq = None
        try:
-               if state.curq is not None or state.nextq is not None:
-                       state.curq = None
-                       state.nextq = None
-                       try:
-                               state.steptimer.cancel()
-                       except Exception as e:
-                               print "!!! steptimer.cancel(): %s %r" % (e,e)
-                       try:
-                               state.nextquestiontimer.cancel()
-                               state.nextquestiontimer = None
-                       except Exception as e:
-                               print "!!! nextquestiontimer.cancel(): %s %r" % (e,e)
-                       return True
-               else:
-                       return False
-       except NameError:
-               pass
-
-@lib.hook('badq', needchan=False)
-@lib.argsGE(2)
-def cmd_badq(bot, user, chan, realtarget, *args):
-       qid = int(args[0])
-       reason = ' '.join(args[1:])
-       state.db['badqs'].append([qid, reason])
-       bot.msg(user, "Reported bad question #%d" % (qid))
-
-@lib.hook('badqs', glevel=lib.STAFF, needchan=False)
-def cmd_badqs(bot, user, chan, realtarget, *args):
+               state.steptimer.cancel()
+       except Exception as e:
+               print "!!! steptimer.cancel(): %s %r" % (e,e)
+       state.steptimer = None
+       try:
+               state.nextquestiontimer.cancel()
+       except Exception as e:
+               print "!!! nextquestiontimer.cancel(): %s %r" % (e,e)
+       state.nextquestiontimer = None
+       return True
+
+@lib.hook(needchan=False)
+@lib.help("<reason>", "reports a bad question to the admins")
+@lib.argsGE(1)
+def badq(bot, user, chan, realtarget, *args):
+       lastqid = state.lastqid
+       curqid = state.curqid
+
+       reason = ' '.join(args)
+       state.db['badqs'].append([state.db['category'], lastqid, curqid, reason])
+       bot.msg(user, "Reported bad question.")
+
+@lib.hook(glevel=lib.STAFF, needchan=False)
+@lib.help(None, "shows a list of BADQ reports")
+def badqs(bot, user, chan, realtarget, *args):
        if len(state.db['badqs']) == 0:
                bot.msg(user, "No reports.")
 
        for i in range(len(state.db['badqs'])):
                try:
                        report = state.db['badqs'][i]
-                       bot.msg(user, "Report #%d: Q%d: %s" % (i, report[0], report[1]))
-                       question = state.db['questions'][int(report[0])]
-                       bot.msg(user, "- Question is: %s" % (question[0]))
-                       bot.msg(user, "- Answer is: %s" % (question[1]))
+                       bot.msg(user, "Report #%d: Cat=%s LastQ=%r CurQ=%r: %s" % (i, report[0], report[1], report[2], report[3]))
+                       try: lq = state.db['questions'][report[0]][int(report[1])]
+                       except Exception as e: lq = (None,None)
+                       try: cq = state.db['questions'][report[0]][int(report[2])]
+                       except Exception as e: cq = (None, None)
+                       bot.msg(user, "- Last: %s*%s" % (lq[0], lq[1]))
+                       bot.msg(user, "- Curr: %s*%s" % (cq[0], cq[1]))
                except Exception as e:
                        bot.msg(user, "- Exception: %r" % (e))
 
-@lib.hook('clearbadqs', glevel=lib.STAFF, needchan=False)
-def cmd_clearbadqs(bot, user, chan, realtarget, *args):
+@lib.hook(glevel=lib.STAFF, needchan=False)
+@lib.hook(None, "clears list of BADQ reports")
+def clearbadqs(bot, user, chan, realtarget, *args):
        state.db['badqs'] = []
        bot.msg(user, "Cleared reports.")
 
-@lib.hook('delbadq', glevel=lib.STAFF, needchan=False)
+@lib.hook(glevel=lib.STAFF, needchan=False)
+@lib.hook("<badqid>", "removes a BADQ report")
 @lib.argsEQ(1)
-def cmd_delbadq(bot, user, chan, realtarget, *args):
-       qid = int(args[0])
-       del state.db['badqs'][qid]
-       bot.msg(user, "Removed report #%d" % (qid))
+def delbadq(bot, user, chan, realtarget, *args):
+       try:
+               qid = int(args[0])
+               del state.db['badqs'][qid]
+               bot.msg(user, "Removed report #%d" % (qid))
+       except:
+               bot.msg(user, "Failed!")
 
-@lib.hook('rank', needchan=False)
-def cmd_rank(bot, user, chan, realtarget, *args):
+@lib.hook(needchan=False)
+@lib.help("[<user>]", "shows you or someone else's rank")
+def rank(bot, user, chan, realtarget, *args):
        if chan is not None and realtarget == chan.name: replyto = chan
        else: replyto = user
 
        if len(args) != 0: who = args[0]
        else: who = user
 
-       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)))
+       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)))
 
-@lib.hook('top10', needchan=False)
-def cmd_top10(bot, user, chan, realtarget, *args):
+@lib.hook(needchan=False)
+@lib.help(None, "shows top10 list")
+def top10(bot, user, chan, realtarget, *args):
        if len(state.db['ranks']) == 0:
                return bot.msg(state.db['chan'], "No one is ranked!")
 
        max = len(state.db['ranks'])
        if max > 10:
                max = 10
-       replylist = ', '.join(["%s (%s) %s" % (person(x), country(x, "unknown"), pts(x)) for x in range(max)])
-       bot.msg(state.db['chan'], "Top %d: %s" % (max, replylist))
+       replylist = ', '.join(["%s (%s) %s" % (person(x), country(x), pts(x)) for x in range(max)])
+       bot.msg(state.db['chan'], "Top 10: %s" % (replylist))
 
-@lib.hook('settarget', glevel=lib.ADMIN, needchan=False)
-def cmd_settarget(bot, user, chan, realtarget, *args):
+@lib.hook(glevel=lib.ADMIN, needchan=False)
+@lib.help("<target score>", "changes the target score for this round")
+def settarget(bot, user, chan, realtarget, *args):
        try:
                state.db['target'] = int(args[0])
                bot.msg(state.db['chan'], "Target has been changed to %s points!" % (state.db['target']))
@@ -506,8 +606,9 @@ def cmd_settarget(bot, user, chan, realtarget, *args):
                print e
                bot.msg(user, "Failed to set target.")
 
-@lib.hook('vote', needchan=False)
-def cmd_vote(bot, user, chan, realtarget, *args):
+@lib.hook(needchan=False)
+@lib.help("<option>", "votes for a trarget score for next round")
+def vote(bot, user, chan, realtarget, *args):
        if state.pointvote is not None:
                if int(args[0]) in state.voteamounts:
                        state.voteamounts[int(args[0])] += 1
@@ -517,41 +618,58 @@ def cmd_vote(bot, user, chan, realtarget, *args):
        else:
                bot.msg(user, "There's no vote in progress.")
 
-@lib.hook('maxmissed', glevel=lib.ADMIN, needchan=False)
-def cmd_maxmissed(bot, user, chan, realtarget, *args):
+@lib.hook(glevel=lib.ADMIN, needchan=False)
+@lib.help("<number>", "sets the max missed question before game stops")
+def maxmissed(bot, user, chan, realtarget, *args):
        try:
                state.db['maxmissedquestions'] = int(args[0])
                bot.msg(state.db['chan'], "Max missed questions before round ends has been changed to %s." % (state.db['maxmissedquestions']))
        except:
                bot.msg(user, "Failed to set maxmissed.")
 
-@lib.hook('hinttimer', glevel=lib.ADMIN, needchan=False)
-def cmd_hinttimer(bot, user, chan, realtarget, *args):
+@lib.hook(glevel=lib.ADMIN, needchan=False)
+@lib.help("<seconds>", "sets the time between hints")
+def hinttimer(bot, user, chan, realtarget, *args):
        try:
                state.db['hinttimer'] = float(args[0])
                bot.msg(state.db['chan'], "Time between hints has been changed to %s." % (state.db['hinttimer']))
        except:
                bot.msg(user, "Failed to set hint timer.")
 
-@lib.hook('hintnum', glevel=lib.ADMIN, needchan=False)
-def cmd_hintnum(bot, user, chan, realtarget, *args):
+@lib.hook(glevel=lib.ADMIN, needchan=False)
+@lib.help("<number>", "sets the number of hints given")
+def hintnum(bot, user, chan, realtarget, *args):
        try:
                state.db['hintnum'] = int(args[0])
                bot.msg(state.db['chan'], "Max number of hints has been changed to %s." % (state.db['hintnum']))
        except:
                bot.msg(user, "Failed to set hintnum.")
 
-@lib.hook('questionpause', glevel=lib.ADMIN, needchan=False)
-def cmd_questionpause(bot, user, chan, realtarget, *args):
+@lib.hook(glevel=lib.ADMIN, needchan=False)
+@lib.help("<seconds>", "sets the pause between questions")
+def questionpause(bot, user, chan, realtarget, *args):
        try:
                state.db['questionpause'] = float(args[0])
                bot.msg(state.db['chan'], "Pause between questions has been changed to %s." % (state.db['questionpause']))
        except:
                bot.msg(user, "Failed to set questionpause.")
 
-@lib.hook('findq', glevel=1, needchan=False)
-def cmd_findquestion(bot, user, chan, realtarget, *args):
-       matches = [str(i) for i in range(len(state.db['questions'])) if state.db['questions'][i][0] == ' '.join(args)] #TODO looser equality check
+@lib.hook(glevel=1, needchan=False)
+@lib.help("<full question>", "finds a qid given a complete question")
+def findq(bot, user, chan, realtarget, *args):
+       args = list(args)
+       if args[0][0] == "@":
+               cat = args.pop(0)[1:].lower()
+               questions = state.db['questions'][cat]
+       else:
+               questions = state.questions
+
+       if len(args) == 0:
+               bot.msg(user, "You need to specify the question.")
+               return
+
+       searchkey = ' '.join(args).lower()
+       matches = [str(i) for i in range(len(questions)) if questions[i][0].lower() == searchkey]
        if len(matches) > 1:
                bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
        elif len(matches) == 1:
@@ -559,18 +677,80 @@ def cmd_findquestion(bot, user, chan, realtarget, *args):
        else:
                bot.msg(user, "No match.")
 
-@lib.hook('delq', glevel=lib.STAFF, needchan=False)
-@lib.hook('deleteq', glevel=lib.STAFF, needchan=False)
-def cmd_deletequestion(bot, user, chan, realtarget, *args):
+@lib.hook(glevel=1, needchan=False)
+@lib.help("[@<category>] <regex>", "finds a qid given a regex or partial question")
+def findqre(bot, user, chan, realtarget, *args):
+       args = list(args)
+       if args[0][0] == "@":
+               cat = args.pop(0)[1:].lower()
+               questions = state.db['questions'][cat]
+       else:
+               questions = state.questions
+
+       if len(args) == 0:
+               bot.msg(user, "You need to specify a search string.")
+               return
+
+       searcher = re.compile(' '.join(args), re.IGNORECASE)
+       matches = [str(i) for i in range(len(questions)) if searcher.search(questions[i][0]) is not None]
+       if len(matches) > 25:
+               bot.msg(user, "Too many matches! (>25)")
+       elif len(matches) > 1:
+               bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
+       elif len(matches) == 1:
+               bot.msg(user, "One match: %s" % (matches[0]))
+       else:
+               bot.msg(user, "No match.")
+
+@lib.hook(glevel=lib.STAFF, needchan=False)
+@lib.help("[@<category>] <qid>", "displays the q*a for a qid", "category defaults to current")
+def showq(bot, user, chan, realtarget, *args):
+       args = list(args)
+       if args[0][0] == "@":
+               cat = args.pop(0)[1:].lower()
+               questions = state.db['questions'][cat]
+       else:
+               questions = state.questions
+
+       try:
+               qid = int(args[0])
+       except:
+               bot.msg(user, "Specify a numeric question ID.")
+               return
+       try:
+               q = questions[qid]
+       except:
+               bot.msg(user, "ID not valid.")
+               return
+       bot.msg(user, "%s: %s*%s" % (qid, q[0], q[1]))
+
+@lib.hook(('delq', 'deleteq'), glevel=lib.STAFF, needchan=False)
+@lib.help("[@<category>] <qid>", "removes a question from the database")
+def delq(bot, user, chan, realtarget, *args):
+       args = list(args)
+       if args[0][0] == "@":
+               cat = args.pop(0)[1:].lower()
+               questions = state.db['questions'][cat]
+       else:
+               questions = state.questions
+
        try:
-               backup = state.db['questions'][int(args[0])]
-               del state.db['questions'][int(args[0])]
+               backup = questions[int(args[0])]
+               del questions[int(args[0])]
                bot.msg(user, "Deleted %s*%s" % (backup[0], backup[1]))
        except:
-               bot.msg(user, "Couldn't delete that question.")
+               bot.msg(user, "Couldn't delete that question. %r" % (e))
+
+@lib.hook(glevel=lib.STAFF, needchan=False)
+@lib.help("[@<category>] <q>*<a>", "adds a question")
+def addq(bot, user, chan, realtarget, *args):
+       args = list(args)
+       if args[0][0] == "@":
+               cat = args.pop(0)[1:].lower()
+               questions = state.db['questions'][cat]
+       else:
+               questions = state.questions
 
-@lib.hook('addq', glevel=lib.STAFF, needchan=False)
-def cmd_addquestion(bot, user, chan, realtarget, *args):
        line = ' '.join([str(arg) for arg in args])
        linepieces = line.split('*')
        if len(linepieces) < 2:
@@ -578,39 +758,81 @@ def cmd_addquestion(bot, user, chan, realtarget, *args):
                return
        question = linepieces[0].strip()
        answer = linepieces[1].strip()
-       state.db['questions'].append([question, answer])
-       bot.msg(user, "Done. Question is #%s" % (len(state.db['questions'])-1))
-
-
-@lib.hook('triviahelp', needchan=False)
-def cmd_triviahelp(bot, user, chan, realtarget, *args):
-       bot.msg(user,             "START")
-       bot.msg(user,             "TOP10")
-       bot.msg(user,             "POINTS        [<user>]")
-       bot.msg(user,             "RANK          [<user>]")
-       bot.msg(user,             "BADQ          <id> <reason>")
+       questions.append([question, answer])
+       bot.msg(user, "Done. Question is #%s" % (len(questions)-1))
+
+@lib.hook(glevel=1, needchan=False)
+@lib.help("<category>", "change category")
+def setcat(bot, user, chan, realtarget, *args):
+       category = args[0].lower()
+       if category in state.db['questions']:
+               state.db['category'] = category
+               state.questions = state.db['questions'][category]
+               bot.msg(user, "Changed category to %s" % (category))
+       else:
+               bot.msg(user, "That category doesn't exist.")
+
+@lib.hook(needchan=False)
+@lib.help(None, "list categories")
+def listcats(bot, user, chan, realtarget, *args):
+       cats = ["%s (%d)" % (c, len(state.db['questions'][c])) for c in state.db['questions'].keys()]
+       bot.msg(user, "Categories: %s" % (', '.join(cats)))
+
+@lib.hook(glevel=lib.STAFF, needchan=False)
+@lib.help("<category>", "adds an empty category")
+def addcat(bot, user, chan, realtarget, *args):
+       category = args[0].lower()
+       if category not in state.db['questions']:
+               state.db['questions'][category] = []
+               bot.msg(user, "Added category %s" % (category))
+       else:
+               bot.msg(user, "Category already exists.")
+
+@lib.hook(glevel=lib.MANAGER, needchan=False)
+@lib.help("<category>", "deletes an entire category")
+def delcat(bot, user, chan, realtarget, *args):
+       category = args[0].lower()
+       if category == state.db['category']:
+               bot.msg(user, "Category currently in use!")
+       elif category in state.db['questions']:
+               length = len(state.db['questions'][category])
+               del state.db['questions'][category]
+               bot.msg(user, "Deleted category %s (%d questions)" % (category, length))
+       else:
+               bot.msg(user, "Category does not exist.")
+
+@lib.hook(needchan=False)
+def triviahelp(bot, user, chan, realtarget, *args):
+       bot.slowmsg(user,             "START")
+       bot.slowmsg(user,             "TOP10")
+       bot.slowmsg(user,             "POINTS        [<user>]")
+       bot.slowmsg(user,             "RANK          [<user>]")
+       bot.slowmsg(user,             "BADQ          <reason> (include info to identify question)")
        if user.glevel >= 1:
-               bot.msg(user,         "SKIP                            (>=KNOWN)")
-               bot.msg(user,         "STOP                            (>=KNOWN)")
-               bot.msg(user,         "FINDQ         <question>        (>=KNOWN)")
+               bot.slowmsg(user,         "SKIP                            (KNOWN)")
+               bot.slowmsg(user,         "STOP                            (KNOWN)")
+               bot.slowmsg(user,         "FINDQ         <full question>   (KNOWN)")
+               bot.slowmsg(user,         "FINDQRE       <regex>           (KNOWN)")
+               bot.slowmsg(user,         "SETNEXTID     <qid>             (KNOWN)")
                if user.glevel >= lib.STAFF:
-                       bot.msg(user,     "GIVE          <user> [<points>] (>=STAFF)")
-                       bot.msg(user,     "SETNEXT       <q>*<a>           (>=STAFF)")
-                       bot.msg(user,     "ADDQ          <q>*<a>           (>=STAFF)")
-                       bot.msg(user,     "DELETEQ       <q>*<a>           (>=STAFF)  [aka DELQ]")
-                       bot.msg(user,     "BADQS                           (>=STAFF)")
-                       bot.msg(user,     "CLEARBADQS                      (>=STAFF)")
-                       bot.msg(user,     "DELBADQ       <reportid>        (>=STAFF)")
+                       bot.slowmsg(user,     "GIVE          <user> [<points>] (STAFF)")
+                       bot.slowmsg(user,     "SETNEXT       <q>*<a>           (STAFF)")
+                       bot.slowmsg(user,     "ADDQ          <q>*<a>           (STAFF)")
+                       bot.slowmsg(user,     "DELQ          <q>*<a>           (STAFF)  [aka DELETEQ]")
+                       bot.slowmsg(user,     "SHOWQ         <qid>             (STAFF)")
+                       bot.slowmsg(user,     "BADQS                           (STAFF)")
+                       bot.slowmsg(user,     "CLEARBADQS                      (STAFF)")
+                       bot.slowmsg(user,     "DELBADQ       <reportid>        (STAFF)")
                        if user.glevel >= lib.ADMIN:
-                               bot.msg(user, "SETTARGET     <points>          (>=ADMIN)")
-                               bot.msg(user, "MAXMISSED     <questions>       (>=ADMIN)")
-                               bot.msg(user, "HINTTIMER     <float seconds>   (>=ADMIN)")
-                               bot.msg(user, "HINTNUM       <hints>           (>=ADMIN)")
-                               bot.msg(user, "QUESTIONPAUSE <float seconds>   (>=ADMIN)")
+                               bot.slowmsg(user, "SETTARGET     <points>          (ADMIN)")
+                               bot.slowmsg(user, "MAXMISSED     <questions>       (ADMIN)")
+                               bot.slowmsg(user, "HINTTIMER     <float seconds>   (ADMIN)")
+                               bot.slowmsg(user, "HINTNUM       <hints>           (ADMIN)")
+                               bot.slowmsg(user, "QUESTIONPAUSE <float seconds>   (ADMIN)")
 
 @lib.hooknum(417)
 def num_417(bot, textline):
-       bot.msg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
+#      bot.fastmsg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
        state.nextquestion(qskipped=False, skipwait=True)
 
 @lib.hooknum(332)
@@ -628,8 +850,8 @@ def num_TOPIC(bot, textline):
                        "%s (%s)" % (person(x), pts(x))
                        for x in range(3) if x < len(state.db['ranks'])
                ]),
-               'top3c': ' '.join([
-                       "%s (%s, %s)" % (person(x), pts(x), country(x))
+               'top3c': ', '.join([
+                       "%s (%s) %s" % (person(x), country(x), pts(x))
                        for x in range(3) if x < len(state.db['ranks'])
                ]),
                'top10': ' '.join([
@@ -640,6 +862,8 @@ def num_TOPIC(bot, textline):
                        "%s (%s, %s)" % (person(x), pts(x), country(x))
                        for x in range(10) if x < len(state.db['ranks'])
                ]),
+               'lastwinner': state.db['lastwinner'],
+               'lastwon': time.strftime("%b %d", time.gmtime(state.db['lastwon'])),
                'target': state.db['target'],
        }
        if gottopic != formatted:
@@ -658,11 +882,12 @@ def specialQuestion(oldq):
                randnum2 = random.randrange(0, 11)
                newq[0] = "What is %d + %d?" % (randnum1, randnum2)
                newq[1] = spellout(randnum1+randnum2)
+       else: pass #default to not modifying
        return newq
 
 def spellout(num):
        return [
-               "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", 
+               "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
                "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
                "sixteen", "seventeen", "eighteen", "nineteen", "twenty"
        ][num]