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