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