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