]> jfr.im git - erebus.git/blob - modules/trivia.py
fixed bug, ctlmod.reloadmod needed to return success
[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 self.nextquestion() #start the game!
142
143 def nextquestion(self, qskipped=False, iteration=0):
144 if self.gameover == True:
145 return self.doGameOver()
146 if qskipped:
147 self.getchan().msg("\00304Fail! The correct answer was: %s" % (self.hintanswer))
148 self.missedquestions += 1
149 else:
150 self.missedquestions = 0
151
152 if isinstance(self.steptimer, threading._Timer):
153 self.steptimer.cancel()
154
155 self.hintstr = None
156 self.hintsgiven = 0
157 self.revealpossibilities = None
158 self.reveal = None
159
160 if self.missedquestions > self.db['maxmissedquestions']:
161 stop()
162 self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game.")
163
164 if state.nextq is not None:
165 nextq = state.nextq
166 state.nextq = None
167 else:
168 nextq = random.choice(self.db['questions'])
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()
178
179 qtext = "\00304,01Next up: "
180 qary = nextq['question'].split(None)
181 for qword in qary:
182 qtext += "\00304,01"+qword+"\00301,01"+chr(random.randrange(0x61,0x7A)) #a-z
183 self.getbot().msg(self.chan, qtext)
184
185 self.curq = nextq
186
187 if isinstance(self.curq['answer'], basestring): self.hintanswer = self.curq['answer']
188 else: self.hintanswer = random.choice(self.curq['answer'])
189
190 self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[1])
191 self.steptimer.start()
192
193 def checkanswer(self, answer):
194 if self.curq is None:
195 return False
196 elif isinstance(self.curq['answer'], basestring):
197 return answer.lower() == self.curq['answer']
198 else: # assume it's a list or something.
199 return answer.lower() in self.curq['answer']
200
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
204 if user in self.db['users']:
205 self.db['users'][user]['points'] += count
206 else:
207 self.db['users'][user] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
208 self.db['ranks'].append(user)
209
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
211 for i in range(0, len(self.db['ranks'])):
212 nick = self.db['ranks'][i]
213 self.db['users'][nick]['rank'] = i
214
215 if self.db['users'][user]['points'] >= state.db['target']:
216 self.gameover = True
217
218 return self.db['users'][user]['points']
219
220 def points(self, user):
221 user = str(user).lower()
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):
228 user = str(user).lower()
229 if user in self.db['users']:
230 return self.db['users'][user]['rank']+1
231 else:
232 return len(self.db['users'])+1
233
234 def targetuser(self, user):
235 if len(self.db['ranks']) == 0: return "no one is ranked!"
236
237 user = str(user).lower()
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]
244 else:
245 return self.db['ranks'][-1]
246 def targetpoints(self, user):
247 if len(self.db['ranks']) == 0: return 0
248
249 user = str(user).lower()
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']
256 else:
257 return self.db['users'][self.db['ranks'][-1]]['points']
258
259 state = TriviaState("/home/jrunyon/erebus/modules/trivia.json") #TODO get path from config
260
261 @lib.hookchan(state.db['chan'])
262 def trivia_checkanswer(bot, user, chan, *args):
263 line = ' '.join([str(arg) for arg in args])
264 if state.checkanswer(line):
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)))
266 if state.hintsgiven == 0:
267 bot.msg(chan, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user)))
268 state.nextquestion()
269
270 @lib.hook('points', needchan=False)
271 def cmd_points(bot, user, chan, realtarget, *args):
272 if chan == realtarget: replyto = chan
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
280 @lib.hook('give', clevel=lib.OP, needchan=False)
281 @lib.argsGE(1)
282 def cmd_give(bot, user, chan, realtarget, *args):
283 whoto = args[0]
284 if len(args) > 1:
285 numpoints = int(args[1])
286 else:
287 numpoints = 1
288 balance = state.addpoint(whoto, numpoints)
289
290 bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance))
291
292 @lib.hook('setnext', clevel=lib.OP, needchan=False)
293 @lib.argsGE(1)
294 def cmd_setnext(bot, user, chan, realtarget, *args):
295 line = ' '.join([str(arg) for arg in args])
296 linepieces = line.split('*')
297 if len(linepieces) < 2:
298 bot.msg(user, "Error: need <question>*<answer>")
299 return
300 question = linepieces[0].strip()
301 answer = linepieces[1].strip()
302 state.nextq = {'question':question,'answer':answer}
303 bot.msg(user, "Done.")
304
305 @lib.hook('skip', clevel=lib.KNOWN, needchan=False)
306 def cmd_skip(bot, user, chan, realtarget, *args):
307 state.nextquestion(True)
308
309 @lib.hook('start', needchan=False)
310 def cmd_start(bot, user, chan, realtarget, *args):
311 if chan == realtarget: replyto = chan
312 else: replyto = user
313
314 if state.curq is None and state.pointvote is None:
315 state.nextquestion()
316 elif state.pointvote is not None:
317 bot.msg(replyto, "There's a vote in progress!")
318 else:
319 bot.msg(replyto, "Game is already started!")
320
321 #FIXME @lib.hook('stop', clevel=lib.KNOWN, needchan=False)
322 @lib.hook('stop', needchan=False) #FIXME
323 def cmd_stop(bot, user, chan, realtarget, *args):
324 if stop():
325 bot.msg(state.chan, "Game stopped by %s" % (user))
326 else:
327 bot.msg(user, "Game isn't running.")
328
329 def stop():
330 if state.curq is not None:
331 state.curq = None
332 try:
333 state.steptimer.cancel()
334 except Exception as e:
335 print "!!! steptimer.cancel(): e"
336 return True
337 else:
338 return False
339
340 @lib.hook('rank', needchan=False)
341 def cmd_rank(bot, user, chan, realtarget, *args):
342 if chan == realtarget: replyto = chan
343 else: replyto = user
344
345 if len(args) != 0: who = args[0]
346 else: who = user
347
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)))
349
350 @lib.hook('top10', needchan=False)
351 def cmd_top10(bot, user, chan, realtarget, *args):
352 if len(state.db['ranks']) == 0:
353 return bot.msg(state.db['chan'], "No one is ranked!")
354
355 replylist = []
356 for nick in state.db['ranks'][0:10]:
357 user = state.db['users'][nick]
358 replylist.append("%s (%s)" % (user['realnick'], user['points']))
359 bot.msg(state.db['chan'], ', '.join(replylist))
360
361 @lib.hook('settarget', clevel=lib.MASTER, needchan=False)
362 def 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']))
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!")
371 except:
372 bot.msg(user, "Failed to set target.")
373
374 @lib.hook('vote', needchan=False)
375 def 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
385 @lib.hook('maxmissed', clevel=lib.MASTER, needchan=False)
386 def 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)
394 def 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)
402 def 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)
410 def 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)
421 def 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)
430 def 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
442 @lib.hook('triviahelp', needchan=False)
443 def cmd_triviahelp(bot, user, chan, realtarget, *args):
444 bot.msg(user, "START")
445 bot.msg(user, "TOP10")
446 bot.msg(user, "POINTS [<user>]")
447 bot.msg(user, "RANK [<user>]")
448 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.KNOWN:
449 bot.msg(user, "SKIP (>=KNOWN )")
450 bot.msg(user, "STOP (>=KNOWN )")
451 bot.msg(user, "FINDQ <question> (>=KNOWN )")
452 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.OP:
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]")
457 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.MASTER:
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)")
462
463 @lib.hooknum(417)
464 def 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
468
469 def 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
483 def 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]