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