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