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