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