]> jfr.im git - erebus.git/blame - modules/trivia.py
fixed bug, ctlmod.reloadmod needed to return success
[erebus.git] / modules / trivia.py
CommitLineData
80d02bd8 1# Erebus IRC bot - Author: Erebus Team
c695f740 2# trivia module
80d02bd8 3# This file is released into the public domain; see http://unlicense.org/
4
5# module info
6modinfo = {
7 'author': 'Erebus Team',
8 'license': 'public domain',
9 'compatible': [1], # compatible module API versions
10 'depends': [], # other modules required to work properly?
11}
12
13# preamble
14import modlib
15lib = modlib.modlib(__name__)
16def modstart(parent, *args, **kwargs):
9557ee54 17 state.parent = parent
80d02bd8 18 return lib.modstart(parent, *args, **kwargs)
19def modstop(*args, **kwargs):
c0eee1b4 20 global state
fadbf980 21 stop()
77c61775 22 state.closeshop()
80d02bd8 23 del state
24 return lib.modstop(*args, **kwargs)
25
26# module code
b5c89dfb 27import json, random, threading, re, time
b16b8c05 28
c0eee1b4 29try:
c53f6514 30 import twitter
31except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
c0eee1b4 32
b16b8c05 33def findnth(haystack, needle, n): #http://stackoverflow.com/a/1884151
34 parts = haystack.split(needle, n+1)
35 if len(parts)<=n+1:
36 return -1
37 return len(haystack)-len(parts[-1])-len(needle)
80d02bd8 38
39class TriviaState(object):
c53f6514 40 def __init__(self, questionfile, parent=None, pointvote=False):
77c61775 41 self.parent = parent
80d02bd8 42 self.questionfile = questionfile
43 self.db = json.load(open(questionfile, "r"))
9557ee54 44 self.chan = self.db['chan']
45 self.curq = None
c695f740 46 self.nextq = None
b16b8c05 47 self.steptimer = None
48 self.hintstr = None
49 self.hintanswer = None
77c61775 50 self.hintsgiven = 0
b16b8c05 51 self.revealpossibilities = None
77c61775 52 self.gameover = False
c0eee1b4 53 self.missedquestions = 0
80d02bd8 54
c53f6514 55 if pointvote:
56 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']])))
57 self.getchan().msg("You have %s seconds." % (self.db['votetimer']))
58 self.voteamounts = dict([(x, 0) for x in self.db['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
59 self.pointvote = threading.Timer(self.db['votetimer'], self.endPointVote)
60 self.pointvote.start()
61 else:
62 self.pointvote = None
63
80d02bd8 64 def __del__(self):
77c61775 65 self.closeshop()
66 def closeshop(self):
b16b8c05 67 if threading is not None and threading._Timer is not None and isinstance(self.steptimer, threading._Timer):
68 self.steptimer.cancel()
c695f740 69 if json is not None and json.dump is not None:
6374d61f 70 json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
80d02bd8 71
fadbf980 72 def getchan(self):
73 return self.parent.channel(self.chan)
74 def getbot(self):
75 return self.getchan().bot
76
b16b8c05 77 def nexthint(self, hintnum):
b16b8c05 78 answer = self.hintanswer
79
b5c89dfb 80 if self.hintstr is None or self.revealpossibilities is None or self.reveal is None:
b16b8c05 81 self.hintstr = list(re.sub(r'[a-zA-Z0-9]', '*', answer))
82 self.revealpossibilities = range(''.join(self.hintstr).count('*'))
b5c89dfb 83 self.reveal = int(''.join(self.hintstr).count('*') * (7/24.0))
b16b8c05 84
b5c89dfb 85 for i in range(self.reveal):
b16b8c05 86 revealcount = random.choice(self.revealpossibilities)
87 revealloc = findnth(''.join(self.hintstr), '*', revealcount)
88 self.revealpossibilities.remove(revealcount)
89 self.hintstr[revealloc] = answer[revealloc]
6374d61f 90 self.parent.channel(self.chan).bot.msg(self.chan, "\00304,01Here's a hint: %s" % (''.join(self.hintstr)))
b16b8c05 91
77c61775 92 self.hintsgiven += 1
93
c4763e66 94 if hintnum < self.db['hintnum']:
95 self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[hintnum+1])
b16b8c05 96 self.steptimer.start()
97 else:
c4763e66 98 self.steptimer = threading.Timer(self.db['hinttimer'], self.nextquestion, args=[True])
b16b8c05 99 self.steptimer.start()
100
77c61775 101 def doGameOver(self):
102 def msg(line): self.getbot().msg(self.getchan(), line)
103 def person(num): return self.db['users'][self.db['ranks'][num]]['realnick']
104 def pts(num): return self.db['users'][self.db['ranks'][num]]['points']
c0eee1b4 105 winner = person(0)
77c61775 106 try:
107 msg("\00312THE GAME IS OVER!!!")
108 msg("THE WINNER IS: %s (%s)" % (person(0), pts(0)))
109 msg("2ND PLACE: %s (%s)" % (person(1), pts(1)))
110 msg("3RD PLACE: %s (%s)" % (person(2), pts(2)))
111 [msg("%dth place: %s (%s)" % (i+1, person(i), pts(i))) for i in range(3,10)]
112 except IndexError: pass
c0eee1b4 113 except Exception as e: msg("DERP! %r" % (e))
114
77c61775 115 self.db['users'] = {}
116 self.db['ranks'] = []
117 stop()
118 self.closeshop()
c0eee1b4 119
c53f6514 120 try:
c0eee1b4 121 t = twitter.Twitter(auth=twitter.OAuth(self.getbot().parent.cfg.get('trivia', 'token'),
122 self.getbot().parent.cfg.get('trivia', 'token_sec'),
123 self.getbot().parent.cfg.get('trivia', 'con'),
124 self.getbot().parent.cfg.get('trivia', 'con_sec')))
125 t.statuses.update(status="Round is over! The winner was %s" % (winner))
c53f6514 126 except: pass #don't care if errors happen updating twitter.
127
128 self.__init__(self.questionfile, self.parent, True)
129
130 def endPointVote(self):
131 self.getchan().msg("Voting has ended!")
132 votelist = sorted(self.voteamounts.items(), key=lambda item: item[1]) #sort into list of tuples: [(option, number_of_votes), ...]
133 for i in range(len(votelist)-1):
134 item = votelist[i]
135 self.getchan().msg("%s place: %s (%s votes)" % (len(votelist)-i, item[0], item[1]))
136 self.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist[-1][0], votelist[-1][1]))
c0eee1b4 137
c53f6514 138 self.db['target'] = votelist[-1][0]
139 self.pointvote = None
77c61775 140
38b29993 141 self.nextquestion() #start the game!
142
b5c89dfb 143 def nextquestion(self, qskipped=False, iteration=0):
77c61775 144 if self.gameover == True:
145 return self.doGameOver()
fadbf980 146 if qskipped:
c53f6514 147 self.getchan().msg("\00304Fail! The correct answer was: %s" % (self.hintanswer))
c0eee1b4 148 self.missedquestions += 1
149 else:
150 self.missedquestions = 0
fadbf980 151
b16b8c05 152 if isinstance(self.steptimer, threading._Timer):
153 self.steptimer.cancel()
c0eee1b4 154
b16b8c05 155 self.hintstr = None
77c61775 156 self.hintsgiven = 0
b16b8c05 157 self.revealpossibilities = None
b5c89dfb 158 self.reveal = None
b16b8c05 159
c4763e66 160 if self.missedquestions > self.db['maxmissedquestions']:
c0eee1b4 161 stop()
162 self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game.")
b16b8c05 163
c695f740 164 if state.nextq is not None:
165 nextq = state.nextq
c695f740 166 state.nextq = None
167 else:
168 nextq = random.choice(self.db['questions'])
b5c89dfb 169
170 if nextq['question'][0] == "!":
171 nextq = specialQuestion(nextq)
172
173 if iteration < 10 and 'lastasked' in nextq and nextq['lastasked'] - time.time() < 24*60*60:
174 return self.nextquestion(iteration=iteration+1) #short-circuit to pick another question
175 nextq['lastasked'] = time.time()
176
177 nextq['answer'] = nextq['answer'].lower()
c695f740 178
6374d61f 179 qtext = "\00304,01Next up: "
c695f740 180 qary = nextq['question'].split(None)
181 for qword in qary:
6374d61f 182 qtext += "\00304,01"+qword+"\00301,01"+chr(random.randrange(0x61,0x7A)) #a-z
fadbf980 183 self.getbot().msg(self.chan, qtext)
80d02bd8 184
b5c89dfb 185 self.curq = nextq
186
c0eee1b4 187 if isinstance(self.curq['answer'], basestring): self.hintanswer = self.curq['answer']
188 else: self.hintanswer = random.choice(self.curq['answer'])
189
c4763e66 190 self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[1])
b16b8c05 191 self.steptimer.start()
192
80d02bd8 193 def checkanswer(self, answer):
9557ee54 194 if self.curq is None:
195 return False
196 elif isinstance(self.curq['answer'], basestring):
80d02bd8 197 return answer.lower() == self.curq['answer']
198 else: # assume it's a list or something.
199 return answer.lower() in self.curq['answer']
77c61775 200
c53f6514 201 def addpoint(self, user_obj, count=1):
202 user_nick = str(user_obj)
203 user = user_nick.lower() # save this separately as we use both
80d02bd8 204 if user in self.db['users']:
205 self.db['users'][user]['points'] += count
206 else:
c53f6514 207 self.db['users'][user] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
9557ee54 208 self.db['ranks'].append(user)
80d02bd8 209
c53f6514 210 self.db['ranks'].sort(key=lambda nick: state.db['users'][nick]['points'], reverse=True) #re-sort ranks, rather than dealing with anything more efficient
6374d61f 211 for i in range(0, len(self.db['ranks'])):
212 nick = self.db['ranks'][i]
213 self.db['users'][nick]['rank'] = i
77c61775 214
215 if self.db['users'][user]['points'] >= state.db['target']:
216 self.gameover = True
217
80d02bd8 218 return self.db['users'][user]['points']
219
220 def points(self, user):
9557ee54 221 user = str(user).lower()
80d02bd8 222 if user in self.db['users']:
223 return self.db['users'][user]['points']
224 else:
225 return 0
226
227 def rank(self, user):
c695f740 228 user = str(user).lower()
fadbf980 229 if user in self.db['users']:
230 return self.db['users'][user]['rank']+1
231 else:
232 return len(self.db['users'])+1
77c61775 233
c695f740 234 def targetuser(self, user):
77c61775 235 if len(self.db['ranks']) == 0: return "no one is ranked!"
236
c695f740 237 user = str(user).lower()
fadbf980 238 if user in self.db['users']:
239 rank = self.db['users'][user]['rank']
240 if rank == 0:
241 return "you're in the lead!"
242 else:
243 return self.db['ranks'][rank-1]
c695f740 244 else:
fadbf980 245 return self.db['ranks'][-1]
c695f740 246 def targetpoints(self, user):
77c61775 247 if len(self.db['ranks']) == 0: return 0
248
c695f740 249 user = str(user).lower()
fadbf980 250 if user in self.db['users']:
251 rank = self.db['users'][user]['rank']
252 if rank == 0:
253 return "N/A"
254 else:
255 return self.db['users'][self.db['ranks'][rank-1]]['points']
c695f740 256 else:
fadbf980 257 return self.db['users'][self.db['ranks'][-1]]['points']
80d02bd8 258
c695f740 259state = TriviaState("/home/jrunyon/erebus/modules/trivia.json") #TODO get path from config
9557ee54 260
80d02bd8 261@lib.hookchan(state.db['chan'])
262def trivia_checkanswer(bot, user, chan, *args):
80d02bd8 263 line = ' '.join([str(arg) for arg in args])
264 if state.checkanswer(line):
6374d61f 265 bot.msg(chan, "\00312%s\003 has it! The answer was \00312%s\003. New score: %d. Rank: %d. Target: %s (%s)." % (user, line, state.addpoint(user), state.rank(user), state.targetuser(user), state.targetpoints(user)))
77c61775 266 if state.hintsgiven == 0:
6374d61f 267 bot.msg(chan, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user)))
9557ee54 268 state.nextquestion()
80d02bd8 269
f6252f1c 270@lib.hook('points', needchan=False)
80d02bd8 271def cmd_points(bot, user, chan, realtarget, *args):
c695f740 272 if chan == realtarget: replyto = chan
80d02bd8 273 else: replyto = user
274
275 if len(args) != 0: who = args[0]
276 else: who = user
277
278 bot.msg(replyto, "%s has %d points." % (who, state.points(who)))
279
f6252f1c 280@lib.hook('give', clevel=lib.OP, needchan=False)
80d02bd8 281@lib.argsGE(1)
282def cmd_give(bot, user, chan, realtarget, *args):
80d02bd8 283 whoto = args[0]
c695f740 284 if len(args) > 1:
285 numpoints = int(args[1])
286 else:
287 numpoints = 1
288 balance = state.addpoint(whoto, numpoints)
fadbf980 289
c695f740 290 bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance))
291
f6252f1c 292@lib.hook('setnext', clevel=lib.OP, needchan=False)
c695f740 293@lib.argsGE(1)
294def cmd_setnext(bot, user, chan, realtarget, *args):
295 line = ' '.join([str(arg) for arg in args])
296 linepieces = line.split('*')
b5c89dfb 297 if len(linepieces) < 2:
298 bot.msg(user, "Error: need <question>*<answer>")
299 return
c695f740 300 question = linepieces[0].strip()
301 answer = linepieces[1].strip()
302 state.nextq = {'question':question,'answer':answer}
303 bot.msg(user, "Done.")
304
f6252f1c 305@lib.hook('skip', clevel=lib.KNOWN, needchan=False)
c695f740 306def cmd_skip(bot, user, chan, realtarget, *args):
c0eee1b4 307 state.nextquestion(True)
c695f740 308
f6252f1c 309@lib.hook('start', needchan=False)
c695f740 310def cmd_start(bot, user, chan, realtarget, *args):
311 if chan == realtarget: replyto = chan
312 else: replyto = user
313
c53f6514 314 if state.curq is None and state.pointvote is None:
c695f740 315 state.nextquestion()
c53f6514 316 elif state.pointvote is not None:
317 bot.msg(replyto, "There's a vote in progress!")
c695f740 318 else:
319 bot.msg(replyto, "Game is already started!")
320
6374d61f 321#FIXME @lib.hook('stop', clevel=lib.KNOWN, needchan=False)
322@lib.hook('stop', needchan=False) #FIXME
c695f740 323def cmd_stop(bot, user, chan, realtarget, *args):
fadbf980 324 if stop():
325 bot.msg(state.chan, "Game stopped by %s" % (user))
326 else:
327 bot.msg(user, "Game isn't running.")
c695f740 328
fadbf980 329def stop():
c695f740 330 if state.curq is not None:
331 state.curq = None
c0eee1b4 332 try:
b16b8c05 333 state.steptimer.cancel()
c0eee1b4 334 except Exception as e:
335 print "!!! steptimer.cancel(): e"
fadbf980 336 return True
c695f740 337 else:
fadbf980 338 return False
80d02bd8 339
f6252f1c 340@lib.hook('rank', needchan=False)
80d02bd8 341def cmd_rank(bot, user, chan, realtarget, *args):
c695f740 342 if chan == realtarget: replyto = chan
80d02bd8 343 else: replyto = user
344
c695f740 345 if len(args) != 0: who = args[0]
346 else: who = user
347
77c61775 348 bot.msg(replyto, "%s is in %d place (%s points). Target is: %s (%s points)." % (who, state.rank(who), state.points(who), state.targetuser(who), state.targetpoints(who)))
fadbf980 349
f6252f1c 350@lib.hook('top10', needchan=False)
fadbf980 351def cmd_top10(bot, user, chan, realtarget, *args):
77c61775 352 if len(state.db['ranks']) == 0:
353 return bot.msg(state.db['chan'], "No one is ranked!")
fadbf980 354
355 replylist = []
356 for nick in state.db['ranks'][0:10]:
357 user = state.db['users'][nick]
77c61775 358 replylist.append("%s (%s)" % (user['realnick'], user['points']))
359 bot.msg(state.db['chan'], ', '.join(replylist))
360
f6252f1c 361@lib.hook('settarget', clevel=lib.MASTER, needchan=False)
77c61775 362def cmd_settarget(bot, user, chan, realtarget, *args):
363 try:
364 state.db['target'] = int(args[0])
365 bot.msg(state.db['chan'], "Target has been changed to %s points!" % (state.db['target']))
38b29993 366
367 if state.votetimer is not None:
368 state.votetimer.cancel()
369 state.votetimer = None
370 bot.msg(state.db['chan'], "Vote has been cancelled!")
77c61775 371 except:
372 bot.msg(user, "Failed to set target.")
373
38b29993 374@lib.hook('vote', needchan=False)
375def cmd_vote(bot, user, chan, realtarget, *args):
376 if state.votetimer is not None:
377 if int(args[0]) in state.voteamounts:
378 state.voteamounts[int(args[0])] += 1
379 bot.msg(user, "Your vote has been recorded.")
380 else:
381 bot.msg(user, "Sorry - that's not an option!")
382 else:
383 bot.msg(user, "There's no vote in progress.")
384
c4763e66 385@lib.hook('maxmissed', clevel=lib.MASTER, needchan=False)
386def cmd_maxmissed(bot, user, chan, realtarget, *args):
387 try:
388 state.db['maxmissedquestions'] = int(args[0])
389 bot.msg(state.db['chan'], "Max missed questions before round ends has been changed to %s." % (state.db['maxmissedquestions']))
390 except:
391 bot.msg(user, "Failed to set maxmissed.")
392
393@lib.hook('hinttimer', clevel=lib.MASTER, needchan=False)
394def cmd_hinttimer(bot, user, chan, realtarget, *args):
395 try:
396 state.db['hinttimer'] = float(args[0])
397 bot.msg(state.db['chan'], "Time between hints has been changed to %s." % (state.db['hinttimer']))
398 except:
399 bot.msg(user, "Failed to set hint timer.")
400
401@lib.hook('hintnum', clevel=lib.MASTER, needchan=False)
402def cmd_hintnum(bot, user, chan, realtarget, *args):
403 try:
404 state.db['hintnum'] = int(args[0])
405 bot.msg(state.db['chan'], "Max number of hints has been changed to %s." % (state.db['hintnum']))
406 except:
407 bot.msg(user, "Failed to set hintnum.")
408
409@lib.hook('findq', clevel=lib.KNOWN, needchan=False)
410def cmd_findquestion(bot, user, chan, realtarget, *args):
411 matches = [str(i) for i in range(len(state.db['questions'])) if state.db['questions'][i]['question'] == ' '.join(args)] #FIXME: looser equality check
412 if len(matches) > 1:
413 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
414 elif len(matches) == 1:
415 bot.msg(user, "One match: %s" % (matches[0]))
416 else:
417 bot.msg(user, "No match.")
418
419@lib.hook('delq', clevel=lib.OP, needchan=False)
420@lib.hook('deleteq', clevel=lib.OP, needchan=False)
421def cmd_deletequestion(bot, user, chan, realtarget, *args):
422 try:
423 backup = state.db['questions'][int(args[0])]
424 del state.db['questions'][int(args[0])]
425 bot.msg(user, "Deleted %s*%s" % (backup['question'], backup['answer']))
426 except:
427 bot.msg(user, "Couldn't delete that question.")
428
429@lib.hook('addq', clevel=lib.OP, needchan=False)
430def cmd_addquestion(bot, user, chan, realtarget, *args):
431 line = ' '.join([str(arg) for arg in args])
432 linepieces = line.split('*')
433 if len(linepieces) < 2:
434 bot.msg(user, "Error: need <question>*<answer>")
435 return
436 question = linepieces[0].strip()
437 answer = linepieces[1].strip()
438 state.db['questions'].append({'question':question,'answer':answer})
439 bot.msg(user, "Done. Question is #%s" % (len(state.db['questions'])-1))
440
441
f6252f1c 442@lib.hook('triviahelp', needchan=False)
77c61775 443def cmd_triviahelp(bot, user, chan, realtarget, *args):
c4763e66 444 bot.msg(user, "START")
445 bot.msg(user, "TOP10")
446 bot.msg(user, "POINTS [<user>]")
447 bot.msg(user, "RANK [<user>]")
77c61775 448 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.KNOWN:
c4763e66 449 bot.msg(user, "SKIP (>=KNOWN )")
450 bot.msg(user, "STOP (>=KNOWN )")
451 bot.msg(user, "FINDQ <question> (>=KNOWN )")
77c61775 452 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.OP:
c4763e66 453 bot.msg(user, "GIVE <user> [<points>] (>=OP )")
454 bot.msg(user, "SETNEXT <q>*<a> (>=OP )")
455 bot.msg(user, "ADDQ <q>*<a> (>=OP )")
456 bot.msg(user, "DELETEQ <q>*<a> (>=OP ) [aka DELQ]")
77c61775 457 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.MASTER:
c4763e66 458 bot.msg(user, "SETTARGET <points> (>=MASTER)")
459 bot.msg(user, "MAXMISSED <questions> (>=MASTER)")
460 bot.msg(user, "HINTTIMER <float seconds> (>=MASTER)")
461 bot.msg(user, "HINTNUM <hints> (>=MASTER)")
b5c89dfb 462
6374d61f 463@lib.hooknum(417)
464def num_417(bot, textline):
465 bot.msg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
466 state.nextquestion(False)
467
b5c89dfb 468
469def specialQuestion(oldq):
470 newq = {'question': oldq['question'], 'answer': oldq['answer']}
471 qtype = oldq['question'].upper()
472
473 if qtype == "!MONTH":
474 newq['question'] = "What month is it currently (in UTC)?"
475 newq['answer'] = time.strftime("%B").lower()
476 elif qtype == "!MATH+":
477 randnum1 = random.randrange(0, 11)
478 randnum2 = random.randrange(0, 11)
479 newq['question'] = "What is %d + %d?" % (randnum1, randnum2)
480 newq['answer'] = spellout(randnum1+randnum2)
481 return newq
482
483def spellout(num):
484 return [
485 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
486 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
487 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"
488 ][num]