]> jfr.im git - erebus.git/blame - modules/trivia.py
help - make response format match for cmd list vs single cmd
[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
fb20be7c 10 'depends': ['userinfo'], # other modules required to work properly?
80d02bd8 11}
12
13# preamble
14import modlib
15lib = modlib.modlib(__name__)
16def modstart(parent, *args, **kwargs):
5871567f 17 state.gotParent(parent)
18 lib.hookchan(state.db['chan'])(trivia_checkanswer) # we need parent for this. so it goes here.
80d02bd8 19 return lib.modstart(parent, *args, **kwargs)
20def modstop(*args, **kwargs):
c0eee1b4 21 global state
8ef938d0 22 try:
23 stop()
24 state.closeshop()
25 del state
26 except Exception: pass
80d02bd8 27 return lib.modstop(*args, **kwargs)
28
29# module code
7bd5e7d5 30import json, random, threading, re, time, datetime
b16b8c05 31
c0eee1b4 32try:
be8072b5 33 import twitter
c53f6514 34except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
c0eee1b4 35
b16b8c05 36def findnth(haystack, needle, n): #http://stackoverflow.com/a/1884151
37 parts = haystack.split(needle, n+1)
38 if len(parts)<=n+1:
39 return -1
40 return len(haystack)-len(parts[-1])-len(needle)
80d02bd8 41
00ccae72 42def person(num, throwindexerror=False):
43 try:
44 return state.db['users'][state.db['ranks'][num]]['realnick']
45 except IndexError:
46 if throwindexerror:
47 raise
48 else:
49 return ''
50
3b89ebff 51def pts(num):
00ccae72 52 try:
53 return str(state.db['users'][state.db['ranks'][num]]['points'])
54 except IndexError:
55 return 0
2bb267e0 56
00ccae72 57def country(num, default="??"):
2bb267e0 58 return lib.mod('userinfo')._get(person(num), 'country', default=default).upper()
8ef938d0 59
be8072b5 60class MyTimer(threading._Timer):
61 def __init__(self, *args, **kwargs):
62 threading._Timer.__init__(self, *args, **kwargs)
63 self.daemon = True
64
80d02bd8 65class TriviaState(object):
5871567f 66 def __init__(self, parent=None, pointvote=False):
67 if parent is not None:
68 self.gotParent(parent, pointvote)
69
70 def gotParent(self, parent, pointvote=False):
bf8676ae 71 self.parent = parent
72 self.questionfile = self.parent.cfg.get('trivia', 'jsonpath', default="./modules/trivia.json")
73 self.db = json.load(open(self.questionfile, "r"))
74 self.chan = self.db['chan']
75 self.curq = None
76 self.nextq = None
77 self.nextquestiontimer = None
78 self.steptimer = None
79 self.hintstr = None
80 self.hintanswer = None
81 self.hintsgiven = 0
b16b8c05 82 self.revealpossibilities = None
bf8676ae 83 self.gameover = False
84 self.missedquestions = 0
85 self.curqid = None
86 self.lastqid = None
80d02bd8 87
00ccae72 88 if 'lastwon' not in self.db or self.db['lastwon'] is None:
89 self.db['lastwon'] = time.time()
7bd5e7d5 90
c53f6514 91 if pointvote:
92 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']])))
93 self.getchan().msg("You have %s seconds." % (self.db['votetimer']))
94 self.voteamounts = dict([(x, 0) for x in self.db['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
be8072b5 95 self.pointvote = MyTimer(self.db['votetimer'], self.endPointVote)
c53f6514 96 self.pointvote.start()
97 else:
98 self.pointvote = None
99
80d02bd8 100 def __del__(self):
77c61775 101 self.closeshop()
102 def closeshop(self):
442ed923 103 if threading is not None and threading._Timer is not None:
104 if isinstance(self.steptimer, threading._Timer):
105 self.steptimer.cancel()
106 if isinstance(self.nextquestiontimer, threading._Timer):
107 self.nextquestiontimer.cancel()
108 self.nextquestiontimer = None
b9daa51a 109 self.savedb()
110
111 def savedb(self):
c695f740 112 if json is not None and json.dump is not None:
6374d61f 113 json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
80d02bd8 114
fadbf980 115 def getchan(self):
116 return self.parent.channel(self.chan)
117 def getbot(self):
118 return self.getchan().bot
119
b16b8c05 120 def nexthint(self, hintnum):
b16b8c05 121 answer = self.hintanswer
122
b5c89dfb 123 if self.hintstr is None or self.revealpossibilities is None or self.reveal is None:
93ce52fd 124 oldhintstr = ""
b16b8c05 125 self.hintstr = list(re.sub(r'[a-zA-Z0-9]', '*', answer))
126 self.revealpossibilities = range(''.join(self.hintstr).count('*'))
93ce52fd 127 self.reveal = int(round(''.join(self.hintstr).count('*') * (7/24.0)))
128 else:
129 oldhintstr = ''.join(self.hintstr)
b16b8c05 130
b5c89dfb 131 for i in range(self.reveal):
b16b8c05 132 revealcount = random.choice(self.revealpossibilities)
133 revealloc = findnth(''.join(self.hintstr), '*', revealcount)
134 self.revealpossibilities.remove(revealcount)
135 self.hintstr[revealloc] = answer[revealloc]
2bb267e0 136 if oldhintstr != ''.join(self.hintstr): self.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self.hintstr)))
b16b8c05 137
77c61775 138 self.hintsgiven += 1
139
c4763e66 140 if hintnum < self.db['hintnum']:
be8072b5 141 self.steptimer = MyTimer(self.db['hinttimer'], self.nexthint, args=[hintnum+1])
b16b8c05 142 self.steptimer.start()
143 else:
be8072b5 144 self.steptimer = MyTimer(self.db['hinttimer'], self.nextquestion, args=[True])
b16b8c05 145 self.steptimer.start()
146
77c61775 147 def doGameOver(self):
7bd5e7d5 148 msg = self.getchan().msg
c0eee1b4 149 winner = person(0)
77c61775 150 try:
151 msg("\00312THE GAME IS OVER!!!")
00ccae72 152 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
153 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
154 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
155 [msg("%dth place: %s (%s)" % (i+1, person(i, True), pts(i))) for i in range(3,10)]
77c61775 156 except IndexError: pass
09566235 157 except Exception as e:
158 msg("DERP! %r" % (e))
c0eee1b4 159
5f42c250 160 self.db['lastwinner'] = winner
161 self.db['lastwon'] = time.time()
162
7bd5e7d5 163 if self.db['hofpath'] is not None and self.db['hofpath'] != '':
164 self.writeHof()
165
77c61775 166 self.db['users'] = {}
167 self.db['ranks'] = []
168 stop()
169 self.closeshop()
c0eee1b4 170
c53f6514 171 try:
c0eee1b4 172 t = twitter.Twitter(auth=twitter.OAuth(self.getbot().parent.cfg.get('trivia', 'token'),
173 self.getbot().parent.cfg.get('trivia', 'token_sec'),
174 self.getbot().parent.cfg.get('trivia', 'con'),
175 self.getbot().parent.cfg.get('trivia', 'con_sec')))
176 t.statuses.update(status="Round is over! The winner was %s" % (winner))
c53f6514 177 except: pass #don't care if errors happen updating twitter.
178
5871567f 179 self.__init__(self.parent, True)
c53f6514 180
7bd5e7d5 181 def writeHof(self):
182 def person(num):
183 try: return self.db['users'][self.db['ranks'][num]]['realnick']
184 except: return "none"
185 def pts(num):
186 try: return str(self.db['users'][self.db['ranks'][num]]['points'])
187 except: return 0
188
aaf381b8 189 status = False
7bd5e7d5 190 try:
191 f = open(self.db['hofpath'], 'rb+')
192 for i in range(self.db['hoflines']): #skip this many lines
193 f.readline()
194 insertpos = f.tell()
195 fcontents = f.read()
196 f.seek(insertpos)
197 f.write((self.db['hofformat']+"\n") % {
198 'date': time.strftime("%F", time.gmtime()),
00ccae72 199 'duration': str(datetime.timedelta(seconds=time.time()-self.db['lastwon'])),
7bd5e7d5 200 'targetscore': self.db['target'],
201 'firstperson': person(0),
202 'firstscore': pts(0),
203 'secondperson': person(1),
204 'secondscore': pts(1),
205 'thirdperson': person(2),
206 'thirdscore': pts(2),
207 })
208 f.write(fcontents)
aaf381b8 209 status = True
7bd5e7d5 210 except Exception as e:
aaf381b8 211 status = False
7bd5e7d5 212 finally:
213 f.close()
aaf381b8 214 return status
7bd5e7d5 215
c53f6514 216 def endPointVote(self):
217 self.getchan().msg("Voting has ended!")
218 votelist = sorted(self.voteamounts.items(), key=lambda item: item[1]) #sort into list of tuples: [(option, number_of_votes), ...]
219 for i in range(len(votelist)-1):
220 item = votelist[i]
221 self.getchan().msg("%s place: %s (%s votes)" % (len(votelist)-i, item[0], item[1]))
222 self.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist[-1][0], votelist[-1][1]))
c0eee1b4 223
c53f6514 224 self.db['target'] = votelist[-1][0]
225 self.pointvote = None
77c61775 226
38b29993 227 self.nextquestion() #start the game!
228
442ed923 229 def nextquestion(self, qskipped=False, iteration=0, skipwait=False):
7b832b55 230 self.lastqid = self.curqid
6bdfec48 231 self.curq = None
7b832b55 232 self.curqid = None
77c61775 233 if self.gameover == True:
234 return self.doGameOver()
fadbf980 235 if qskipped:
be8072b5 236 self.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self.hintanswer))
c0eee1b4 237 self.missedquestions += 1
238 else:
239 self.missedquestions = 0
f8cc0124 240 if 'topicformat' in self.db and self.db['topicformat'] is not None:
241 self.getbot().conn.send("TOPIC %s" % (self.db['chan']))
fadbf980 242
b16b8c05 243 if isinstance(self.steptimer, threading._Timer):
244 self.steptimer.cancel()
442ed923 245 if isinstance(self.nextquestiontimer, threading._Timer):
246 self.nextquestiontimer.cancel()
247 self.nextquestiontimer = None
c0eee1b4 248
b16b8c05 249 self.hintstr = None
77c61775 250 self.hintsgiven = 0
b16b8c05 251 self.revealpossibilities = None
b5c89dfb 252 self.reveal = None
b16b8c05 253
c4763e66 254 if self.missedquestions > self.db['maxmissedquestions']:
c0eee1b4 255 stop()
ce03ceda 256 self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game." % (self.missedquestions))
257 return
b16b8c05 258
442ed923 259 if skipwait:
6bdfec48 260 self._nextquestion(iteration)
442ed923 261 else:
be8072b5 262 self.nextquestiontimer = MyTimer(self.db['questionpause'], self._nextquestion, args=[iteration])
442ed923 263 self.nextquestiontimer.start()
264
6bdfec48 265 def _nextquestion(self, iteration):
e5a3970b 266 if self.nextq is not None:
2520caee 267 nextqid = None
e5a3970b 268 nextq = self.nextq
269 self.nextq = None
c695f740 270 else:
2520caee 271 nextqid = random.randrange(0, len(self.db['questions']))
272 nextq = self.db['questions'][nextqid]
b5c89dfb 273
ebee6edb 274 if nextq[0][0] == "!":
2520caee 275 nextqid = None
b5c89dfb 276 nextq = specialQuestion(nextq)
277
ebee6edb 278 if len(nextq) > 2 and nextq[2] - time.time() < 7*24*60*60 and iteration < 10:
442ed923 279 return self._nextquestion(iteration=iteration+1) #short-circuit to pick another question
ebee6edb 280 if len(nextq) > 2:
281 nextq[2] = time.time()
282 else:
283 nextq.append(time.time())
b5c89dfb 284
93ce52fd 285 if isinstance(nextq[1], basestring):
286 nextq[1] = nextq[1].lower()
287 else:
288 nextq[1] = [s.lower() for s in nextq[1]]
c695f740 289
00ccae72 290 qtext = "\00312,01Next up: "
bf8676ae 291 qtext += "(%5d)" % (random.randint(0,99999))
ebee6edb 292 qary = nextq[0].split(None)
71e0b5fb 293 qtext += " "
c695f740 294 for qword in qary:
6374d61f 295 qtext += "\00304,01"+qword+"\00301,01"+chr(random.randrange(0x61,0x7A)) #a-z
be8072b5 296 self.getbot().fastmsg(self.chan, qtext)
80d02bd8 297
b5c89dfb 298 self.curq = nextq
7b832b55 299 self.curqid = nextqid
b5c89dfb 300
ebee6edb 301 if isinstance(self.curq[1], basestring): self.hintanswer = self.curq[1]
302 else: self.hintanswer = random.choice(self.curq[1])
c0eee1b4 303
be8072b5 304 self.steptimer = MyTimer(self.db['hinttimer'], self.nexthint, args=[1])
b16b8c05 305 self.steptimer.start()
306
80d02bd8 307 def checkanswer(self, answer):
9557ee54 308 if self.curq is None:
309 return False
ebee6edb 310 elif isinstance(self.curq[1], basestring):
311 return answer.lower() == self.curq[1]
80d02bd8 312 else: # assume it's a list or something.
ebee6edb 313 return answer.lower() in self.curq[1]
77c61775 314
c53f6514 315 def addpoint(self, user_obj, count=1):
316 user_nick = str(user_obj)
317 user = user_nick.lower() # save this separately as we use both
80d02bd8 318 if user in self.db['users']:
319 self.db['users'][user]['points'] += count
320 else:
c53f6514 321 self.db['users'][user] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
9557ee54 322 self.db['ranks'].append(user)
80d02bd8 323
e5a3970b 324 self.db['ranks'].sort(key=lambda nick: self.db['users'][nick]['points'], reverse=True) #re-sort ranks, rather than dealing with anything more efficient
6374d61f 325 for i in range(0, len(self.db['ranks'])):
326 nick = self.db['ranks'][i]
327 self.db['users'][nick]['rank'] = i
77c61775 328
e5a3970b 329 if self.db['users'][user]['points'] >= self.db['target']:
77c61775 330 self.gameover = True
331
80d02bd8 332 return self.db['users'][user]['points']
333
334 def points(self, user):
9557ee54 335 user = str(user).lower()
80d02bd8 336 if user in self.db['users']:
337 return self.db['users'][user]['points']
338 else:
339 return 0
340
341 def rank(self, user):
c695f740 342 user = str(user).lower()
fadbf980 343 if user in self.db['users']:
344 return self.db['users'][user]['rank']+1
345 else:
346 return len(self.db['users'])+1
77c61775 347
c695f740 348 def targetuser(self, user):
77c61775 349 if len(self.db['ranks']) == 0: return "no one is ranked!"
350
c695f740 351 user = str(user).lower()
fadbf980 352 if user in self.db['users']:
353 rank = self.db['users'][user]['rank']
354 if rank == 0:
355 return "you're in the lead!"
356 else:
357 return self.db['ranks'][rank-1]
c695f740 358 else:
fadbf980 359 return self.db['ranks'][-1]
c695f740 360 def targetpoints(self, user):
77c61775 361 if len(self.db['ranks']) == 0: return 0
362
c695f740 363 user = str(user).lower()
fadbf980 364 if user in self.db['users']:
365 rank = self.db['users'][user]['rank']
366 if rank == 0:
367 return "N/A"
368 else:
369 return self.db['users'][self.db['ranks'][rank-1]]['points']
c695f740 370 else:
fadbf980 371 return self.db['users'][self.db['ranks'][-1]]['points']
80d02bd8 372
5871567f 373state = TriviaState()
9557ee54 374
5871567f 375# we have to hook this in modstart, since we don't know the channel until then.
80d02bd8 376def trivia_checkanswer(bot, user, chan, *args):
80d02bd8 377 line = ' '.join([str(arg) for arg in args])
378 if state.checkanswer(line):
6bdfec48 379 state.curq = None
93ce52fd 380 if state.hintanswer.lower() == line.lower():
381 bot.fastmsg(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)))
382 else:
383 bot.fastmsg(chan, "\00312%s\003 has it! The answer was \00312%s\003 (hinted answer: %s). New score: %d. Rank: %d. Target: %s (%s)." % (user, line, state.hintanswer, state.addpoint(user), state.rank(user), state.targetuser(user), state.targetpoints(user)))
77c61775 384 if state.hintsgiven == 0:
6374d61f 385 bot.msg(chan, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user)))
9557ee54 386 state.nextquestion()
80d02bd8 387
fb20be7c 388@lib.hook(needchan=False)
5f03d045 389@lib.help("[<user>]", "shows how many points you or someone has")
fb20be7c 390def points(bot, user, chan, realtarget, *args):
6bdfec48 391 if chan is not None and realtarget == chan.name: replyto = chan
80d02bd8 392 else: replyto = user
393
394 if len(args) != 0: who = args[0]
395 else: who = user
396
397 bot.msg(replyto, "%s has %d points." % (who, state.points(who)))
398
fb20be7c 399@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 400@lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
80d02bd8 401@lib.argsGE(1)
fb20be7c 402def give(bot, user, chan, realtarget, *args):
80d02bd8 403 whoto = args[0]
c695f740 404 if len(args) > 1:
405 numpoints = int(args[1])
406 else:
407 numpoints = 1
408 balance = state.addpoint(whoto, numpoints)
fadbf980 409
c695f740 410 bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance))
411
fb20be7c 412@lib.hook(glevel=1, needchan=False)
5f03d045 413@lib.help("<qid>", "sets next question to one in the database")
414@lib.argsEQ(1)
fb20be7c 415def setnextid(bot, user, chan, realtarget, *args):
9306587e 416 try:
417 qid = int(args[0])
418 state.nextq = state.db['questions'][qid]
71e0b5fb 419 if user.glevel >= lib.STAFF:
420 respstr = "Done. Next question is: %s" % (state.nextq[0])
421 else:
422 respstr = "Done."
423 bot.msg(user, respstr)
9306587e 424 except Exception as e:
425 bot.msg(user, "Error: %s" % (e))
426
fb20be7c 427@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 428@lib.help("<q>*<a>", "sets next question to one not in database")
c695f740 429@lib.argsGE(1)
fb20be7c 430def setnext(bot, user, chan, realtarget, *args):
c695f740 431 line = ' '.join([str(arg) for arg in args])
432 linepieces = line.split('*')
b5c89dfb 433 if len(linepieces) < 2:
434 bot.msg(user, "Error: need <question>*<answer>")
435 return
c695f740 436 question = linepieces[0].strip()
437 answer = linepieces[1].strip()
ebee6edb 438 state.nextq = [question, answer]
c695f740 439 bot.msg(user, "Done.")
440
fb20be7c 441@lib.hook(glevel=1, needchan=False)
5f03d045 442@lib.help(None, "skips to next question")
fb20be7c 443def skip(bot, user, chan, realtarget, *args):
442ed923 444 state.nextquestion(qskipped=True, skipwait=True)
c695f740 445
fb20be7c 446@lib.hook(needchan=False)
5f03d045 447@lib.help(None, "starts the trivia game")
fb20be7c 448def start(bot, user, chan, realtarget, *args):
6bdfec48 449 if chan is not None and realtarget == chan.name: replyto = chan
c695f740 450 else: replyto = user
451
77a265cd 452 if chan is not None and chan.name != state.db['chan']:
453 bot.msg(replyto, "That command isn't valid here.")
454 return
455
442ed923 456 if state.curq is None and state.pointvote is None and state.nextquestiontimer is None:
77a265cd 457 bot.msg(state.db['chan'], "%s has started the game!" % (user))
442ed923 458 state.nextquestion(skipwait=True)
c53f6514 459 elif state.pointvote is not None:
00ccae72 460 bot.msg(user, "There's a vote in progress!")
c695f740 461 else:
00ccae72 462 bot.msg(user, "Game is already started!")
c695f740 463
9306587e 464@lib.hook('stop', glevel=1, needchan=False)
5f03d045 465@lib.help(None, "stops the trivia game")
c695f740 466def cmd_stop(bot, user, chan, realtarget, *args):
fadbf980 467 if stop():
468 bot.msg(state.chan, "Game stopped by %s" % (user))
469 else:
470 bot.msg(user, "Game isn't running.")
c695f740 471
fadbf980 472def stop():
3b89ebff 473 state.curq = None
474 state.nextq = None
09566235 475 try:
476 state.steptimer.cancel()
477 except Exception as e:
478 print "!!! steptimer.cancel(): %s %r" % (e,e)
3b89ebff 479 state.steptimer = None
09566235 480 try:
481 state.nextquestiontimer.cancel()
482 except Exception as e:
483 print "!!! nextquestiontimer.cancel(): %s %r" % (e,e)
3b89ebff 484 state.nextquestiontimer = None
485 return True
80d02bd8 486
fb20be7c 487@lib.hook(needchan=False)
5f03d045 488@lib.help("<reason>", "reports a bad question to the admins")
7b832b55 489@lib.argsGE(1)
fb20be7c 490def badq(bot, user, chan, realtarget, *args):
7b832b55 491 lastqid = state.lastqid
492 curqid = state.curqid
493
494 reason = ' '.join(args)
495 state.db['badqs'].append([lastqid, curqid, reason])
4d98501a 496 state.savedb()
7b832b55 497 bot.msg(user, "Reported bad question.")
2520caee 498
fb20be7c 499@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 500@lib.help(None, "shows a list of BADQ reports")
fb20be7c 501def badqs(bot, user, chan, realtarget, *args):
2520caee 502 if len(state.db['badqs']) == 0:
503 bot.msg(user, "No reports.")
504
505 for i in range(len(state.db['badqs'])):
506 try:
507 report = state.db['badqs'][i]
7b832b55 508 bot.msg(user, "Report #%d: LastQ=%r CurQ=%r: %s" % (i, report[0], report[1], report[2]))
509 try: lq = state.db['questions'][int(report[0])]
510 except Exception as e: lq = (None,None)
511 try: cq = state.db['questions'][int(report[1])]
512 except Exception as e: cq = (None, None)
513 bot.msg(user, "- Last: %s*%s" % (lq[0], lq[1]))
514 bot.msg(user, "- Curr: %s*%s" % (cq[0], cq[1]))
2520caee 515 except Exception as e:
516 bot.msg(user, "- Exception: %r" % (e))
517
fb20be7c 518@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 519@lib.hook(None, "clears list of BADQ reports")
fb20be7c 520def clearbadqs(bot, user, chan, realtarget, *args):
2520caee 521 state.db['badqs'] = []
4d98501a 522 state.savedb()
2520caee 523 bot.msg(user, "Cleared reports.")
524
fb20be7c 525@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 526@lib.hook("<badqid>", "removes a BADQ report")
2520caee 527@lib.argsEQ(1)
fb20be7c 528def delbadq(bot, user, chan, realtarget, *args):
4d98501a 529 try:
530 qid = int(args[0])
531 del state.db['badqs'][qid]
532 state.savedb()
533 bot.msg(user, "Removed report #%d" % (qid))
534 except:
535 bot.msg(user, "Failed!")
2520caee 536
fb20be7c 537@lib.hook(needchan=False)
5f03d045 538@lib.help("[<user>]", "shows you or someone else's rank")
fb20be7c 539def rank(bot, user, chan, realtarget, *args):
6bdfec48 540 if chan is not None and realtarget == chan.name: replyto = chan
80d02bd8 541 else: replyto = user
542
c695f740 543 if len(args) != 0: who = args[0]
544 else: who = user
545
77c61775 546 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 547
fb20be7c 548@lib.hook(needchan=False)
5f03d045 549@lib.help(None, "shows top10 list")
fb20be7c 550def top10(bot, user, chan, realtarget, *args):
77c61775 551 if len(state.db['ranks']) == 0:
552 return bot.msg(state.db['chan'], "No one is ranked!")
fadbf980 553
8ef938d0 554 max = len(state.db['ranks'])
555 if max > 10:
556 max = 10
2bb267e0 557 replylist = ', '.join(["%s (%s) %s" % (person(x), country(x), pts(x)) for x in range(max)])
00ccae72 558 bot.msg(state.db['chan'], "Top 10: %s" % (replylist))
77c61775 559
fb20be7c 560@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 561@lib.help("<target score>", "changes the target score for this round")
fb20be7c 562def settarget(bot, user, chan, realtarget, *args):
77c61775 563 try:
564 state.db['target'] = int(args[0])
565 bot.msg(state.db['chan'], "Target has been changed to %s points!" % (state.db['target']))
38b29993 566
7bd5e7d5 567 if state.pointvote is not None:
568 state.pointvote.cancel()
569 state.pointvote = None
38b29993 570 bot.msg(state.db['chan'], "Vote has been cancelled!")
7bd5e7d5 571 except Exception as e:
572 print e
77c61775 573 bot.msg(user, "Failed to set target.")
574
fb20be7c 575@lib.hook(needchan=False)
5f03d045 576@lib.help("<option>", "votes for a trarget score for next round")
fb20be7c 577def vote(bot, user, chan, realtarget, *args):
7bd5e7d5 578 if state.pointvote is not None:
38b29993 579 if int(args[0]) in state.voteamounts:
580 state.voteamounts[int(args[0])] += 1
581 bot.msg(user, "Your vote has been recorded.")
582 else:
583 bot.msg(user, "Sorry - that's not an option!")
584 else:
585 bot.msg(user, "There's no vote in progress.")
586
fb20be7c 587@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 588@lib.help("<number>", "sets the max missed question before game stops")
fb20be7c 589def maxmissed(bot, user, chan, realtarget, *args):
c4763e66 590 try:
591 state.db['maxmissedquestions'] = int(args[0])
592 bot.msg(state.db['chan'], "Max missed questions before round ends has been changed to %s." % (state.db['maxmissedquestions']))
593 except:
594 bot.msg(user, "Failed to set maxmissed.")
595
fb20be7c 596@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 597@lib.help("<seconds>", "sets the time between hints")
fb20be7c 598def hinttimer(bot, user, chan, realtarget, *args):
c4763e66 599 try:
600 state.db['hinttimer'] = float(args[0])
601 bot.msg(state.db['chan'], "Time between hints has been changed to %s." % (state.db['hinttimer']))
602 except:
603 bot.msg(user, "Failed to set hint timer.")
604
fb20be7c 605@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 606@lib.help("<number>", "sets the number of hints given")
fb20be7c 607def hintnum(bot, user, chan, realtarget, *args):
c4763e66 608 try:
609 state.db['hintnum'] = int(args[0])
610 bot.msg(state.db['chan'], "Max number of hints has been changed to %s." % (state.db['hintnum']))
611 except:
612 bot.msg(user, "Failed to set hintnum.")
613
fb20be7c 614@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 615@lib.help("<seconds>", "sets the pause between questions")
fb20be7c 616def questionpause(bot, user, chan, realtarget, *args):
442ed923 617 try:
618 state.db['questionpause'] = float(args[0])
619 bot.msg(state.db['chan'], "Pause between questions has been changed to %s." % (state.db['questionpause']))
620 except:
621 bot.msg(user, "Failed to set questionpause.")
622
fb20be7c 623@lib.hook(glevel=1, needchan=False)
5f03d045 624@lib.help("<full question>", "finds a qid given a complete question")
fb20be7c 625def findq(bot, user, chan, realtarget, *args):
4d98501a 626 if len(args) == 0:
627 bot.msg(user, "You need to specify the question.")
628 return
629
630 searchkey = ' '.join(args).lower()
631 matches = [str(i) for i in range(len(state.db['questions'])) if state.db['questions'][i][0].lower() == searchkey]
632 if len(matches) > 1:
633 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
634 elif len(matches) == 1:
635 bot.msg(user, "One match: %s" % (matches[0]))
636 else:
637 bot.msg(user, "No match.")
638
639@lib.hook(glevel=1, needchan=False)
5f03d045 640@lib.help("<regex>", "finds a qid given a regex or partial question")
4d98501a 641def findqre(bot, user, chan, realtarget, *args):
bf8676ae 642 if len(args) == 0:
643 bot.msg(user, "You need to specify a search string.")
644 return
645
4d98501a 646 searcher = re.compile(' '.join(args), re.IGNORECASE)
aaa67e6d 647 matches = [str(i) for i in range(len(state.db['questions'])) if searcher.search(state.db['questions'][i][0]) is not None]
bf8676ae 648 if len(matches) > 25:
649 bot.msg(user, "Too many matches! (>25)")
650 elif len(matches) > 1:
c4763e66 651 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
652 elif len(matches) == 1:
653 bot.msg(user, "One match: %s" % (matches[0]))
654 else:
655 bot.msg(user, "No match.")
656
b9daa51a 657@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 658@lib.help("<qid>", "displays the q*a for a qid")
b9daa51a 659def showq(bot, user, chan, realtarget, *args):
660 try:
661 qid = int(args[0])
662 except:
663 bot.msg(user, "Specify a numeric question ID.")
664 return
665 try:
666 q = state.db['questions'][qid]
667 except:
668 bot.msg(user, "ID not valid.")
669 return
670 bot.msg(user, "%s: %s*%s" % (qid, q[0], q[1]))
671
fb20be7c 672@lib.hook(('delq', 'deleteq'), glevel=lib.STAFF, needchan=False)
5f03d045 673@lib.help("<qid>", "removes a question from the database")
fb20be7c 674def delq(bot, user, chan, realtarget, *args):
c4763e66 675 try:
676 backup = state.db['questions'][int(args[0])]
677 del state.db['questions'][int(args[0])]
b9daa51a 678 state.savedb()
ebee6edb 679 bot.msg(user, "Deleted %s*%s" % (backup[0], backup[1]))
c4763e66 680 except:
b9daa51a 681 bot.msg(user, "Couldn't delete that question. %r" % (e))
c4763e66 682
fb20be7c 683@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 684@lib.help("<q>*<a>", "adds a question")
fb20be7c 685def addq(bot, user, chan, realtarget, *args):
c4763e66 686 line = ' '.join([str(arg) for arg in args])
687 linepieces = line.split('*')
688 if len(linepieces) < 2:
689 bot.msg(user, "Error: need <question>*<answer>")
690 return
691 question = linepieces[0].strip()
692 answer = linepieces[1].strip()
ebee6edb 693 state.db['questions'].append([question, answer])
b9daa51a 694 state.savedb()
c4763e66 695 bot.msg(user, "Done. Question is #%s" % (len(state.db['questions'])-1))
696
697
fb20be7c 698@lib.hook(needchan=False)
699def triviahelp(bot, user, chan, realtarget, *args):
2bb267e0 700 bot.slowmsg(user, "START")
701 bot.slowmsg(user, "TOP10")
702 bot.slowmsg(user, "POINTS [<user>]")
703 bot.slowmsg(user, "RANK [<user>]")
704 bot.slowmsg(user, "BADQ <reason> (include info to identify question)")
9306587e 705 if user.glevel >= 1:
b9daa51a 706 bot.slowmsg(user, "SKIP (KNOWN)")
707 bot.slowmsg(user, "STOP (KNOWN)")
4d98501a 708 bot.slowmsg(user, "FINDQ <full question> (KNOWN)")
709 bot.slowmsg(user, "FINDQRE <regex> (KNOWN)")
b9daa51a 710 bot.slowmsg(user, "SETNEXTID <qid> (KNOWN)")
9306587e 711 if user.glevel >= lib.STAFF:
b9daa51a 712 bot.slowmsg(user, "GIVE <user> [<points>] (STAFF)")
713 bot.slowmsg(user, "SETNEXT <q>*<a> (STAFF)")
714 bot.slowmsg(user, "ADDQ <q>*<a> (STAFF)")
715 bot.slowmsg(user, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
716 bot.slowmsg(user, "SHOWQ <qid> (STAFF)")
717 bot.slowmsg(user, "BADQS (STAFF)")
718 bot.slowmsg(user, "CLEARBADQS (STAFF)")
719 bot.slowmsg(user, "DELBADQ <reportid> (STAFF)")
9306587e 720 if user.glevel >= lib.ADMIN:
b9daa51a 721 bot.slowmsg(user, "SETTARGET <points> (ADMIN)")
722 bot.slowmsg(user, "MAXMISSED <questions> (ADMIN)")
723 bot.slowmsg(user, "HINTTIMER <float seconds> (ADMIN)")
724 bot.slowmsg(user, "HINTNUM <hints> (ADMIN)")
725 bot.slowmsg(user, "QUESTIONPAUSE <float seconds> (ADMIN)")
b5c89dfb 726
6374d61f 727@lib.hooknum(417)
728def num_417(bot, textline):
93ce52fd 729# bot.fastmsg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
442ed923 730 state.nextquestion(qskipped=False, skipwait=True)
6374d61f 731
f8cc0124 732@lib.hooknum(332)
733def num_TOPIC(bot, textline):
734 pieces = textline.split(None, 4)
735 chan = pieces[3]
736 if chan != state.db['chan']:
737 return
738 gottopic = pieces[4][1:]
739
740 formatted = state.db['topicformat'] % {
741 'chan': state.db['chan'],
8ef938d0 742 'top1': "%s (%s)" % (person(0), pts(0)),
743 'top3': '/'.join([
744 "%s (%s)" % (person(x), pts(x))
745 for x in range(3) if x < len(state.db['ranks'])
746 ]),
747 'top3c': ' '.join([
748 "%s (%s, %s)" % (person(x), pts(x), country(x))
749 for x in range(3) if x < len(state.db['ranks'])
750 ]),
751 'top10': ' '.join([
752 "%s (%s)" % (person(x), pts(x))
753 for x in range(10) if x < len(state.db['ranks'])
754 ]),
755 'top10c': ' '.join([
756 "%s (%s, %s)" % (person(x), pts(x), country(x))
757 for x in range(10) if x < len(state.db['ranks'])
758 ]),
5f42c250 759 'lastwinner': state.db['lastwinner'],
760 'lastwon': time.strftime("%b %d", time.gmtime(state.db['lastwon'])),
f8cc0124 761 'target': state.db['target'],
762 }
763 if gottopic != formatted:
764 state.getbot().conn.send("TOPIC %s :%s" % (state.db['chan'], formatted))
765
b5c89dfb 766
767def specialQuestion(oldq):
ebee6edb 768 newq = [oldq[0], oldq[1]]
769 qtype = oldq[0].upper()
b5c89dfb 770
771 if qtype == "!MONTH":
ebee6edb 772 newq[0] = "What month is it currently (in UTC)?"
773 newq[1] = time.strftime("%B", time.gmtime()).lower()
b5c89dfb 774 elif qtype == "!MATH+":
775 randnum1 = random.randrange(0, 11)
776 randnum2 = random.randrange(0, 11)
ebee6edb 777 newq[0] = "What is %d + %d?" % (randnum1, randnum2)
778 newq[1] = spellout(randnum1+randnum2)
b5c89dfb 779 return newq
780
781def spellout(num):
782 return [
00ccae72 783 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
b5c89dfb 784 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
785 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"
786 ][num]