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