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