]> jfr.im git - erebus.git/blame - modules/trivia.py
add msg(...) on Channel objects, passthru to Bot.msg()
[erebus.git] / modules / trivia.py
CommitLineData
80d02bd8 1# Erebus IRC bot - Author: Erebus Team
c695f740 2# trivia module
80d02bd8 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):
9557ee54 17 state.parent = parent
80d02bd8 18 return lib.modstart(parent, *args, **kwargs)
19def modstop(*args, **kwargs):
c0eee1b4 20 global state
fadbf980 21 stop()
77c61775 22 state.closeshop()
80d02bd8 23 del state
24 return lib.modstop(*args, **kwargs)
25
26# module code
b5c89dfb 27import json, random, threading, re, time
b16b8c05 28
c0eee1b4 29try:
30 import twitter
31 hastwitter = True
32except ImportError:
33 hastwitter = False
34
b16b8c05 35def findnth(haystack, needle, n): #http://stackoverflow.com/a/1884151
36 parts = haystack.split(needle, n+1)
37 if len(parts)<=n+1:
38 return -1
39 return len(haystack)-len(parts[-1])-len(needle)
80d02bd8 40
41class TriviaState(object):
77c61775 42 def __init__(self, questionfile, parent=None):
43 self.parent = parent
80d02bd8 44 self.questionfile = questionfile
45 self.db = json.load(open(questionfile, "r"))
9557ee54 46 self.chan = self.db['chan']
47 self.curq = None
c695f740 48 self.nextq = None
b16b8c05 49 self.steptimer = None
50 self.hintstr = None
51 self.hintanswer = None
77c61775 52 self.hintsgiven = 0
b16b8c05 53 self.revealpossibilities = None
77c61775 54 self.gameover = False
c0eee1b4 55 self.missedquestions = 0
80d02bd8 56
57 def __del__(self):
77c61775 58 self.closeshop()
59 def closeshop(self):
b16b8c05 60 if threading is not None and threading._Timer is not None and isinstance(self.steptimer, threading._Timer):
61 self.steptimer.cancel()
c695f740 62 if json is not None and json.dump is not None:
6374d61f 63 json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
80d02bd8 64
fadbf980 65 def getchan(self):
66 return self.parent.channel(self.chan)
67 def getbot(self):
68 return self.getchan().bot
69
b16b8c05 70 def nexthint(self, hintnum):
b16b8c05 71 answer = self.hintanswer
72
b5c89dfb 73 if self.hintstr is None or self.revealpossibilities is None or self.reveal is None:
b16b8c05 74 self.hintstr = list(re.sub(r'[a-zA-Z0-9]', '*', answer))
75 self.revealpossibilities = range(''.join(self.hintstr).count('*'))
b5c89dfb 76 self.reveal = int(''.join(self.hintstr).count('*') * (7/24.0))
b16b8c05 77
b5c89dfb 78 for i in range(self.reveal):
b16b8c05 79 revealcount = random.choice(self.revealpossibilities)
80 revealloc = findnth(''.join(self.hintstr), '*', revealcount)
81 self.revealpossibilities.remove(revealcount)
82 self.hintstr[revealloc] = answer[revealloc]
6374d61f 83 self.parent.channel(self.chan).bot.msg(self.chan, "\00304,01Here's a hint: %s" % (''.join(self.hintstr)))
b16b8c05 84
77c61775 85 self.hintsgiven += 1
86
c4763e66 87 if hintnum < self.db['hintnum']:
88 self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[hintnum+1])
b16b8c05 89 self.steptimer.start()
90 else:
c4763e66 91 self.steptimer = threading.Timer(self.db['hinttimer'], self.nextquestion, args=[True])
b16b8c05 92 self.steptimer.start()
93
77c61775 94 def doGameOver(self):
95 def msg(line): self.getbot().msg(self.getchan(), line)
96 def person(num): return self.db['users'][self.db['ranks'][num]]['realnick']
97 def pts(num): return self.db['users'][self.db['ranks'][num]]['points']
c0eee1b4 98 winner = person(0)
77c61775 99 try:
100 msg("\00312THE GAME IS OVER!!!")
101 msg("THE WINNER IS: %s (%s)" % (person(0), pts(0)))
102 msg("2ND PLACE: %s (%s)" % (person(1), pts(1)))
103 msg("3RD PLACE: %s (%s)" % (person(2), pts(2)))
104 [msg("%dth place: %s (%s)" % (i+1, person(i), pts(i))) for i in range(3,10)]
105 except IndexError: pass
c0eee1b4 106 except Exception as e: msg("DERP! %r" % (e))
107
77c61775 108 self.db['users'] = {}
109 self.db['ranks'] = []
110 stop()
111 self.closeshop()
c0eee1b4 112
113 if hastwitter:
114 t = twitter.Twitter(auth=twitter.OAuth(self.getbot().parent.cfg.get('trivia', 'token'),
115 self.getbot().parent.cfg.get('trivia', 'token_sec'),
116 self.getbot().parent.cfg.get('trivia', 'con'),
117 self.getbot().parent.cfg.get('trivia', 'con_sec')))
118 t.statuses.update(status="Round is over! The winner was %s" % (winner))
119
77c61775 120 self.__init__(self.questionfile, self.parent)
121
b5c89dfb 122 def nextquestion(self, qskipped=False, iteration=0):
77c61775 123 if self.gameover == True:
124 return self.doGameOver()
fadbf980 125 if qskipped:
6374d61f 126 self.getbot().msg(self.getchan(), "\00304Fail! The correct answer was: %s" % (self.hintanswer))
c0eee1b4 127 self.missedquestions += 1
128 else:
129 self.missedquestions = 0
fadbf980 130
b16b8c05 131 if isinstance(self.steptimer, threading._Timer):
132 self.steptimer.cancel()
c0eee1b4 133
b16b8c05 134 self.hintstr = None
77c61775 135 self.hintsgiven = 0
b16b8c05 136 self.revealpossibilities = None
b5c89dfb 137 self.reveal = None
b16b8c05 138
c4763e66 139 if self.missedquestions > self.db['maxmissedquestions']:
c0eee1b4 140 stop()
141 self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game.")
b16b8c05 142
c695f740 143 if state.nextq is not None:
144 nextq = state.nextq
c695f740 145 state.nextq = None
146 else:
147 nextq = random.choice(self.db['questions'])
b5c89dfb 148
149 if nextq['question'][0] == "!":
150 nextq = specialQuestion(nextq)
151
152 if iteration < 10 and 'lastasked' in nextq and nextq['lastasked'] - time.time() < 24*60*60:
153 return self.nextquestion(iteration=iteration+1) #short-circuit to pick another question
154 nextq['lastasked'] = time.time()
155
156 nextq['answer'] = nextq['answer'].lower()
c695f740 157
6374d61f 158 qtext = "\00304,01Next up: "
c695f740 159 qary = nextq['question'].split(None)
160 for qword in qary:
6374d61f 161 qtext += "\00304,01"+qword+"\00301,01"+chr(random.randrange(0x61,0x7A)) #a-z
fadbf980 162 self.getbot().msg(self.chan, qtext)
80d02bd8 163
b5c89dfb 164 self.curq = nextq
165
c0eee1b4 166 if isinstance(self.curq['answer'], basestring): self.hintanswer = self.curq['answer']
167 else: self.hintanswer = random.choice(self.curq['answer'])
168
c4763e66 169 self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[1])
b16b8c05 170 self.steptimer.start()
171
80d02bd8 172 def checkanswer(self, answer):
9557ee54 173 if self.curq is None:
174 return False
175 elif isinstance(self.curq['answer'], basestring):
80d02bd8 176 return answer.lower() == self.curq['answer']
177 else: # assume it's a list or something.
178 return answer.lower() in self.curq['answer']
77c61775 179
80d02bd8 180 def addpoint(self, _user, count=1):
9557ee54 181 _user = str(_user)
80d02bd8 182 user = _user.lower()
183 if user in self.db['users']:
184 self.db['users'][user]['points'] += count
185 else:
186 self.db['users'][user] = {'points': count, 'realnick': _user, 'rank': len(self.db['ranks'])}
9557ee54 187 self.db['ranks'].append(user)
80d02bd8 188
6374d61f 189 self.db['ranks'].sort(key=lambda nick: state.db['users'][nick]['points'], reverse=True)
190 for i in range(0, len(self.db['ranks'])):
191 nick = self.db['ranks'][i]
192 self.db['users'][nick]['rank'] = i
77c61775 193
194 if self.db['users'][user]['points'] >= state.db['target']:
195 self.gameover = True
196
80d02bd8 197 return self.db['users'][user]['points']
198
199 def points(self, user):
9557ee54 200 user = str(user).lower()
80d02bd8 201 if user in self.db['users']:
202 return self.db['users'][user]['points']
203 else:
204 return 0
205
206 def rank(self, user):
c695f740 207 user = str(user).lower()
fadbf980 208 if user in self.db['users']:
209 return self.db['users'][user]['rank']+1
210 else:
211 return len(self.db['users'])+1
77c61775 212
c695f740 213 def targetuser(self, user):
77c61775 214 if len(self.db['ranks']) == 0: return "no one is ranked!"
215
c695f740 216 user = str(user).lower()
fadbf980 217 if user in self.db['users']:
218 rank = self.db['users'][user]['rank']
219 if rank == 0:
220 return "you're in the lead!"
221 else:
222 return self.db['ranks'][rank-1]
c695f740 223 else:
fadbf980 224 return self.db['ranks'][-1]
c695f740 225 def targetpoints(self, user):
77c61775 226 if len(self.db['ranks']) == 0: return 0
227
c695f740 228 user = str(user).lower()
fadbf980 229 if user in self.db['users']:
230 rank = self.db['users'][user]['rank']
231 if rank == 0:
232 return "N/A"
233 else:
234 return self.db['users'][self.db['ranks'][rank-1]]['points']
c695f740 235 else:
fadbf980 236 return self.db['users'][self.db['ranks'][-1]]['points']
80d02bd8 237
c695f740 238state = TriviaState("/home/jrunyon/erebus/modules/trivia.json") #TODO get path from config
9557ee54 239
80d02bd8 240@lib.hookchan(state.db['chan'])
241def trivia_checkanswer(bot, user, chan, *args):
80d02bd8 242 line = ' '.join([str(arg) for arg in args])
243 if state.checkanswer(line):
6374d61f 244 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)))
77c61775 245 if state.hintsgiven == 0:
6374d61f 246 bot.msg(chan, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user)))
9557ee54 247 state.nextquestion()
80d02bd8 248
f6252f1c 249@lib.hook('points', needchan=False)
80d02bd8 250def cmd_points(bot, user, chan, realtarget, *args):
c695f740 251 if chan == realtarget: replyto = chan
80d02bd8 252 else: replyto = user
253
254 if len(args) != 0: who = args[0]
255 else: who = user
256
257 bot.msg(replyto, "%s has %d points." % (who, state.points(who)))
258
f6252f1c 259@lib.hook('give', clevel=lib.OP, needchan=False)
80d02bd8 260@lib.argsGE(1)
261def cmd_give(bot, user, chan, realtarget, *args):
80d02bd8 262 whoto = args[0]
c695f740 263 if len(args) > 1:
264 numpoints = int(args[1])
265 else:
266 numpoints = 1
267 balance = state.addpoint(whoto, numpoints)
fadbf980 268
c695f740 269 bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance))
270
f6252f1c 271@lib.hook('setnext', clevel=lib.OP, needchan=False)
c695f740 272@lib.argsGE(1)
273def cmd_setnext(bot, user, chan, realtarget, *args):
274 line = ' '.join([str(arg) for arg in args])
275 linepieces = line.split('*')
b5c89dfb 276 if len(linepieces) < 2:
277 bot.msg(user, "Error: need <question>*<answer>")
278 return
c695f740 279 question = linepieces[0].strip()
280 answer = linepieces[1].strip()
281 state.nextq = {'question':question,'answer':answer}
282 bot.msg(user, "Done.")
283
f6252f1c 284@lib.hook('skip', clevel=lib.KNOWN, needchan=False)
c695f740 285def cmd_skip(bot, user, chan, realtarget, *args):
c0eee1b4 286 state.nextquestion(True)
c695f740 287
f6252f1c 288@lib.hook('start', needchan=False)
c695f740 289def cmd_start(bot, user, chan, realtarget, *args):
290 if chan == realtarget: replyto = chan
291 else: replyto = user
292
293 if state.curq is None:
294 state.nextquestion()
295 else:
296 bot.msg(replyto, "Game is already started!")
297
6374d61f 298#FIXME @lib.hook('stop', clevel=lib.KNOWN, needchan=False)
299@lib.hook('stop', needchan=False) #FIXME
c695f740 300def cmd_stop(bot, user, chan, realtarget, *args):
fadbf980 301 if stop():
302 bot.msg(state.chan, "Game stopped by %s" % (user))
303 else:
304 bot.msg(user, "Game isn't running.")
c695f740 305
fadbf980 306def stop():
c695f740 307 if state.curq is not None:
308 state.curq = None
c0eee1b4 309 try:
b16b8c05 310 state.steptimer.cancel()
c0eee1b4 311 except Exception as e:
312 print "!!! steptimer.cancel(): e"
fadbf980 313 return True
c695f740 314 else:
fadbf980 315 return False
80d02bd8 316
f6252f1c 317@lib.hook('rank', needchan=False)
80d02bd8 318def cmd_rank(bot, user, chan, realtarget, *args):
c695f740 319 if chan == realtarget: replyto = chan
80d02bd8 320 else: replyto = user
321
c695f740 322 if len(args) != 0: who = args[0]
323 else: who = user
324
77c61775 325 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)))
fadbf980 326
f6252f1c 327@lib.hook('top10', needchan=False)
fadbf980 328def cmd_top10(bot, user, chan, realtarget, *args):
77c61775 329 if len(state.db['ranks']) == 0:
330 return bot.msg(state.db['chan'], "No one is ranked!")
fadbf980 331
332 replylist = []
333 for nick in state.db['ranks'][0:10]:
334 user = state.db['users'][nick]
77c61775 335 replylist.append("%s (%s)" % (user['realnick'], user['points']))
336 bot.msg(state.db['chan'], ', '.join(replylist))
337
f6252f1c 338@lib.hook('settarget', clevel=lib.MASTER, needchan=False)
77c61775 339def cmd_settarget(bot, user, chan, realtarget, *args):
340 try:
341 state.db['target'] = int(args[0])
342 bot.msg(state.db['chan'], "Target has been changed to %s points!" % (state.db['target']))
343 except:
344 bot.msg(user, "Failed to set target.")
345
c4763e66 346@lib.hook('maxmissed', clevel=lib.MASTER, needchan=False)
347def cmd_maxmissed(bot, user, chan, realtarget, *args):
348 try:
349 state.db['maxmissedquestions'] = int(args[0])
350 bot.msg(state.db['chan'], "Max missed questions before round ends has been changed to %s." % (state.db['maxmissedquestions']))
351 except:
352 bot.msg(user, "Failed to set maxmissed.")
353
354@lib.hook('hinttimer', clevel=lib.MASTER, needchan=False)
355def cmd_hinttimer(bot, user, chan, realtarget, *args):
356 try:
357 state.db['hinttimer'] = float(args[0])
358 bot.msg(state.db['chan'], "Time between hints has been changed to %s." % (state.db['hinttimer']))
359 except:
360 bot.msg(user, "Failed to set hint timer.")
361
362@lib.hook('hintnum', clevel=lib.MASTER, needchan=False)
363def cmd_hintnum(bot, user, chan, realtarget, *args):
364 try:
365 state.db['hintnum'] = int(args[0])
366 bot.msg(state.db['chan'], "Max number of hints has been changed to %s." % (state.db['hintnum']))
367 except:
368 bot.msg(user, "Failed to set hintnum.")
369
370@lib.hook('findq', clevel=lib.KNOWN, needchan=False)
371def cmd_findquestion(bot, user, chan, realtarget, *args):
372 matches = [str(i) for i in range(len(state.db['questions'])) if state.db['questions'][i]['question'] == ' '.join(args)] #FIXME: looser equality check
373 if len(matches) > 1:
374 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
375 elif len(matches) == 1:
376 bot.msg(user, "One match: %s" % (matches[0]))
377 else:
378 bot.msg(user, "No match.")
379
380@lib.hook('delq', clevel=lib.OP, needchan=False)
381@lib.hook('deleteq', clevel=lib.OP, needchan=False)
382def cmd_deletequestion(bot, user, chan, realtarget, *args):
383 try:
384 backup = state.db['questions'][int(args[0])]
385 del state.db['questions'][int(args[0])]
386 bot.msg(user, "Deleted %s*%s" % (backup['question'], backup['answer']))
387 except:
388 bot.msg(user, "Couldn't delete that question.")
389
390@lib.hook('addq', clevel=lib.OP, needchan=False)
391def cmd_addquestion(bot, user, chan, realtarget, *args):
392 line = ' '.join([str(arg) for arg in args])
393 linepieces = line.split('*')
394 if len(linepieces) < 2:
395 bot.msg(user, "Error: need <question>*<answer>")
396 return
397 question = linepieces[0].strip()
398 answer = linepieces[1].strip()
399 state.db['questions'].append({'question':question,'answer':answer})
400 bot.msg(user, "Done. Question is #%s" % (len(state.db['questions'])-1))
401
402
f6252f1c 403@lib.hook('triviahelp', needchan=False)
77c61775 404def cmd_triviahelp(bot, user, chan, realtarget, *args):
c4763e66 405 bot.msg(user, "START")
406 bot.msg(user, "TOP10")
407 bot.msg(user, "POINTS [<user>]")
408 bot.msg(user, "RANK [<user>]")
77c61775 409 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.KNOWN:
c4763e66 410 bot.msg(user, "SKIP (>=KNOWN )")
411 bot.msg(user, "STOP (>=KNOWN )")
412 bot.msg(user, "FINDQ <question> (>=KNOWN )")
77c61775 413 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.OP:
c4763e66 414 bot.msg(user, "GIVE <user> [<points>] (>=OP )")
415 bot.msg(user, "SETNEXT <q>*<a> (>=OP )")
416 bot.msg(user, "ADDQ <q>*<a> (>=OP )")
417 bot.msg(user, "DELETEQ <q>*<a> (>=OP ) [aka DELQ]")
77c61775 418 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.MASTER:
c4763e66 419 bot.msg(user, "SETTARGET <points> (>=MASTER)")
420 bot.msg(user, "MAXMISSED <questions> (>=MASTER)")
421 bot.msg(user, "HINTTIMER <float seconds> (>=MASTER)")
422 bot.msg(user, "HINTNUM <hints> (>=MASTER)")
b5c89dfb 423
6374d61f 424@lib.hooknum(417)
425def num_417(bot, textline):
426 bot.msg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
427 state.nextquestion(False)
428
b5c89dfb 429
430def specialQuestion(oldq):
431 newq = {'question': oldq['question'], 'answer': oldq['answer']}
432 qtype = oldq['question'].upper()
433
434 if qtype == "!MONTH":
435 newq['question'] = "What month is it currently (in UTC)?"
436 newq['answer'] = time.strftime("%B").lower()
437 elif qtype == "!MATH+":
438 randnum1 = random.randrange(0, 11)
439 randnum2 = random.randrange(0, 11)
440 newq['question'] = "What is %d + %d?" % (randnum1, randnum2)
441 newq['answer'] = spellout(randnum1+randnum2)
442 return newq
443
444def spellout(num):
445 return [
446 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
447 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
448 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"
449 ][num]