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