X-Git-Url: https://jfr.im/git/erebus.git/blobdiff_plain/67faf5d7f29388269939ad5fb2f40caac6982529..a62d0d18bbb5926d22df18db5eba53eb21a10817:/modules/trivia.py diff --git a/modules/trivia.py b/modules/trivia.py index 18e2e6b..cb4b407 100644 --- a/modules/trivia.py +++ b/modules/trivia.py @@ -6,8 +6,9 @@ modinfo = { 'author': 'Erebus Team', 'license': 'public domain', - 'compatible': [1], # compatible module API versions - 'depends': ['userinfo'], # other modules required to work properly? + 'compatible': [1,2], + 'depends': ['userinfo'], + 'softdeps': ['help'], } # preamble @@ -71,6 +72,7 @@ class TriviaState(object): 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 @@ -100,20 +102,29 @@ 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 - self.savedb() + try: + self.steptimer.cancel() + self.steptimer = None + except: pass + try: + self.nextquestiontimer.cancel() + self.nextquestiontimer = None + except: pass +#TODO remove if the replacement works +# 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 +# self.savedb() 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=(',', ': ')) dbjson = json.dumps(self.db) if len(dbjson) > 0: - os.rename(self.questionfile, self.questionfile+".autobak") + os.rename(self.questionfile, self.questionfile+".auto.bak") tmpfn = os.tempnam('.', 'trivia') try: f = open(tmpfn, "w") @@ -122,7 +133,7 @@ class TriviaState(object): os.rename(tmpfn, self.questionfile) return True except: #if something happens, restore the backup - os.rename(self.questionfile+".autobak", self.questionfile) + os.rename(self.questionfile+".auto.bak", self.questionfile) try: os.unlink(tmpfn) except OSError: # temp file is already gone @@ -269,13 +280,13 @@ 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)) return - self.savedb() - if skipwait: self._nextquestion(iteration) else: @@ -288,8 +299,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 @@ -312,7 +323,10 @@ class TriviaState(object): qary = nextq[0].split(None) qtext += " " for qword in qary: - qtext += "\00304,01"+qword+"\00301,01"+chr(random.randrange(0x61,0x7A)) #a-z + 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 @@ -384,11 +398,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() @@ -398,9 +412,9 @@ def trivia_checkanswer(bot, user, chan, *args): if state.checkanswer(line): state.curq = None 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))) + 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))) + 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() @@ -446,7 +460,7 @@ def give(bot, user, chan, realtarget, *args): def setnextid(bot, user, chan, realtarget, *args): try: qid = int(args[0]) - state.nextq = state.db['questions'][qid] + state.nextq = state.questions[qid] if user.glevel >= lib.STAFF: respstr = "Done. Next question is: %s" % (state.nextq[0]) else: @@ -523,7 +537,7 @@ def badq(bot, user, chan, realtarget, *args): curqid = state.curqid reason = ' '.join(args) - state.db['badqs'].append([lastqid, curqid, reason]) + state.db['badqs'].append([state.db['category'], lastqid, curqid, reason]) bot.msg(user, "Reported bad question.") @lib.hook(glevel=lib.STAFF, needchan=False) @@ -535,10 +549,10 @@ def badqs(bot, user, chan, realtarget, *args): for i in range(len(state.db['badqs'])): try: report = state.db['badqs'][i] - bot.msg(user, "Report #%d: LastQ=%r CurQ=%r: %s" % (i, report[0], report[1], report[2])) - try: lq = state.db['questions'][int(report[0])] + 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'][int(report[1])] + 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])) @@ -571,7 +585,7 @@ def rank(bot, user, chan, realtarget, *args): 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(needchan=False) @lib.help(None, "shows top10 list") @@ -651,12 +665,19 @@ def questionpause(bot, user, chan, realtarget, *args): @lib.hook(glevel=1, needchan=False) @lib.help("", "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(state.db['questions'])) if state.db['questions'][i][0].lower() == searchkey] + 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: @@ -665,14 +686,21 @@ def findq(bot, user, chan, realtarget, *args): bot.msg(user, "No match.") @lib.hook(glevel=1, needchan=False) -@lib.help("", "finds a qid given a regex or partial question") +@lib.help("[@] ", "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(state.db['questions'])) if searcher.search(state.db['questions'][i][0]) is not None] + 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: @@ -683,33 +711,54 @@ def findqre(bot, user, chan, realtarget, *args): bot.msg(user, "No match.") @lib.hook(glevel=lib.STAFF, needchan=False) -@lib.help("", "displays the q*a for a qid") +@lib.help("[@] ", "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 = state.db['questions'][qid] + 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("", "removes a question from the database") +@lib.help("[@] ", "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. %r" % (e)) @lib.hook(glevel=lib.STAFF, needchan=False) -@lib.help("*", "adds a question") +@lib.help("[@] *", "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 + line = ' '.join([str(arg) for arg in args]) linepieces = line.split('*') if len(linepieces) < 2: @@ -717,9 +766,48 @@ def addq(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)) + questions.append([question, answer]) + bot.msg(user, "Done. Question is #%s" % (len(questions)-1)) + +@lib.hook(glevel=1, needchan=False) +@lib.help("", "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("", "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("", "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):