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