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