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