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