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