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