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