]> jfr.im git - erebus.git/blob - modules/trivia.py
b4c0785b16c456f6a8e094427cea5425667871ac
[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
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 = questionfile
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 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
64 def __del__(self):
65 self.closeshop()
66 def closeshop(self):
67 if threading is not None and threading._Timer is not None and isinstance(self.steptimer, threading._Timer):
68 self.steptimer.cancel()
69 if json is not None and json.dump is not None:
70 json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
71
72 def getchan(self):
73 return self.parent.channel(self.chan)
74 def getbot(self):
75 return self.getchan().bot
76
77 def nexthint(self, hintnum):
78 answer = self.hintanswer
79
80 if self.hintstr is None or self.revealpossibilities is None or self.reveal is None:
81 self.hintstr = list(re.sub(r'[a-zA-Z0-9]', '*', answer))
82 self.revealpossibilities = range(''.join(self.hintstr).count('*'))
83 self.reveal = int(''.join(self.hintstr).count('*') * (7/24.0))
84
85 for i in range(self.reveal):
86 revealcount = random.choice(self.revealpossibilities)
87 revealloc = findnth(''.join(self.hintstr), '*', revealcount)
88 self.revealpossibilities.remove(revealcount)
89 self.hintstr[revealloc] = answer[revealloc]
90 self.parent.channel(self.chan).bot.msg(self.chan, "\00304,01Here's a hint: %s" % (''.join(self.hintstr)))
91
92 self.hintsgiven += 1
93
94 if hintnum < self.db['hintnum']:
95 self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[hintnum+1])
96 self.steptimer.start()
97 else:
98 self.steptimer = threading.Timer(self.db['hinttimer'], self.nextquestion, args=[True])
99 self.steptimer.start()
100
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']
105 winner = person(0)
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
113 except Exception as e: msg("DERP! %r" % (e))
114
115 self.db['users'] = {}
116 self.db['ranks'] = []
117 stop()
118 self.closeshop()
119
120 try:
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))
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]))
137
138 self.db['target'] = votelist[-1][0]
139 self.pointvote = None
140
141 def nextquestion(self, qskipped=False, iteration=0):
142 if self.gameover == True:
143 return self.doGameOver()
144 if qskipped:
145 self.getchan().msg("\00304Fail! The correct answer was: %s" % (self.hintanswer))
146 self.missedquestions += 1
147 else:
148 self.missedquestions = 0
149
150 if isinstance(self.steptimer, threading._Timer):
151 self.steptimer.cancel()
152
153 self.hintstr = None
154 self.hintsgiven = 0
155 self.revealpossibilities = None
156 self.reveal = None
157
158 if self.missedquestions > self.db['maxmissedquestions']:
159 stop()
160 self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game.")
161
162 if state.nextq is not None:
163 nextq = state.nextq
164 state.nextq = None
165 else:
166 nextq = random.choice(self.db['questions'])
167
168 if nextq['question'][0] == "!":
169 nextq = specialQuestion(nextq)
170
171 if iteration < 10 and 'lastasked' in nextq and nextq['lastasked'] - time.time() < 24*60*60:
172 return self.nextquestion(iteration=iteration+1) #short-circuit to pick another question
173 nextq['lastasked'] = time.time()
174
175 nextq['answer'] = nextq['answer'].lower()
176
177 qtext = "\00304,01Next up: "
178 qary = nextq['question'].split(None)
179 for qword in qary:
180 qtext += "\00304,01"+qword+"\00301,01"+chr(random.randrange(0x61,0x7A)) #a-z
181 self.getbot().msg(self.chan, qtext)
182
183 self.curq = nextq
184
185 if isinstance(self.curq['answer'], basestring): self.hintanswer = self.curq['answer']
186 else: self.hintanswer = random.choice(self.curq['answer'])
187
188 self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[1])
189 self.steptimer.start()
190
191 def checkanswer(self, answer):
192 if self.curq is None:
193 return False
194 elif isinstance(self.curq['answer'], basestring):
195 return answer.lower() == self.curq['answer']
196 else: # assume it's a list or something.
197 return answer.lower() in self.curq['answer']
198
199 def addpoint(self, user_obj, count=1):
200 user_nick = str(user_obj)
201 user = user_nick.lower() # save this separately as we use both
202 if user in self.db['users']:
203 self.db['users'][user]['points'] += count
204 else:
205 self.db['users'][user] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
206 self.db['ranks'].append(user)
207
208 self.db['ranks'].sort(key=lambda nick: state.db['users'][nick]['points'], reverse=True) #re-sort ranks, rather than dealing with anything more efficient
209 for i in range(0, len(self.db['ranks'])):
210 nick = self.db['ranks'][i]
211 self.db['users'][nick]['rank'] = i
212
213 if self.db['users'][user]['points'] >= state.db['target']:
214 self.gameover = True
215
216 return self.db['users'][user]['points']
217
218 def points(self, user):
219 user = str(user).lower()
220 if user in self.db['users']:
221 return self.db['users'][user]['points']
222 else:
223 return 0
224
225 def rank(self, user):
226 user = str(user).lower()
227 if user in self.db['users']:
228 return self.db['users'][user]['rank']+1
229 else:
230 return len(self.db['users'])+1
231
232 def targetuser(self, user):
233 if len(self.db['ranks']) == 0: return "no one is ranked!"
234
235 user = str(user).lower()
236 if user in self.db['users']:
237 rank = self.db['users'][user]['rank']
238 if rank == 0:
239 return "you're in the lead!"
240 else:
241 return self.db['ranks'][rank-1]
242 else:
243 return self.db['ranks'][-1]
244 def targetpoints(self, user):
245 if len(self.db['ranks']) == 0: return 0
246
247 user = str(user).lower()
248 if user in self.db['users']:
249 rank = self.db['users'][user]['rank']
250 if rank == 0:
251 return "N/A"
252 else:
253 return self.db['users'][self.db['ranks'][rank-1]]['points']
254 else:
255 return self.db['users'][self.db['ranks'][-1]]['points']
256
257 state = TriviaState("/home/jrunyon/erebus/modules/trivia.json") #TODO get path from config
258
259 @lib.hookchan(state.db['chan'])
260 def trivia_checkanswer(bot, user, chan, *args):
261 line = ' '.join([str(arg) for arg in args])
262 if state.checkanswer(line):
263 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)))
264 if state.hintsgiven == 0:
265 bot.msg(chan, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user)))
266 state.nextquestion()
267
268 @lib.hook('points', needchan=False)
269 def cmd_points(bot, user, chan, realtarget, *args):
270 if chan == realtarget: replyto = chan
271 else: replyto = user
272
273 if len(args) != 0: who = args[0]
274 else: who = user
275
276 bot.msg(replyto, "%s has %d points." % (who, state.points(who)))
277
278 @lib.hook('give', clevel=lib.OP, needchan=False)
279 @lib.argsGE(1)
280 def cmd_give(bot, user, chan, realtarget, *args):
281 whoto = args[0]
282 if len(args) > 1:
283 numpoints = int(args[1])
284 else:
285 numpoints = 1
286 balance = state.addpoint(whoto, numpoints)
287
288 bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance))
289
290 @lib.hook('setnext', clevel=lib.OP, needchan=False)
291 @lib.argsGE(1)
292 def cmd_setnext(bot, user, chan, realtarget, *args):
293 line = ' '.join([str(arg) for arg in args])
294 linepieces = line.split('*')
295 if len(linepieces) < 2:
296 bot.msg(user, "Error: need <question>*<answer>")
297 return
298 question = linepieces[0].strip()
299 answer = linepieces[1].strip()
300 state.nextq = {'question':question,'answer':answer}
301 bot.msg(user, "Done.")
302
303 @lib.hook('skip', clevel=lib.KNOWN, needchan=False)
304 def cmd_skip(bot, user, chan, realtarget, *args):
305 state.nextquestion(True)
306
307 @lib.hook('start', needchan=False)
308 def cmd_start(bot, user, chan, realtarget, *args):
309 if chan == realtarget: replyto = chan
310 else: replyto = user
311
312 if state.curq is None and state.pointvote is None:
313 state.nextquestion()
314 elif state.pointvote is not None:
315 bot.msg(replyto, "There's a vote in progress!")
316 else:
317 bot.msg(replyto, "Game is already started!")
318
319 #FIXME @lib.hook('stop', clevel=lib.KNOWN, needchan=False)
320 @lib.hook('stop', needchan=False) #FIXME
321 def cmd_stop(bot, user, chan, realtarget, *args):
322 if stop():
323 bot.msg(state.chan, "Game stopped by %s" % (user))
324 else:
325 bot.msg(user, "Game isn't running.")
326
327 def stop():
328 if state.curq is not None:
329 state.curq = None
330 try:
331 state.steptimer.cancel()
332 except Exception as e:
333 print "!!! steptimer.cancel(): e"
334 return True
335 else:
336 return False
337
338 @lib.hook('rank', needchan=False)
339 def cmd_rank(bot, user, chan, realtarget, *args):
340 if chan == realtarget: replyto = chan
341 else: replyto = user
342
343 if len(args) != 0: who = args[0]
344 else: who = user
345
346 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)))
347
348 @lib.hook('top10', needchan=False)
349 def cmd_top10(bot, user, chan, realtarget, *args):
350 if len(state.db['ranks']) == 0:
351 return bot.msg(state.db['chan'], "No one is ranked!")
352
353 replylist = []
354 for nick in state.db['ranks'][0:10]:
355 user = state.db['users'][nick]
356 replylist.append("%s (%s)" % (user['realnick'], user['points']))
357 bot.msg(state.db['chan'], ', '.join(replylist))
358
359 @lib.hook('settarget', clevel=lib.MASTER, needchan=False)
360 def cmd_settarget(bot, user, chan, realtarget, *args):
361 try:
362 state.db['target'] = int(args[0])
363 bot.msg(state.db['chan'], "Target has been changed to %s points!" % (state.db['target']))
364 except:
365 bot.msg(user, "Failed to set target.")
366
367 @lib.hook('maxmissed', clevel=lib.MASTER, needchan=False)
368 def cmd_maxmissed(bot, user, chan, realtarget, *args):
369 try:
370 state.db['maxmissedquestions'] = int(args[0])
371 bot.msg(state.db['chan'], "Max missed questions before round ends has been changed to %s." % (state.db['maxmissedquestions']))
372 except:
373 bot.msg(user, "Failed to set maxmissed.")
374
375 @lib.hook('hinttimer', clevel=lib.MASTER, needchan=False)
376 def cmd_hinttimer(bot, user, chan, realtarget, *args):
377 try:
378 state.db['hinttimer'] = float(args[0])
379 bot.msg(state.db['chan'], "Time between hints has been changed to %s." % (state.db['hinttimer']))
380 except:
381 bot.msg(user, "Failed to set hint timer.")
382
383 @lib.hook('hintnum', clevel=lib.MASTER, needchan=False)
384 def cmd_hintnum(bot, user, chan, realtarget, *args):
385 try:
386 state.db['hintnum'] = int(args[0])
387 bot.msg(state.db['chan'], "Max number of hints has been changed to %s." % (state.db['hintnum']))
388 except:
389 bot.msg(user, "Failed to set hintnum.")
390
391 @lib.hook('findq', clevel=lib.KNOWN, needchan=False)
392 def cmd_findquestion(bot, user, chan, realtarget, *args):
393 matches = [str(i) for i in range(len(state.db['questions'])) if state.db['questions'][i]['question'] == ' '.join(args)] #FIXME: looser equality check
394 if len(matches) > 1:
395 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
396 elif len(matches) == 1:
397 bot.msg(user, "One match: %s" % (matches[0]))
398 else:
399 bot.msg(user, "No match.")
400
401 @lib.hook('delq', clevel=lib.OP, needchan=False)
402 @lib.hook('deleteq', clevel=lib.OP, needchan=False)
403 def cmd_deletequestion(bot, user, chan, realtarget, *args):
404 try:
405 backup = state.db['questions'][int(args[0])]
406 del state.db['questions'][int(args[0])]
407 bot.msg(user, "Deleted %s*%s" % (backup['question'], backup['answer']))
408 except:
409 bot.msg(user, "Couldn't delete that question.")
410
411 @lib.hook('addq', clevel=lib.OP, needchan=False)
412 def cmd_addquestion(bot, user, chan, realtarget, *args):
413 line = ' '.join([str(arg) for arg in args])
414 linepieces = line.split('*')
415 if len(linepieces) < 2:
416 bot.msg(user, "Error: need <question>*<answer>")
417 return
418 question = linepieces[0].strip()
419 answer = linepieces[1].strip()
420 state.db['questions'].append({'question':question,'answer':answer})
421 bot.msg(user, "Done. Question is #%s" % (len(state.db['questions'])-1))
422
423
424 @lib.hook('triviahelp', needchan=False)
425 def cmd_triviahelp(bot, user, chan, realtarget, *args):
426 bot.msg(user, "START")
427 bot.msg(user, "TOP10")
428 bot.msg(user, "POINTS [<user>]")
429 bot.msg(user, "RANK [<user>]")
430 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.KNOWN:
431 bot.msg(user, "SKIP (>=KNOWN )")
432 bot.msg(user, "STOP (>=KNOWN )")
433 bot.msg(user, "FINDQ <question> (>=KNOWN )")
434 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.OP:
435 bot.msg(user, "GIVE <user> [<points>] (>=OP )")
436 bot.msg(user, "SETNEXT <q>*<a> (>=OP )")
437 bot.msg(user, "ADDQ <q>*<a> (>=OP )")
438 bot.msg(user, "DELETEQ <q>*<a> (>=OP ) [aka DELQ]")
439 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.MASTER:
440 bot.msg(user, "SETTARGET <points> (>=MASTER)")
441 bot.msg(user, "MAXMISSED <questions> (>=MASTER)")
442 bot.msg(user, "HINTTIMER <float seconds> (>=MASTER)")
443 bot.msg(user, "HINTNUM <hints> (>=MASTER)")
444
445 @lib.hooknum(417)
446 def num_417(bot, textline):
447 bot.msg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
448 state.nextquestion(False)
449
450
451 def specialQuestion(oldq):
452 newq = {'question': oldq['question'], 'answer': oldq['answer']}
453 qtype = oldq['question'].upper()
454
455 if qtype == "!MONTH":
456 newq['question'] = "What month is it currently (in UTC)?"
457 newq['answer'] = time.strftime("%B").lower()
458 elif qtype == "!MATH+":
459 randnum1 = random.randrange(0, 11)
460 randnum2 = random.randrange(0, 11)
461 newq['question'] = "What is %d + %d?" % (randnum1, randnum2)
462 newq['answer'] = spellout(randnum1+randnum2)
463 return newq
464
465 def spellout(num):
466 return [
467 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
468 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
469 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"
470 ][num]