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