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