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',
13 'depends': ['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
39 timerbase
= threading
.Timer
44 except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
46 def findnth(haystack
, needle
, n
): #http://stackoverflow.com/a/1884151
47 parts
= haystack
.split(needle
, n
+1)
50 return len(haystack
)-len(parts
[-1])-len(needle
)
52 def person(num
, throwindexerror
=False):
54 return state
.db
['users'][state
.db
['ranks'][num
]]['realnick']
63 return str(state
.db
['users'][state
.db
['ranks'][num
]]['points'])
67 def country(num
, default
="??"):
68 return lib
.mod('userinfo').get(person(num
), 'country', default
=default
).upper()
70 class MyTimer(timerbase
):
71 def __init__(self
, *args
, **kwargs
):
72 timerbase
.__init
__(self
, *args
, **kwargs
)
75 class TriviaState(object):
76 def __init__(self
, parent
=None, pointvote
=False):
77 if parent
is not None:
78 self
.gotParent(parent
, pointvote
)
80 def gotParent(self
, parent
, pointvote
=False):
82 self
.questionfile
= self
.parent
.cfg
.get('trivia', 'jsonpath', default
="./modules/trivia.json")
83 self
.db
= json
.load(open(self
.questionfile
, "r"))
84 self
.questions
= self
.db
['questions'][self
.db
['category']]
85 self
.chan
= self
.db
['chan']
89 self
.nextquestiontimer
= None
92 self
.hintanswer
= None
94 self
.revealpossibilities
= None
96 self
.missedquestions
= 0
100 if 'lastwon' not in self
.db
or self
.db
['lastwon'] is None:
101 self
.db
['lastwon'] = time
.time()
104 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']])))
105 self
.getchan().msg("You have %s seconds." % (self
.db
['votetimer']))
106 self
.voteamounts
= dict([(x
, 0) for x
in self
.db
['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
107 self
.pointvote
= MyTimer(self
.db
['votetimer'], self
.endPointVote
)
108 self
.pointvote
.start()
110 self
.pointvote
= None
116 self
.steptimer
.cancel()
117 self
.steptimer
= None
120 self
.nextquestiontimer
.cancel()
121 self
.nextquestiontimer
= None
124 def savedb(self
): #returns whether or not it was able to save
125 if json
is not None and json
.dump
is not None:
126 # json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
127 dbjson
= json
.dumps(self
.db
)
129 os
.rename(self
.questionfile
, self
.questionfile
+".auto.bak")
130 tmpfn
= os
.tempnam('.', 'trivia')
135 os
.rename(tmpfn
, self
.questionfile
)
137 except: #if something happens, restore the backup
138 os
.rename(self
.questionfile
+".auto.bak", self
.questionfile
)
141 except OSError: # temp file is already gone
143 raise # we may be better off just swallowing exceptions?
147 return self
.parent
.channel(self
.chan
)
149 return self
.getchan().bot
151 def nexthint(self
, hintnum
):
152 answer
= self
.hintanswer
154 if self
.hintstr
is None or self
.revealpossibilities
is None or self
.reveal
is None:
156 self
.hintstr
= list(re
.sub(r
'[a-zA-Z0-9]', '*', answer
))
157 self
.revealpossibilities
= range(''.join(self
.hintstr
).count('*'))
158 self
.reveal
= int(round(''.join(self
.hintstr
).count('*') * (7/24.0)))
160 oldhintstr
= ''.join(self
.hintstr
)
162 for i
in range(self
.reveal
):
163 revealcount
= random
.choice(self
.revealpossibilities
)
164 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
165 self
.revealpossibilities
.remove(revealcount
)
166 self
.hintstr
[revealloc
] = answer
[revealloc
]
167 if oldhintstr
!= ''.join(self
.hintstr
): self
.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
171 if hintnum
< self
.db
['hintnum']:
172 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
173 self
.steptimer
.start()
175 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
176 self
.steptimer
.start()
178 def doGameOver(self
):
179 msg
= self
.getchan().msg
182 msg("\00312THE GAME IS OVER!!!")
183 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
184 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
185 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
186 [msg("%dth place: %s (%s)" % (i
+1, person(i
, True), pts(i
))) for i
in range(3,10)]
187 except IndexError: pass
188 except Exception as e
:
189 msg("DERP! %r" % (e
))
191 self
.db
['lastwinner'] = winner
192 self
.db
['lastwon'] = time
.time()
194 if self
.db
['hofpath'] is not None and self
.db
['hofpath'] != '':
197 self
.db
['users'] = {}
198 self
.db
['ranks'] = []
203 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
204 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
205 self
.getbot().parent
.cfg
.get('trivia', 'con'),
206 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
207 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
208 except: pass #don't care if errors happen updating twitter.
210 self
.__init
__(self
.parent
, True)
214 try: return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
215 except: return "none"
217 try: return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
222 f
= open(self
.db
['hofpath'], 'rb+')
223 for i
in range(self
.db
['hoflines']): #skip this many lines
228 f
.write((self
.db
['hofformat']+"\n") % {
229 'date': time
.strftime("%F", time
.gmtime()),
230 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['lastwon'])),
231 'targetscore': self
.db
['target'],
232 'firstperson': person(0),
233 'firstscore': pts(0),
234 'secondperson': person(1),
235 'secondscore': pts(1),
236 'thirdperson': person(2),
237 'thirdscore': pts(2),
241 except Exception as e
:
247 def endPointVote(self
):
248 self
.getchan().msg("Voting has ended!")
249 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
250 for i
in range(len(votelist
)-1):
252 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
253 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
255 self
.db
['target'] = votelist
[-1][0]
256 self
.pointvote
= None
258 self
.nextquestion() #start the game!
260 def nextquestion(self
, qskipped
=False, iteration
=0, skipwait
=False):
261 self
.lastqid
= self
.curqid
264 if self
.gameover
== True:
265 return self
.doGameOver()
267 self
.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
268 self
.missedquestions
+= 1
270 self
.missedquestions
= 0
271 if 'topicformat' in self
.db
and self
.db
['topicformat'] is not None:
272 self
.getbot().conn
.send("TOPIC %s" % (self
.db
['chan']))
274 if isinstance(self
.steptimer
, MyTimer
):
275 self
.steptimer
.cancel()
276 if isinstance(self
.nextquestiontimer
, MyTimer
):
277 self
.nextquestiontimer
.cancel()
278 self
.nextquestiontimer
= None
282 self
.revealpossibilities
= None
287 if self
.missedquestions
> self
.db
['maxmissedquestions']:
289 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game." % (self
.missedquestions
))
293 self
._nextquestion
(iteration
)
295 self
.nextquestiontimer
= MyTimer(self
.db
['questionpause'], self
._nextquestion
, args
=[iteration
])
296 self
.nextquestiontimer
.start()
298 def _nextquestion(self
, iteration
):
299 if self
.nextq
is not None:
303 elif self
.nextqid
is not None:
304 nextqid
= self
.nextqid
305 nextq
= self
.questions
[nextqid
]
308 nextqid
= random
.randrange(0, len(self
.questions
))
309 nextq
= self
.questions
[nextqid
]
311 if nextq
[0].startswith("!"):
313 nextq
= specialQuestion(nextq
)
315 if len(nextq
) > 2 and time
.time() - nextq
[2] < 7*24*60*60 and iteration
< 10:
316 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
318 nextq
[2] = time
.time()
320 nextq
.append(time
.time())
322 if isinstance(nextq
[1], basestring
):
323 nextq
[1] = nextq
[1].lower()
325 nextq
[1] = [s
.lower() for s
in nextq
[1]]
327 qtext
= "\00312,01Next up: "
328 qtext
+= "(%5d)" % (random
.randint(0,99999))
329 qary
= nextq
[0].split(None)
332 spacer
= random
.choice(
333 range(0x61,0x7A) + ([0x20]*4)
335 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(spacer
) #a-z
336 if not self
.getbot().fastmsg(self
.chan
, qtext
): #if message is too long:
337 if nextqid
is None: nextqid
= "manual"
338 self
.getbot().slowmsg(self
.chan
, "(Unable to ask question #%s: line too long)" % (nextqid
))
339 return self
._nextquestion
(iteration
) #retry; don't increment the iteration
342 self
.curqid
= nextqid
344 if isinstance(self
.curq
[1], basestring
): self
.hintanswer
= self
.curq
[1]
345 else: self
.hintanswer
= random
.choice(self
.curq
[1])
347 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
348 self
.steptimer
.start()
350 def checkanswer(self
, answer
):
351 if self
.curq
is None:
353 elif isinstance(self
.curq
[1], basestring
):
354 return answer
.lower() == self
.curq
[1]
355 else: # assume it's a list or something.
356 return answer
.lower() in self
.curq
[1]
358 def addpoint(self
, user_obj
, count
=1):
359 user_nick
= str(user_obj
)
360 user
= user_nick
.lower() # save this separately as we use both
361 if user
in self
.db
['users']:
362 self
.db
['users'][user
]['points'] += count
364 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
365 self
.db
['ranks'].append(user
)
367 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
368 for i
in range(0, len(self
.db
['ranks'])):
369 nick
= self
.db
['ranks'][i
]
370 self
.db
['users'][nick
]['rank'] = i
372 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
375 return self
.db
['users'][user
]['points']
377 def points(self
, user
):
378 user
= str(user
).lower()
379 if user
in self
.db
['users']:
380 return self
.db
['users'][user
]['points']
384 def rank(self
, user
):
385 user
= str(user
).lower()
386 if user
in self
.db
['users']:
387 return self
.db
['users'][user
]['rank']+1
389 return len(self
.db
['users'])+1
391 def targetuser(self
, user
):
392 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
394 user
= str(user
).lower()
395 if user
in self
.db
['users']:
396 rank
= self
.db
['users'][user
]['rank']
398 return "you're in the lead!"
400 return self
.db
['ranks'][rank
-1]
402 return self
.db
['ranks'][-1]
403 def targetpoints(self
, user
):
404 if len(self
.db
['ranks']) == 0: return 0
406 user
= str(user
).lower()
407 if user
in self
.db
['users']:
408 rank
= self
.db
['users'][user
]['rank']
412 return "("+str(self
.db
['users'][self
.db
['ranks'][rank
-1]]['points'])+")"
414 return "("+str(self
.db
['users'][self
.db
['ranks'][-1]]['points'])+")"
416 state
= TriviaState()
418 # we have to hook this in modstart, since we don't know the channel until then.
419 def trivia_checkanswer(bot
, user
, chan
, *args
):
420 line
= ' '.join([str(arg
) for arg
in args
])
421 if state
.checkanswer(line
):
423 if state
.hintanswer
.lower() == line
.lower():
424 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
)))
426 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
)))
427 if state
.hintsgiven
== 0:
428 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
431 @lib.hook(glevel
=1, needchan
=False, wantchan
=True)
432 @lib.help(None, "saves the trivia database")
433 def save(bot
, user
, chan
, realtarget
, *args
):
434 if chan
is not None: replyto
= chan
438 bot
.msg(replyto
, "Save successful.")
440 bot
.msg(replyto
, "Save failed!")
442 @lib.hook(needchan
=False, wantchan
=True)
443 @lib.help("[<user>]", "shows how many points you or someone has")
444 def points(bot
, user
, chan
, realtarget
, *args
):
445 if chan
is not None: eplyto
= chan
448 if len(args
) != 0: who
= args
[0]
451 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
453 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
454 @lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
456 def give(bot
, user
, chan
, realtarget
, *args
):
459 numpoints
= int(args
[1])
462 balance
= state
.addpoint(whoto
, numpoints
)
464 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
466 @lib.hook(glevel
=1, needchan
=False)
467 @lib.help("<qid>", "sets next question to one in the database")
469 def setnextid(bot
, user
, chan
, realtarget
, *args
):
473 bot
.msg(user
, "Error: QID must be a number.")
475 if qid
>= len(state
.questions
):
476 bot
.msg(user
, "Error: no such QID.")
479 bot
.msg(user
, "Done. Next question is %d: %s" % (qid
, state
.questions
[qid
][0]))
481 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
482 @lib.help("<q>*<a>", "sets next question to one not in database")
484 def setnext(bot
, user
, chan
, realtarget
, *args
):
485 line
= ' '.join([str(arg
) for arg
in args
])
486 linepieces
= line
.split('*', 1)
487 if len(linepieces
) < 2:
488 bot
.msg(user
, "Error: need <question>*<answer>")
490 question
= linepieces
[0].strip()
491 answer
= linepieces
[1].strip()
492 state
.nextq
= [question
, answer
]
493 bot
.msg(user
, "Done.")
495 @lib.hook(glevel
=1, needchan
=False)
496 @lib.help(None, "skips to next question")
497 def skip(bot
, user
, chan
, realtarget
, *args
):
498 state
.nextquestion(qskipped
=True, skipwait
=True)
500 @lib.hook(needchan
=False, wantchan
=True)
501 @lib.help(None, "starts the trivia game")
502 def start(bot
, user
, chan
, realtarget
, *args
):
503 if chan
is not None: replyto
= chan
506 if chan
is not None and chan
.name
!= state
.db
['chan']:
507 bot
.msg(replyto
, "That command isn't valid here.")
510 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
511 bot
.msg(state
.db
['chan'], "%s has started the game!" % (user
))
512 state
.nextquestion(skipwait
=True)
513 elif state
.pointvote
is not None:
514 bot
.msg(user
, "There's a vote in progress!")
516 bot
.msg(user
, "Game is already started!")
518 @lib.hook('stop', glevel
=1, needchan
=False)
519 @lib.help(None, "stops the trivia game")
520 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
522 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
524 bot
.msg(user
, "Game isn't running.")
530 state
.steptimer
.cancel()
531 except Exception as e
:
532 print("!!! steptimer.cancel(): %s %r" % (e
,e
))
533 state
.steptimer
= None
535 state
.nextquestiontimer
.cancel()
536 except Exception as e
:
537 print("!!! nextquestiontimer.cancel(): %s %r" % (e
,e
))
538 state
.nextquestiontimer
= None
541 @lib.hook(needchan
=False)
542 @lib.help("<reason>", "reports a bad question to the admins")
544 def badq(bot
, user
, chan
, realtarget
, *args
):
545 lastqid
= state
.lastqid
546 curqid
= state
.curqid
548 reason
= ' '.join(args
)
549 state
.db
['badqs'].append([state
.db
['category'], lastqid
, curqid
, reason
])
550 bot
.msg(user
, "Reported bad question.")
552 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
553 @lib.help(None, "shows a list of BADQ reports")
554 def badqs(bot
, user
, chan
, realtarget
, *args
):
555 if len(state
.db
['badqs']) == 0:
556 bot
.msg(user
, "No reports.")
558 for i
in range(len(state
.db
['badqs'])):
560 report
= state
.db
['badqs'][i
]
561 bot
.msg(user
, "Report #%d: Cat=%s LastQ=%r CurQ=%r: %s" % (i
, report
[0], report
[1], report
[2], report
[3]))
562 try: lq
= state
.db
['questions'][report
[0]][int(report
[1])]
563 except Exception as e
: lq
= (None,None)
564 try: cq
= state
.db
['questions'][report
[0]][int(report
[2])]
565 except Exception as e
: cq
= (None, None)
566 bot
.msg(user
, "- Last: %s*%s" % (lq
[0], lq
[1]))
567 bot
.msg(user
, "- Curr: %s*%s" % (cq
[0], cq
[1]))
568 except Exception as e
:
569 bot
.msg(user
, "- Exception: %r" % (e
))
571 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
572 @lib.hook(None, "clears list of BADQ reports")
573 def clearbadqs(bot
, user
, chan
, realtarget
, *args
):
574 state
.db
['badqs'] = []
575 bot
.msg(user
, "Cleared reports.")
577 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
578 @lib.hook("<badqid>", "removes a BADQ report")
580 def delbadq(bot
, user
, chan
, realtarget
, *args
):
583 del state
.db
['badqs'][qid
]
584 bot
.msg(user
, "Removed report #%d" % (qid
))
586 bot
.msg(user
, "Failed!")
588 @lib.hook(needchan
=False, wantchan
=True)
589 @lib.help("[<user>]", "shows you or someone else's rank")
590 def rank(bot
, user
, chan
, realtarget
, *args
):
591 if chan
is not None: replyto
= chan
594 if len(args
) != 0: who
= args
[0]
597 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
)))
599 @lib.hook(needchan
=False)
600 @lib.help(None, "shows top10 list")
601 def top10(bot
, user
, chan
, realtarget
, *args
):
602 if len(state
.db
['ranks']) == 0:
603 return bot
.msg(state
.db
['chan'], "No one is ranked!")
605 max = len(state
.db
['ranks'])
608 replylist
= ', '.join(["%s (%s) %s" % (person(x
), country(x
), pts(x
)) for x
in range(max)])
609 bot
.msg(state
.db
['chan'], "Top 10: %s" % (replylist
))
611 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
612 @lib.help("<target score>", "changes the target score for this round")
613 def settarget(bot
, user
, chan
, realtarget
, *args
):
615 state
.db
['target'] = int(args
[0])
616 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
618 if state
.pointvote
is not None:
619 state
.pointvote
.cancel()
620 state
.pointvote
= None
621 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
622 except Exception as e
:
624 bot
.msg(user
, "Failed to set target.")
626 @lib.hook(needchan
=False)
627 @lib.help("<option>", "votes for a trarget score for next round")
628 def vote(bot
, user
, chan
, realtarget
, *args
):
629 if state
.pointvote
is not None:
630 if int(args
[0]) in state
.voteamounts
:
631 state
.voteamounts
[int(args
[0])] += 1
632 bot
.msg(user
, "Your vote has been recorded.")
634 bot
.msg(user
, "Sorry - that's not an option!")
636 bot
.msg(user
, "There's no vote in progress.")
638 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
639 @lib.help("<number>", "sets the max missed question before game stops")
640 def maxmissed(bot
, user
, chan
, realtarget
, *args
):
642 state
.db
['maxmissedquestions'] = int(args
[0])
643 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
645 bot
.msg(user
, "Failed to set maxmissed.")
647 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
648 @lib.help("<seconds>", "sets the time between hints")
649 def hinttimer(bot
, user
, chan
, realtarget
, *args
):
651 state
.db
['hinttimer'] = float(args
[0])
652 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
654 bot
.msg(user
, "Failed to set hint timer.")
656 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
657 @lib.help("<number>", "sets the number of hints given")
658 def hintnum(bot
, user
, chan
, realtarget
, *args
):
660 state
.db
['hintnum'] = int(args
[0])
661 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
663 bot
.msg(user
, "Failed to set hintnum.")
665 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
666 @lib.help("<seconds>", "sets the pause between questions")
667 def questionpause(bot
, user
, chan
, realtarget
, *args
):
669 state
.db
['questionpause'] = float(args
[0])
670 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
672 bot
.msg(user
, "Failed to set questionpause.")
674 @lib.hook(glevel
=1, needchan
=False)
675 @lib.help("<full question>", "finds a qid given a complete question")
676 def findq(bot
, user
, chan
, realtarget
, *args
):
678 if args
[0].startswith("@"):
679 cat
= args
.pop(0)[1:].lower()
680 questions
= state
.db
['questions'][cat
]
682 questions
= state
.questions
685 bot
.msg(user
, "You need to specify the question.")
688 searchkey
= ' '.join(args
).lower()
689 matches
= [str(i
) for i
in range(len(questions
)) if questions
[i
][0].lower() == searchkey
]
691 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
692 elif len(matches
) == 1:
693 bot
.msg(user
, "One match: %s" % (matches
[0]))
695 bot
.msg(user
, "No match.")
697 @lib.hook(glevel
=1, needchan
=False)
698 @lib.help("[@<category>] <regex>", "finds a qid given a regex or partial question")
699 def findqre(bot
, user
, chan
, realtarget
, *args
):
701 if args
[0].startswith("@"):
702 cat
= args
.pop(0)[1:].lower()
703 questions
= state
.db
['questions'][cat
]
705 questions
= state
.questions
708 bot
.msg(user
, "You need to specify a search string.")
711 searcher
= re
.compile(' '.join(args
), re
.IGNORECASE
)
712 matches
= [str(i
) for i
in range(len(questions
)) if searcher
.search(questions
[i
][0]) is not None]
713 if len(matches
) > 25:
714 bot
.msg(user
, "Too many matches! (>25)")
715 elif len(matches
) > 1:
716 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
717 elif len(matches
) == 1:
718 bot
.msg(user
, "One match: %s" % (matches
[0]))
720 bot
.msg(user
, "No match.")
722 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
723 @lib.help("[@<category>] <qid>", "displays the q*a for a qid", "category defaults to current")
724 def showq(bot
, user
, chan
, realtarget
, *args
):
726 if args
[0].startswith("@"):
727 cat
= args
.pop(0)[1:].lower()
728 questions
= state
.db
['questions'][cat
]
730 questions
= state
.questions
735 bot
.msg(user
, "Specify a numeric question ID.")
740 bot
.msg(user
, "ID not valid.")
742 bot
.msg(user
, "%s: %s*%s" % (qid
, q
[0], q
[1]))
744 @lib.hook(('delq', 'deleteq'), glevel
=lib
.STAFF
, needchan
=False)
745 @lib.help("[@<category>] <qid>", "removes a question from the database")
746 def delq(bot
, user
, chan
, realtarget
, *args
):
748 if args
[0].startswith("@"):
749 cat
= args
.pop(0)[1:].lower()
750 questions
= state
.db
['questions'][cat
]
752 questions
= state
.questions
755 backup
= questions
[int(args
[0])]
756 del questions
[int(args
[0])]
757 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]))
759 bot
.msg(user
, "Couldn't delete that question. %r" % (e
))
761 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
762 @lib.help("[@<category>] <q>*<a>", "adds a question")
763 def addq(bot
, user
, chan
, realtarget
, *args
):
765 if args
[0].startswith("@"):
766 cat
= args
.pop(0)[1:].lower()
767 questions
= state
.db
['questions'][cat
]
769 questions
= state
.questions
771 line
= ' '.join([str(arg
) for arg
in args
])
772 linepieces
= line
.split('*', 1)
773 if len(linepieces
) < 2:
774 bot
.msg(user
, "Error: need <question>*<answer>")
776 question
= linepieces
[0].strip()
777 answer
= linepieces
[1].strip()
778 questions
.append([question
, answer
])
779 bot
.msg(user
, "Done. Question is #%s" % (len(questions
)-1))
781 @lib.hook(needchan
=False)
782 @lib.help(None, "show current category")
783 def showcat(bot
, user
, chan
, realtarget
, *args
):
784 bot
.msg(user
, "Current category: %s" % (state
.db
['category']))
786 @lib.hook(glevel
=1, needchan
=False)
787 @lib.help("<category>", "change category")
788 def setcat(bot
, user
, chan
, realtarget
, *args
):
789 category
= args
[0].lower()
790 if category
in state
.db
['questions']:
791 state
.db
['category'] = category
792 state
.questions
= state
.db
['questions'][category
]
793 bot
.msg(user
, "Changed category to %s" % (category
))
795 bot
.msg(user
, "That category doesn't exist.")
797 @lib.hook(needchan
=False)
798 @lib.help(None, "list categories", "the current category will be marked with a *")
799 def listcats(bot
, user
, chan
, realtarget
, *args
):
800 cats
= ["%s%s (%d)" % ("*" if c
== state
.db
['category'] else "", c
, len(state
.db
['questions'][c
])) for c
in state
.db
['questions'].keys()]
801 bot
.msg(user
, "Categories: %s" % (', '.join(cats
)))
803 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
804 @lib.help("<category>", "adds an empty category")
805 def addcat(bot
, user
, chan
, realtarget
, *args
):
806 category
= args
[0].lower()
807 if category
not in state
.db
['questions']:
808 state
.db
['questions'][category
] = []
809 bot
.msg(user
, "Added category %s" % (category
))
811 bot
.msg(user
, "Category already exists.")
813 @lib.hook(glevel
=lib
.MANAGER
, needchan
=False)
814 @lib.help("<category>", "deletes an entire category")
815 def delcat(bot
, user
, chan
, realtarget
, *args
):
816 category
= args
[0].lower()
817 if category
== state
.db
['category']:
818 bot
.msg(user
, "Category currently in use!")
819 elif category
in state
.db
['questions']:
820 length
= len(state
.db
['questions'][category
])
821 del state
.db
['questions'][category
]
822 bot
.msg(user
, "Deleted category %s (%d questions)" % (category
, length
))
824 bot
.msg(user
, "Category does not exist.")
826 @lib.hook(needchan
=False)
827 def triviahelp(bot
, user
, chan
, realtarget
, *args
):
828 bot
.slowmsg(user
, "START")
829 bot
.slowmsg(user
, "TOP10")
830 bot
.slowmsg(user
, "POINTS [<user>]")
831 bot
.slowmsg(user
, "RANK [<user>]")
832 bot
.slowmsg(user
, "BADQ <reason> (include info to identify question)")
834 bot
.slowmsg(user
, "SKIP (KNOWN)")
835 bot
.slowmsg(user
, "STOP (KNOWN)")
836 bot
.slowmsg(user
, "FINDQ <full question> (KNOWN)")
837 bot
.slowmsg(user
, "FINDQRE <regex> (KNOWN)")
838 bot
.slowmsg(user
, "SETNEXTID <qid> (KNOWN)")
839 if user
.glevel
>= lib
.STAFF
:
840 bot
.slowmsg(user
, "GIVE <user> [<points>] (STAFF)")
841 bot
.slowmsg(user
, "SETNEXT <q>*<a> (STAFF)")
842 bot
.slowmsg(user
, "ADDQ <q>*<a> (STAFF)")
843 bot
.slowmsg(user
, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
844 bot
.slowmsg(user
, "SHOWQ <qid> (STAFF)")
845 bot
.slowmsg(user
, "BADQS (STAFF)")
846 bot
.slowmsg(user
, "CLEARBADQS (STAFF)")
847 bot
.slowmsg(user
, "DELBADQ <reportid> (STAFF)")
848 if user
.glevel
>= lib
.ADMIN
:
849 bot
.slowmsg(user
, "SETTARGET <points> (ADMIN)")
850 bot
.slowmsg(user
, "MAXMISSED <questions> (ADMIN)")
851 bot
.slowmsg(user
, "HINTTIMER <float seconds> (ADMIN)")
852 bot
.slowmsg(user
, "HINTNUM <hints> (ADMIN)")
853 bot
.slowmsg(user
, "QUESTIONPAUSE <float seconds> (ADMIN)")
855 @lib.hooknum(332) # topic is...
856 @lib.hooknum(331) # no topic set
857 def num_TOPIC(bot
, textline
):
858 pieces
= textline
.split(None, 4)
860 if chan
!= state
.db
['chan']:
862 gottopic
= pieces
[4][1:]
864 formatted
= state
.db
['topicformat'] % {
865 'chan': state
.db
['chan'],
866 'top1': "%s (%s)" % (person(0), pts(0)),
868 "%s (%s)" % (person(x
), pts(x
))
869 for x
in range(3) if x
< len(state
.db
['ranks'])
872 "%s (%s) %s" % (person(x
), country(x
), pts(x
))
873 for x
in range(3) if x
< len(state
.db
['ranks'])
876 "%s (%s)" % (person(x
), pts(x
))
877 for x
in range(10) if x
< len(state
.db
['ranks'])
880 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
881 for x
in range(10) if x
< len(state
.db
['ranks'])
883 'lastwinner': state
.db
['lastwinner'],
884 'lastwon': time
.strftime("%b %d", time
.gmtime(state
.db
['lastwon'])),
885 'target': state
.db
['target'],
886 'category': state
.db
['category'],
888 if gottopic
!= formatted
:
889 state
.getbot().conn
.send(bot
.parent
.cfg
.get('trivia', 'topiccommand', default
="TOPIC %(chan)s :%(topic)s") % {'chan': state.db['chan'], 'topic': formatted}
)
892 def specialQuestion(oldq
):
893 newq
= [oldq
[0], oldq
[1]]
894 qtype
= oldq
[0].upper()
896 if qtype
== "!MONTH":
897 newq
[0] = "What month is it currently (in UTC)?"
898 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
899 elif qtype
== "!MATH+":
901 maxnum
= int(oldq
[1])
904 randnum1
= random
.randrange(0, maxnum
+1)
905 randnum2
= random
.randrange(0, maxnum
+1)
906 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
907 newq
[1] = spellout(randnum1
+randnum2
)
908 elif qtype
== "!ALGEBRA+":
910 num1
, num2
= [int(i
) for i
in oldq
[1].split('!')]
913 randnum1
= random
.randrange(0, num1
+1)
914 randnum2
= random
.randrange(randnum1
, num2
+1)
915 newq
[0] = "What is x? %d = %d + x" % (randnum2
, randnum1
)
916 newq
[1] = spellout(randnum2
-randnum1
)
917 else: pass #default to not modifying
921 ones
= ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
922 teens
= ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
923 tens
= ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
928 ihundreds
= num
/ 100
929 itens
= num
% 100 / 10
934 buf
.append("%s hundred" % (ones
[ihundreds
]))
936 buf
.append(tens
[itens
])
938 buf
.append(teens
[iones
])
940 buf
.append(ones
[iones
])
943 # "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
944 # "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
945 # "sixteen", "seventeen", "eighteen", "nineteen", "twenty"