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