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