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