1 # Erebus IRC bot - Author: Erebus Team
2 # vim: fileencoding=utf-8
4 # This file is released into the public domain; see http://unlicense.org/
6 from __future__
import print_function
10 'author': 'Erebus Team',
11 'license': 'public domain',
14 'softdeps': ['help','userinfo'],
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
):
30 except Exception: pass
31 return lib
.modstop(*args
, **kwargs
)
34 import json
, random
, threading
, re
, time
, datetime
, os
, sys
36 if sys
.version_info
.major
< 3:
37 timerbase
= threading
._Timer
38 stringbase
= basestring
41 timerbase
= threading
.Timer
47 except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
49 def findnth(haystack
, needle
, n
): #http://stackoverflow.com/a/1884151
50 parts
= haystack
.split(needle
, n
+1)
53 return len(haystack
)-len(parts
[-1])-len(needle
)
55 def person(num
, throwindexerror
=False):
57 return state
.db
['users'][state
.db
['ranks'][num
]]['realnick']
66 return str(state
.db
['users'][state
.db
['ranks'][num
]]['points'])
70 def country(num
, default
="??"):
72 return lib
.mod('userinfo').get(person(num
), 'country', default
=default
).upper()
74 return default
.upper()
76 class MyTimer(timerbase
):
77 def __init__(self
, *args
, **kwargs
):
78 timerbase
.__init
__(self
, *args
, **kwargs
)
81 class TriviaState(object):
82 def __init__(self
, parent
=None, pointvote
=False):
84 self
.streak_holder
= None
85 if parent
is not None:
86 self
.gotParent(parent
, pointvote
)
88 def gotParent(self
, parent
, pointvote
=False):
90 self
.questionfile
= self
.parent
.cfg
.get('trivia', 'jsonpath', default
="./modules/trivia.json")
91 self
.db
= json
.load(open(self
.questionfile
, "r"))
92 self
.questions
= self
.db
['questions'][self
.db
['category']]
93 self
.chan
= self
.db
['chan']
97 self
.nextquestiontimer
= None
100 self
.hintanswer
= None
102 self
.revealpossibilities
= None
103 self
.gameover
= False
104 self
.missedquestions
= 0
108 if 'lastwon' not in self
.db
or self
.db
['lastwon'] is None:
109 self
.db
['lastwon'] = time
.time()
112 self
.getchan().fastmsg("Vote for the next round target points! Options: %s. Vote using !vote <choice>" % (', '.join([str(x
) for x
in self
.db
['targetoptions']])))
113 self
.getchan().fastmsg("You have %s seconds." % (self
.db
['votetimer']))
114 self
.voteamounts
= dict([(x
, 0) for x
in self
.db
['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
115 self
.pointvote
= MyTimer(self
.db
['votetimer'], self
.endPointVote
)
116 self
.pointvote
.start()
118 self
.pointvote
= None
124 self
.steptimer
.cancel()
125 self
.steptimer
= None
128 self
.nextquestiontimer
.cancel()
129 self
.nextquestiontimer
= None
132 def savedb(self
): #returns whether or not it was able to save
133 if json
is not None and json
.dump
is not None:
134 # json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
135 dbjson
= json
.dumps(self
.db
)
136 # we have to do a dance to save the file to make the update atomic, and also because Py3 doesn't have os.tempnam in the misguided pursuit of "security"
138 os
.rename(self
.questionfile
, self
.questionfile
+".auto.bak")
140 # TODO replace both of these with tempfile.NamedTemporaryFile(delete=False, dir=os.path.dirname(self.questionfile), prefix='trivia') & f.name :
141 if sys
.version_info
.major
< 3:
142 tmpfn
= os
.tempnam('.', 'trivia')
145 fd
, tmpfn
= tempfile
.mkstemp(dir='.', prefix
='trivia')
149 os
.rename(tmpfn
, self
.questionfile
)
151 except: #if something happens, restore the backup
152 os
.rename(self
.questionfile
+".auto.bak", self
.questionfile
)
155 except OSError: # temp file is already gone
157 except UnboundLocalError:
163 return self
.parent
.channel(self
.chan
)
165 return self
.getchan().bot
167 def nexthint(self
, hintnum
):
168 answer
= self
.hintanswer
170 if self
.hintstr
is None or self
.revealpossibilities
is None or self
.reveal
is None:
172 self
.hintstr
= list(re
.sub(r
'[a-zA-Z0-9]', '*', answer
))
173 self
.revealpossibilities
= list(range(''.join(self
.hintstr
).count('*')))
174 self
.reveal
= int(round(''.join(self
.hintstr
).count('*') * (7/24.0)))
176 oldhintstr
= ''.join(self
.hintstr
)
179 for i
in range(self
.reveal
):
180 revealcount
= random
.choice(self
.revealpossibilities
)
181 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
182 self
.revealpossibilities
.remove(revealcount
)
183 self
.hintstr
[revealloc
] = answer
[revealloc
]
184 except IndexError: pass # if everything is revealed, random.choice will IndexError
185 if oldhintstr
!= ''.join(self
.hintstr
): self
.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
189 if hintnum
< self
.db
['hintnum']:
190 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
191 self
.steptimer
.start()
193 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
194 self
.steptimer
.start()
196 def doGameOver(self
):
197 msg
= self
.getchan().msg
200 msg("\00312THE GAME IS OVER!!!")
201 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
202 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
203 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
204 [msg("%dth place: %s (%s)" % (i
+1, person(i
, True), pts(i
))) for i
in range(3,10)]
205 except IndexError: pass
206 except Exception as e
:
207 msg("DERP! %r" % (e
))
209 if self
.db
['hofpath'] is not None and self
.db
['hofpath'] != '':
212 self
.db
['lastwinner'] = winner
213 self
.db
['lastwon'] = time
.time()
215 self
.db
['users'] = {}
216 self
.db
['ranks'] = []
222 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
223 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
224 self
.getbot().parent
.cfg
.get('trivia', 'con'),
225 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
226 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
227 except: pass #don't care if errors happen updating twitter.
229 self
.__init
__(self
.parent
, True)
233 try: return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
234 except: return "none"
236 try: return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
242 f
= open(self
.db
['hofpath'], 'rb+')
243 for i
in range(self
.db
['hoflines']): #skip this many lines
248 new_line
= self
.db
['hofformat'] % {
249 'date': time
.strftime("%F", time
.gmtime()),
250 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['lastwon'])),
251 'targetscore': self
.db
['target'],
252 'firstperson': person(0),
253 'firstscore': pts(0),
254 'secondperson': person(1),
255 'secondscore': pts(1),
256 'thirdperson': person(2),
257 'thirdscore': pts(2),
259 f
.write(new_line
.encode() + b
"\n")
262 except Exception as e
:
272 def endPointVote(self
):
273 self
.getchan().msg("Voting has ended!")
274 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: (item
[1], -item
[0])) #sort into list of tuples: [(option, number_of_votes), ...]
275 for i
in range(len(votelist
)-1):
277 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
278 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
280 self
.db
['target'] = votelist
[-1][0]
281 self
.pointvote
= None
283 self
.nextquestion() #start the game!
285 def nextquestion(self
, qskipped
=False, iteration
=0, skipwait
=False):
286 self
.lastqid
= self
.curqid
289 self
.lastqtime
= time
.time()
290 if self
.gameover
== True:
291 return self
.doGameOver()
294 self
.streak_holder
= None
295 self
.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
296 self
.missedquestions
+= 1
298 self
.missedquestions
= 0
299 if 'topicformat' in self
.db
and self
.db
['topicformat'] is not None:
300 self
.getbot().conn
.send("TOPIC %s" % (self
.db
['chan']))
302 if isinstance(self
.steptimer
, MyTimer
):
303 self
.steptimer
.cancel()
304 if isinstance(self
.nextquestiontimer
, MyTimer
):
305 self
.nextquestiontimer
.cancel()
306 self
.nextquestiontimer
= None
310 self
.revealpossibilities
= None
315 if self
.missedquestions
> self
.db
['maxmissedquestions']:
317 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game." % (self
.missedquestions
))
321 self
._nextquestion
(iteration
)
323 self
.nextquestiontimer
= MyTimer(self
.db
['questionpause'], self
._nextquestion
, args
=[iteration
])
324 self
.nextquestiontimer
.start()
326 def _nextquestion(self
, iteration
):
327 if self
.nextq
is not None:
331 elif self
.nextqid
is not None:
332 nextqid
= self
.nextqid
333 nextq
= self
.questions
[nextqid
]
334 if len(nextq
) > 2: nextq
[2] = 0 # Unset the time it was last asked.
337 nextqid
= random
.randrange(0, len(self
.questions
))
338 nextq
= self
.questions
[nextqid
]
340 if nextq
[0].startswith("!"):
342 nextq
= specialQuestion(nextq
)
344 if len(nextq
) > 2 and time
.time() - nextq
[2] < 7*24*60*60 and iteration
< 10:
345 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
347 nextq
[2] = time
.time()
349 nextq
.append(time
.time())
351 if isinstance(nextq
[1], stringbase
):
352 nextq
[1] = nextq
[1].lower()
354 nextq
[1] = [s
.lower() for s
in nextq
[1]]
356 qtext
= "\00312,01Next up: "
357 qtext
+= "(%5d)" % (random
.randint(0,99999))
358 qary
= nextq
[0].split(None)
361 spacer
= random
.choice(
362 list(range(0x61,0x7A)) + ([0x20]*4)
364 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(spacer
) #a-z
365 if not self
.getbot().fastmsg(self
.chan
, qtext
): #if message is too long:
366 if not self
.getbot().fastmsg(self
.chan
, "\00312,01Next up: " + ("(%5d)" % (random
.randint(0,99999))) + "\00304,01" + nextq
[0]):
367 if not self
.getbot().fastmsg(self
.chan
, "Next up: " + nextq
[0]):
368 if nextqid
is None: nextqid
= "manual"
369 self
.getbot().slowmsg(self
.chan
, "(Unable to ask question #%s: line too long)" % (nextqid
))
370 return self
._nextquestion
(iteration
) #retry; don't increment the iteration
373 self
.curqid
= nextqid
375 if isinstance(self
.curq
[1], stringbase
): self
.hintanswer
= self
.curq
[1]
376 else: self
.hintanswer
= random
.choice(self
.curq
[1])
378 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
379 self
.steptimer
.start()
381 def checkanswer(self
, answer
):
382 if self
.curq
is None:
384 elif isinstance(self
.curq
[1], stringbase
):
385 return answer
.lower() == self
.curq
[1]
386 else: # assume it's a list or something.
387 return answer
.lower() in self
.curq
[1]
389 def addpoint(self
, user_obj
, count
=1):
390 user_nick
= str(user_obj
)
391 user
= user_nick
.lower() # save this separately as we use both
392 if user
in self
.db
['users']:
393 self
.db
['users'][user
]['points'] += count
395 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
396 self
.db
['ranks'].append(user
)
398 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
399 for i
in range(0, len(self
.db
['ranks'])):
400 nick
= self
.db
['ranks'][i
]
401 self
.db
['users'][nick
]['rank'] = i
403 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
406 return self
.db
['users'][user
]['points']
408 def points(self
, user
):
409 user
= str(user
).lower()
410 if user
in self
.db
['users']:
411 return self
.db
['users'][user
]['points']
415 def rank(self
, user
):
416 user
= str(user
).lower()
417 if user
in self
.db
['users']:
418 return self
.db
['users'][user
]['rank']+1
420 return len(self
.db
['users'])+1
422 def targetuser(self
, user
):
423 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
425 user
= str(user
).lower()
426 if user
in self
.db
['users']:
427 rank
= self
.db
['users'][user
]['rank']
429 return "you're in the lead!"
431 return self
.db
['ranks'][rank
-1]
433 return self
.db
['ranks'][-1]
434 def targetpoints(self
, user
):
435 if len(self
.db
['ranks']) == 0: return 0
437 user
= str(user
).lower()
438 if user
in self
.db
['users']:
439 rank
= self
.db
['users'][user
]['rank']
443 return "("+str(self
.db
['users'][self
.db
['ranks'][rank
-1]]['points'])+")"
445 return "("+str(self
.db
['users'][self
.db
['ranks'][-1]]['points'])+")"
447 state
= TriviaState()
449 # we have to hook this in modstart, since we don't know the channel until then.
450 def trivia_checkanswer(bot
, user
, chan
, *args
):
451 line
= ' '.join([str(arg
) for arg
in args
])
452 if state
.checkanswer(line
):
455 if state
.streak_holder
== user
:
458 if state
.streak
>= 3:
459 bot
.fastmsg(chan
, "\00312%s\003 broke \00304%s\003's streak of \00307%d\003!" % (user
, state
.streak_holder
, state
.streak
))
460 state
.streak_holder
= user
463 response
= "\00312%s\003 got it in %d seconds! The answer was \00312%s\003" % (user
, time
.time()-state
.lastqtime
, line
)
464 if state
.hintanswer
.lower() != line
.lower():
465 response
+= " (hinted answer: %s)" % (state
.hintanswer
)
466 response
+= ". New score: %d. Rank: %d. Target: %s %s" % (state
.addpoint(user
), state
.rank(user
), state
.targetuser(user
), state
.targetpoints(user
))
467 bot
.fastmsg(chan
, response
)
469 if state
.streak
>= 3:
470 bot
.msg(chan
, "\00312%s\003 is on a streak! \00307%d\003 answers correct in a row!" % (user
, state
.streak
))
472 if state
.hintsgiven
== 0:
473 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
477 @lib.hook(glevel
=1, needchan
=False, wantchan
=True)
478 @lib.help(None, "saves the trivia database")
479 def save(bot
, user
, chan
, realtarget
, *args
):
480 if chan
is not None: replyto
= chan
484 bot
.msg(replyto
, "Save successful.")
486 bot
.msg(replyto
, "Save failed!")
488 @lib.hook(needchan
=False, wantchan
=True)
489 @lib.help("[<user>]", "shows how many points you or someone has")
490 def points(bot
, user
, chan
, realtarget
, *args
):
491 if chan
is not None: eplyto
= chan
494 if len(args
) != 0: who
= args
[0]
497 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
499 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
500 @lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
502 def give(bot
, user
, chan
, realtarget
, *args
):
505 numpoints
= int(args
[1])
508 balance
= state
.addpoint(whoto
, numpoints
)
510 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
512 @lib.hook(glevel
=1, needchan
=False)
513 @lib.help("<qid>", "sets next question to one in the database")
515 def setnextid(bot
, user
, chan
, realtarget
, *args
):
519 bot
.msg(user
, "Error: QID must be a number.")
521 if qid
>= len(state
.questions
):
522 bot
.msg(user
, "Error: no such QID.")
525 bot
.msg(user
, "Done. Next question is %d: %s" % (qid
, state
.questions
[qid
][0]), truncate
=True)
527 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
528 @lib.help("<q>*<a>", "sets next question to one not in database")
530 def setnext(bot
, user
, chan
, realtarget
, *args
):
531 line
= ' '.join([str(arg
) for arg
in args
])
532 linepieces
= line
.split('*', 1)
533 if len(linepieces
) < 2:
534 bot
.msg(user
, "Error: need <question>*<answer>")
536 question
= linepieces
[0].strip()
537 answer
= linepieces
[1].strip()
538 state
.nextq
= [question
, answer
]
539 bot
.msg(user
, "Done.")
541 @lib.hook(glevel
=1, needchan
=False)
542 @lib.help(None, "skips to next question")
543 def skip(bot
, user
, chan
, realtarget
, *args
):
544 state
.nextquestion(qskipped
=True, skipwait
=True)
546 @lib.hook(('start','trivia'), needchan
=False, wantchan
=True)
547 @lib.help(None, "starts the trivia game")
548 def start(bot
, user
, chan
, realtarget
, *args
):
549 if chan
is not None: replyto
= chan
552 if chan
is not None and chan
.name
!= state
.db
['chan']:
553 bot
.msg(replyto
, "That command is only valid in %s" % (state
.db
['chan']))
556 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
557 bot
.msg(state
.db
['chan'], "%s has started the game!" % (user
))
558 state
.nextquestion(skipwait
=True)
559 elif state
.pointvote
is not None:
560 bot
.msg(user
, "There's a vote in progress!")
562 bot
.msg(user
, "Game is already started!")
564 @lib.hook('stop', glevel
=1, needchan
=False)
565 @lib.help(None, "stops the trivia game")
566 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
568 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
570 bot
.msg(user
, "Game isn't running.")
576 state
.steptimer
.cancel()
577 except Exception as e
:
578 print("!!! steptimer.cancel(): %s %r" % (e
,e
))
579 state
.steptimer
= None
581 state
.nextquestiontimer
.cancel()
582 except Exception as e
:
583 print("!!! nextquestiontimer.cancel(): %s %r" % (e
,e
))
584 state
.nextquestiontimer
= None
587 @lib.hook(needchan
=False)
588 @lib.help("<reason>", "reports a bad question to the admins")
590 def badq(bot
, user
, chan
, realtarget
, *args
):
591 lastqid
= state
.lastqid
592 curqid
= state
.curqid
594 reason
= ' '.join(args
)
595 state
.db
['badqs'].append([state
.db
['category'], lastqid
, curqid
, reason
])
596 bot
.msg(user
, "Reported bad question.")
598 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
599 @lib.help(None, "shows a list of BADQ reports")
600 def badqs(bot
, user
, chan
, realtarget
, *args
):
601 if len(state
.db
['badqs']) == 0:
602 bot
.msg(user
, "No reports.")
604 for i
in range(len(state
.db
['badqs'])):
606 report
= state
.db
['badqs'][i
]
607 bot
.msg(user
, "Report #%d: Cat=%s LastQ=%r CurQ=%r: %s" % (i
, report
[0], report
[1], report
[2], report
[3]))
608 try: lq
= state
.db
['questions'][report
[0]][int(report
[1])]
609 except Exception as e
: lq
= (None,None)
610 try: cq
= state
.db
['questions'][report
[0]][int(report
[2])]
611 except Exception as e
: cq
= (None, None)
612 bot
.msg(user
, "- Last: %s*%s" % (lq
[0], lq
[1]))
613 bot
.msg(user
, "- Curr: %s*%s" % (cq
[0], cq
[1]))
614 except Exception as e
:
615 bot
.msg(user
, "- Exception: %r" % (e
))
617 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
618 @lib.hook(None, "clears list of BADQ reports")
619 def clearbadqs(bot
, user
, chan
, realtarget
, *args
):
620 state
.db
['badqs'] = []
621 bot
.msg(user
, "Cleared reports.")
623 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
624 @lib.hook("<badqid>", "removes a BADQ report")
626 def delbadq(bot
, user
, chan
, realtarget
, *args
):
629 del state
.db
['badqs'][qid
]
630 bot
.msg(user
, "Removed report #%d" % (qid
))
632 bot
.msg(user
, "Failed!")
634 @lib.hook(needchan
=False, wantchan
=True)
635 @lib.help("[<user>]", "shows you or someone else's rank")
636 def rank(bot
, user
, chan
, realtarget
, *args
):
637 if chan
is not None: replyto
= chan
640 if len(args
) != 0: who
= args
[0]
643 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
)))
645 @lib.hook(needchan
=False)
646 @lib.help(None, "shows top10 list")
647 def top10(bot
, user
, chan
, realtarget
, *args
):
648 if len(state
.db
['ranks']) == 0:
649 return bot
.msg(state
.db
['chan'], "No one is ranked!")
651 max = len(state
.db
['ranks'])
654 replylist
= ', '.join(["%s (%s) %s" % (person(x
), country(x
), pts(x
)) for x
in range(max)])
655 bot
.msg(state
.db
['chan'], "Game is to %s! Top 10: %s" % (state
.db
['target'], replylist
))
657 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
658 @lib.help("<target score>", "changes the target score for this round")
659 def settarget(bot
, user
, chan
, realtarget
, *args
):
661 state
.db
['target'] = int(args
[0])
662 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
664 if state
.pointvote
is not None:
665 state
.pointvote
.cancel()
666 state
.pointvote
= None
667 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
668 except Exception as e
:
670 bot
.msg(user
, "Failed to set target.")
672 @lib.hook(needchan
=False)
673 @lib.help("<option>", "votes for a trarget score for next round")
674 def vote(bot
, user
, chan
, realtarget
, *args
):
675 if state
.pointvote
is not None:
676 if int(args
[0]) in state
.voteamounts
:
677 state
.voteamounts
[int(args
[0])] += 1
678 bot
.msg(user
, "Your vote has been recorded.")
680 bot
.msg(user
, "Sorry - that's not an option!")
682 bot
.msg(user
, "There's no vote in progress.")
684 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
685 @lib.help("<number>", "sets the max missed question before game stops")
686 def maxmissed(bot
, user
, chan
, realtarget
, *args
):
688 state
.db
['maxmissedquestions'] = int(args
[0])
689 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
691 bot
.msg(user
, "Failed to set maxmissed.")
693 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
694 @lib.help("<seconds>", "sets the time between hints")
695 def hinttimer(bot
, user
, chan
, realtarget
, *args
):
697 state
.db
['hinttimer'] = float(args
[0])
698 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
700 bot
.msg(user
, "Failed to set hint timer.")
702 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
703 @lib.help("<number>", "sets the number of hints given")
704 def hintnum(bot
, user
, chan
, realtarget
, *args
):
706 state
.db
['hintnum'] = int(args
[0])
707 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
709 bot
.msg(user
, "Failed to set hintnum.")
711 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
712 @lib.help("<seconds>", "sets the pause between questions")
713 def questionpause(bot
, user
, chan
, realtarget
, *args
):
715 state
.db
['questionpause'] = float(args
[0])
716 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
718 bot
.msg(user
, "Failed to set questionpause.")
720 @lib.hook(glevel
=1, needchan
=False)
721 @lib.help("[@category] <question>", "finds a question (qid) given a (partial) question")
723 def findq(bot
, user
, chan
, realtarget
, *args
):
725 if args
[0].startswith("@"):
726 cat
= args
.pop(0)[1:].lower()
727 questions
= state
.db
['questions'][cat
]
729 questions
= state
.questions
731 pattern
= re
.escape(' '.join(args
))
732 return _findq(questions
, pattern
)
734 @lib.hook(glevel
=1, needchan
=False)
735 @lib.help("[@<category>] <regex>", "finds a question (qid) given a regex")
737 def findqre(bot
, user
, chan
, realtarget
, *args
):
739 if args
[0].startswith("@"):
740 cat
= args
.pop(0)[1:].lower()
741 questions
= state
.db
['questions'][cat
]
743 questions
= state
.questions
744 pattern
= ' '.join(args
)
745 return _findq(questions
, pattern
)
747 @lib.hook(glevel
=1, needchan
=False)
748 @lib.help("[@<category>] <phrase>", "finds a question (qid) given a (partial) question or answer")
750 def findqa(bot
, user
, chan
, realtarget
, *args
):
752 if args
[0].startswith("@"):
753 cat
= args
.pop(0)[1:].lower()
754 questions
= state
.db
['questions'][cat
]
756 questions
= state
.questions
757 pattern
= ' '.join(args
)
758 return _findq(questions
, pattern
, True)
760 def _findq(questions
, pattern
, check_answers
=False):
761 searcher
= re
.compile(pattern
, re
.IGNORECASE
)
762 matches
= [i
for i
in range(len(questions
)) if searcher
.search(questions
[i
][0]) is not None or (check_answers
and searcher
.search(questions
[i
][1]) is not None)]
763 if len(matches
) > 25:
764 return "Too many matches! (>25)"
765 elif len(matches
) > 1:
766 return "Multiple matches: %s" % (', '.join(str(x
) for x
in matches
))
767 elif len(matches
) == 1:
769 return "One match: %s %s*%s" % (i
, questions
[i
][0], questions
[i
][1])
773 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
774 @lib.help("[@<category>] <qid>", "displays the q*a for a qid", "category defaults to current")
775 def showq(bot
, user
, chan
, realtarget
, *args
):
777 if args
[0].startswith("@"):
778 cat
= args
.pop(0)[1:].lower()
779 questions
= state
.db
['questions'][cat
]
781 questions
= state
.questions
786 bot
.msg(user
, "Specify a numeric question ID.")
791 bot
.msg(user
, "ID not valid.")
793 bot
.msg(user
, "%s: %s*%s" % (qid
, q
[0], q
[1]), True)
795 @lib.hook(('delq', 'deleteq'), glevel
=lib
.STAFF
, needchan
=False)
796 @lib.help("[@<category>] <qid>", "removes a question from the database")
797 def delq(bot
, user
, chan
, realtarget
, *args
):
799 if args
[0].startswith("@"):
800 cat
= args
.pop(0)[1:].lower()
801 questions
= state
.db
['questions'][cat
]
803 questions
= state
.questions
806 backup
= questions
[int(args
[0])]
807 del questions
[int(args
[0])]
808 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]), True)
809 except Exception as e
:
810 bot
.msg(user
, "Couldn't delete that question. %r" % (e
))
812 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
813 @lib.help("[@<category>] <q>*<a>", "adds a question")
814 def addq(bot
, user
, chan
, realtarget
, *args
):
816 if args
[0].startswith("@"):
817 cat
= args
.pop(0)[1:].lower()
818 questions
= state
.db
['questions'][cat
]
820 questions
= state
.questions
822 line
= ' '.join([str(arg
) for arg
in args
])
823 linepieces
= line
.split('*', 1)
824 if len(linepieces
) < 2:
825 bot
.msg(user
, "Error: need <question>*<answer>")
827 question
= linepieces
[0].strip()
828 answer
= linepieces
[1].strip()
829 questions
.append([question
, answer
])
830 bot
.msg(user
, "Done. Question is #%s" % (len(questions
)-1))
832 @lib.hook(needchan
=False)
833 @lib.help(None, "show current category")
834 def showcat(bot
, user
, chan
, realtarget
, *args
):
835 bot
.msg(user
, "Current category: %s" % (state
.db
['category']))
837 @lib.hook(glevel
=1, needchan
=False)
838 @lib.help("<category>", "change category")
839 def setcat(bot
, user
, chan
, realtarget
, *args
):
840 category
= args
[0].lower()
841 if category
in state
.db
['questions']:
842 state
.db
['category'] = category
843 state
.questions
= state
.db
['questions'][category
]
844 bot
.msg(user
, "Changed category to %s" % (category
))
846 bot
.msg(user
, "That category doesn't exist.")
848 @lib.hook(needchan
=False)
849 @lib.help(None, "list categories", "the current category will be marked with a *")
850 def listcats(bot
, user
, chan
, realtarget
, *args
):
851 cats
= ["%s%s (%d)" % ("*" if c
== state
.db
['category'] else "", c
, len(state
.db
['questions'][c
])) for c
in state
.db
['questions'].keys()]
852 bot
.msg(user
, "Categories: %s" % (', '.join(cats
)))
854 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
855 @lib.help("<category>", "adds an empty category")
856 def addcat(bot
, user
, chan
, realtarget
, *args
):
857 category
= args
[0].lower()
858 if category
not in state
.db
['questions']:
859 state
.db
['questions'][category
] = []
860 bot
.msg(user
, "Added category %s" % (category
))
862 bot
.msg(user
, "Category already exists.")
864 @lib.hook(glevel
=lib
.MANAGER
, needchan
=False)
865 @lib.help("<category>", "deletes an entire category")
866 def delcat(bot
, user
, chan
, realtarget
, *args
):
867 category
= args
[0].lower()
868 if category
== state
.db
['category']:
869 bot
.msg(user
, "Category currently in use!")
870 elif category
in state
.db
['questions']:
871 length
= len(state
.db
['questions'][category
])
872 del state
.db
['questions'][category
]
873 bot
.msg(user
, "Deleted category %s (%d questions)" % (category
, length
))
875 bot
.msg(user
, "Category does not exist.")
877 @lib.hook(needchan
=False)
878 def triviahelp(bot
, user
, chan
, realtarget
, *args
):
879 bot
.slowmsg(user
, "START")
880 bot
.slowmsg(user
, "TOP10")
881 bot
.slowmsg(user
, "POINTS [<user>]")
882 bot
.slowmsg(user
, "RANK [<user>]")
883 bot
.slowmsg(user
, "BADQ <reason> (include info to identify question)")
885 bot
.slowmsg(user
, "SKIP (KNOWN)")
886 bot
.slowmsg(user
, "STOP (KNOWN)")
887 bot
.slowmsg(user
, "FINDQ <full question> (KNOWN)")
888 bot
.slowmsg(user
, "FINDQRE <regex> (KNOWN)")
889 bot
.slowmsg(user
, "SETNEXTID <qid> (KNOWN)")
890 if user
.glevel
>= lib
.STAFF
:
891 bot
.slowmsg(user
, "GIVE <user> [<points>] (STAFF)")
892 bot
.slowmsg(user
, "SETNEXT <q>*<a> (STAFF)")
893 bot
.slowmsg(user
, "ADDQ <q>*<a> (STAFF)")
894 bot
.slowmsg(user
, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
895 bot
.slowmsg(user
, "SHOWQ <qid> (STAFF)")
896 bot
.slowmsg(user
, "BADQS (STAFF)")
897 bot
.slowmsg(user
, "CLEARBADQS (STAFF)")
898 bot
.slowmsg(user
, "DELBADQ <reportid> (STAFF)")
899 if user
.glevel
>= lib
.ADMIN
:
900 bot
.slowmsg(user
, "SETTARGET <points> (ADMIN)")
901 bot
.slowmsg(user
, "MAXMISSED <questions> (ADMIN)")
902 bot
.slowmsg(user
, "HINTTIMER <float seconds> (ADMIN)")
903 bot
.slowmsg(user
, "HINTNUM <hints> (ADMIN)")
904 bot
.slowmsg(user
, "QUESTIONPAUSE <float seconds> (ADMIN)")
906 @lib.hooknum(332) # topic is...
907 @lib.hooknum(331) # no topic set
908 def num_TOPIC(bot
, textline
):
909 pieces
= textline
.split(None, 4)
911 if chan
!= state
.db
['chan']:
913 gottopic
= pieces
[4][1:]
915 formatted
= state
.db
['topicformat'] % {
916 'chan': state
.db
['chan'],
917 'top1': "%s (%s)" % (person(0), pts(0)),
919 "%s (%s)" % (person(x
), pts(x
))
920 for x
in range(3) if x
< len(state
.db
['ranks'])
923 "%s (%s) %s" % (person(x
), country(x
), pts(x
))
924 for x
in range(3) if x
< len(state
.db
['ranks'])
927 "%s (%s)" % (person(x
), pts(x
))
928 for x
in range(10) if x
< len(state
.db
['ranks'])
931 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
932 for x
in range(10) if x
< len(state
.db
['ranks'])
934 'lastwinner': state
.db
['lastwinner'],
935 'lastwon': time
.strftime("%b %d", time
.gmtime(state
.db
['lastwon'])),
936 'target': state
.db
['target'],
937 'category': state
.db
['category'],
939 if gottopic
!= formatted
:
940 state
.getbot().conn
.send(bot
.parent
.cfg
.get('trivia', 'topiccommand', default
="TOPIC %(chan)s :%(topic)s") % {'chan': state.db['chan'], 'topic': formatted}
)
943 def specialQuestion(oldq
):
944 newq
= [oldq
[0], oldq
[1]]
945 qtype
= oldq
[0].upper()
947 if qtype
== "!MONTH":
948 newq
[0] = "What month is it currently (in UTC)?"
949 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
950 elif qtype
== "!MATH+":
952 maxnum
= int(oldq
[1])
955 randnum1
= random
.randrange(0, maxnum
+1)
956 randnum2
= random
.randrange(0, maxnum
+1)
957 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
958 newq
[1] = spellout(randnum1
+randnum2
)
959 elif qtype
== "!ALGEBRA+":
961 num1
, num2
= [int(i
) for i
in oldq
[1].split('!')]
964 randnum1
= random
.randrange(0, num1
+1)
965 randnum2
= random
.randrange(randnum1
, num2
+1)
966 newq
[0] = "What is x? %d = %d + x" % (randnum2
, randnum1
)
967 newq
[1] = spellout(randnum2
-randnum1
)
968 else: pass #default to not modifying
972 ones
= ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
973 teens
= ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
974 tens
= ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
979 ihundreds
= num
/ 100
980 itens
= num
% 100 / 10
985 buf
.append("%s hundred" % (ones
[ihundreds
]))
987 buf
.append(tens
[itens
])
989 buf
.append(teens
[iones
])
991 buf
.append(ones
[iones
])
994 # "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
995 # "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
996 # "sixteen", "seventeen", "eighteen", "nineteen", "twenty"
1001 answers
=__import__('collections').defaultdict(int)
1002 for a
in (x
[1] for x
in state
.db
['questions']['general']):
1005 for a
, num
in answers
.items():
1007 a2
.sort(key
=lambda v
: v
[1], reverse
=True)