1 # Erebus IRC bot - Author: Erebus Team
3 # This file is released into the public domain; see http://unlicense.org/
5 from __future__
import print_function
9 'author': 'Erebus Team',
10 'license': 'public domain',
12 'depends': ['userinfo'],
18 lib
= modlib
.modlib(__name__
)
19 def modstart(parent
, *args
, **kwargs
):
20 state
.gotParent(parent
)
21 lib
.hookchan(state
.db
['chan'])(trivia_checkanswer
) # we need parent for this. so it goes here.
22 return lib
.modstart(parent
, *args
, **kwargs
)
23 def modstop(*args
, **kwargs
):
29 except Exception: pass
30 return lib
.modstop(*args
, **kwargs
)
33 import json
, random
, threading
, re
, time
, datetime
, os
, sys
35 if sys
.version_info
.major
< 3:
36 timerbase
= threading
._Timer
38 timerbase
= threading
.Timer
43 except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
45 def findnth(haystack
, needle
, n
): #http://stackoverflow.com/a/1884151
46 parts
= haystack
.split(needle
, n
+1)
49 return len(haystack
)-len(parts
[-1])-len(needle
)
51 def person(num
, throwindexerror
=False):
53 return state
.db
['users'][state
.db
['ranks'][num
]]['realnick']
62 return str(state
.db
['users'][state
.db
['ranks'][num
]]['points'])
66 def country(num
, default
="??"):
67 return lib
.mod('userinfo')._get
(person(num
), 'country', default
=default
).upper()
69 class MyTimer(timerbase
):
70 def __init__(self
, *args
, **kwargs
):
71 timerbase
.__init
__(self
, *args
, **kwargs
)
74 class TriviaState(object):
75 def __init__(self
, parent
=None, pointvote
=False):
76 if parent
is not None:
77 self
.gotParent(parent
, pointvote
)
79 def gotParent(self
, parent
, pointvote
=False):
81 self
.questionfile
= self
.parent
.cfg
.get('trivia', 'jsonpath', default
="./modules/trivia.json")
82 self
.db
= json
.load(open(self
.questionfile
, "r"))
83 self
.questions
= self
.db
['questions'][self
.db
['category']]
84 self
.chan
= self
.db
['chan']
88 self
.nextquestiontimer
= None
91 self
.hintanswer
= None
93 self
.revealpossibilities
= None
95 self
.missedquestions
= 0
99 if 'lastwon' not in self
.db
or self
.db
['lastwon'] is None:
100 self
.db
['lastwon'] = time
.time()
103 self
.getchan().msg("Vote for the next round target points! Options: %s. Vote using !vote <choice>" % (', '.join([str(x
) for x
in self
.db
['targetoptions']])))
104 self
.getchan().msg("You have %s seconds." % (self
.db
['votetimer']))
105 self
.voteamounts
= dict([(x
, 0) for x
in self
.db
['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
106 self
.pointvote
= MyTimer(self
.db
['votetimer'], self
.endPointVote
)
107 self
.pointvote
.start()
109 self
.pointvote
= None
115 self
.steptimer
.cancel()
116 self
.steptimer
= None
119 self
.nextquestiontimer
.cancel()
120 self
.nextquestiontimer
= None
123 def savedb(self
): #returns whether or not it was able to save
124 if json
is not None and json
.dump
is not None:
125 # json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
126 dbjson
= json
.dumps(self
.db
)
128 os
.rename(self
.questionfile
, self
.questionfile
+".auto.bak")
129 tmpfn
= os
.tempnam('.', 'trivia')
134 os
.rename(tmpfn
, self
.questionfile
)
136 except: #if something happens, restore the backup
137 os
.rename(self
.questionfile
+".auto.bak", self
.questionfile
)
140 except OSError: # temp file is already gone
142 raise # we may be better off just swallowing exceptions?
146 return self
.parent
.channel(self
.chan
)
148 return self
.getchan().bot
150 def nexthint(self
, hintnum
):
151 answer
= self
.hintanswer
153 if self
.hintstr
is None or self
.revealpossibilities
is None or self
.reveal
is None:
155 self
.hintstr
= list(re
.sub(r
'[a-zA-Z0-9]', '*', answer
))
156 self
.revealpossibilities
= range(''.join(self
.hintstr
).count('*'))
157 self
.reveal
= int(round(''.join(self
.hintstr
).count('*') * (7/24.0)))
159 oldhintstr
= ''.join(self
.hintstr
)
161 for i
in range(self
.reveal
):
162 revealcount
= random
.choice(self
.revealpossibilities
)
163 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
164 self
.revealpossibilities
.remove(revealcount
)
165 self
.hintstr
[revealloc
] = answer
[revealloc
]
166 if oldhintstr
!= ''.join(self
.hintstr
): self
.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
170 if hintnum
< self
.db
['hintnum']:
171 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
172 self
.steptimer
.start()
174 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
175 self
.steptimer
.start()
177 def doGameOver(self
):
178 msg
= self
.getchan().msg
181 msg("\00312THE GAME IS OVER!!!")
182 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
183 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
184 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
185 [msg("%dth place: %s (%s)" % (i
+1, person(i
, True), pts(i
))) for i
in range(3,10)]
186 except IndexError: pass
187 except Exception as e
:
188 msg("DERP! %r" % (e
))
190 self
.db
['lastwinner'] = winner
191 self
.db
['lastwon'] = time
.time()
193 if self
.db
['hofpath'] is not None and self
.db
['hofpath'] != '':
196 self
.db
['users'] = {}
197 self
.db
['ranks'] = []
202 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
203 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
204 self
.getbot().parent
.cfg
.get('trivia', 'con'),
205 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
206 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
207 except: pass #don't care if errors happen updating twitter.
209 self
.__init
__(self
.parent
, True)
213 try: return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
214 except: return "none"
216 try: return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
221 f
= open(self
.db
['hofpath'], 'rb+')
222 for i
in range(self
.db
['hoflines']): #skip this many lines
227 f
.write((self
.db
['hofformat']+"\n") % {
228 'date': time
.strftime("%F", time
.gmtime()),
229 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['lastwon'])),
230 'targetscore': self
.db
['target'],
231 'firstperson': person(0),
232 'firstscore': pts(0),
233 'secondperson': person(1),
234 'secondscore': pts(1),
235 'thirdperson': person(2),
236 'thirdscore': pts(2),
240 except Exception as e
:
246 def endPointVote(self
):
247 self
.getchan().msg("Voting has ended!")
248 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
249 for i
in range(len(votelist
)-1):
251 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
252 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
254 self
.db
['target'] = votelist
[-1][0]
255 self
.pointvote
= None
257 self
.nextquestion() #start the game!
259 def nextquestion(self
, qskipped
=False, iteration
=0, skipwait
=False):
260 self
.lastqid
= self
.curqid
263 if self
.gameover
== True:
264 return self
.doGameOver()
266 self
.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
267 self
.missedquestions
+= 1
269 self
.missedquestions
= 0
270 if 'topicformat' in self
.db
and self
.db
['topicformat'] is not None:
271 self
.getbot().conn
.send("TOPIC %s" % (self
.db
['chan']))
273 if isinstance(self
.steptimer
, MyTimer
):
274 self
.steptimer
.cancel()
275 if isinstance(self
.nextquestiontimer
, MyTimer
):
276 self
.nextquestiontimer
.cancel()
277 self
.nextquestiontimer
= None
281 self
.revealpossibilities
= None
286 if self
.missedquestions
> self
.db
['maxmissedquestions']:
288 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game." % (self
.missedquestions
))
292 self
._nextquestion
(iteration
)
294 self
.nextquestiontimer
= MyTimer(self
.db
['questionpause'], self
._nextquestion
, args
=[iteration
])
295 self
.nextquestiontimer
.start()
297 def _nextquestion(self
, iteration
):
298 if self
.nextq
is not None:
302 elif self
.nextqid
is not None:
303 nextqid
= self
.nextqid
304 nextq
= self
.questions
[nextqid
]
307 nextqid
= random
.randrange(0, len(self
.questions
))
308 nextq
= self
.questions
[nextqid
]
310 if nextq
[0].startswith("!"):
312 nextq
= specialQuestion(nextq
)
314 if len(nextq
) > 2 and time
.time() - nextq
[2] < 7*24*60*60 and iteration
< 10:
315 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
317 nextq
[2] = time
.time()
319 nextq
.append(time
.time())
321 if isinstance(nextq
[1], basestring
):
322 nextq
[1] = nextq
[1].lower()
324 nextq
[1] = [s
.lower() for s
in nextq
[1]]
326 qtext
= "\00312,01Next up: "
327 qtext
+= "(%5d)" % (random
.randint(0,99999))
328 qary
= nextq
[0].split(None)
331 spacer
= random
.choice(
332 range(0x61,0x7A) + ([0x20]*4)
334 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(spacer
) #a-z
335 if not self
.getbot().fastmsg(self
.chan
, qtext
): #if message is too long:
336 if nextqid
is None: nextqid
= "manual"
337 self
.getbot().slowmsg(self
.chan
, "(Unable to ask question #%s: line too long)" % (nextqid
))
338 return self
._nextquestion
(iteration
) #retry; don't increment the iteration
341 self
.curqid
= nextqid
343 if isinstance(self
.curq
[1], basestring
): self
.hintanswer
= self
.curq
[1]
344 else: self
.hintanswer
= random
.choice(self
.curq
[1])
346 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
347 self
.steptimer
.start()
349 def checkanswer(self
, answer
):
350 if self
.curq
is None:
352 elif isinstance(self
.curq
[1], basestring
):
353 return answer
.lower() == self
.curq
[1]
354 else: # assume it's a list or something.
355 return answer
.lower() in self
.curq
[1]
357 def addpoint(self
, user_obj
, count
=1):
358 user_nick
= str(user_obj
)
359 user
= user_nick
.lower() # save this separately as we use both
360 if user
in self
.db
['users']:
361 self
.db
['users'][user
]['points'] += count
363 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
364 self
.db
['ranks'].append(user
)
366 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
367 for i
in range(0, len(self
.db
['ranks'])):
368 nick
= self
.db
['ranks'][i
]
369 self
.db
['users'][nick
]['rank'] = i
371 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
374 return self
.db
['users'][user
]['points']
376 def points(self
, user
):
377 user
= str(user
).lower()
378 if user
in self
.db
['users']:
379 return self
.db
['users'][user
]['points']
383 def rank(self
, user
):
384 user
= str(user
).lower()
385 if user
in self
.db
['users']:
386 return self
.db
['users'][user
]['rank']+1
388 return len(self
.db
['users'])+1
390 def targetuser(self
, user
):
391 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
393 user
= str(user
).lower()
394 if user
in self
.db
['users']:
395 rank
= self
.db
['users'][user
]['rank']
397 return "you're in the lead!"
399 return self
.db
['ranks'][rank
-1]
401 return self
.db
['ranks'][-1]
402 def targetpoints(self
, user
):
403 if len(self
.db
['ranks']) == 0: return 0
405 user
= str(user
).lower()
406 if user
in self
.db
['users']:
407 rank
= self
.db
['users'][user
]['rank']
411 return "("+str(self
.db
['users'][self
.db
['ranks'][rank
-1]]['points'])+")"
413 return "("+str(self
.db
['users'][self
.db
['ranks'][-1]]['points'])+")"
415 state
= TriviaState()
417 # we have to hook this in modstart, since we don't know the channel until then.
418 def trivia_checkanswer(bot
, user
, chan
, *args
):
419 line
= ' '.join([str(arg
) for arg
in args
])
420 if state
.checkanswer(line
):
422 if state
.hintanswer
.lower() == line
.lower():
423 bot
.fastmsg(chan
, "\00312%s\003 has it! The answer was \00312%s\003. New score: %d. Rank: %d. Target: %s %s" % (user
, line
, state
.addpoint(user
), state
.rank(user
), state
.targetuser(user
), state
.targetpoints(user
)))
425 bot
.fastmsg(chan
, "\00312%s\003 has it! The answer was \00312%s\003 (hinted answer: %s). New score: %d. Rank: %d. Target: %s%s" % (user
, line
, state
.hintanswer
, state
.addpoint(user
), state
.rank(user
), state
.targetuser(user
), state
.targetpoints(user
)))
426 if state
.hintsgiven
== 0:
427 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
430 @lib.hook(glevel
=1, needchan
=False, wantchan
=True)
431 @lib.help(None, "saves the trivia database")
432 def save(bot
, user
, chan
, realtarget
, *args
):
433 if chan
is not None: replyto
= chan
437 bot
.msg(replyto
, "Save successful.")
439 bot
.msg(replyto
, "Save failed!")
441 @lib.hook(needchan
=False, wantchan
=True)
442 @lib.help("[<user>]", "shows how many points you or someone has")
443 def points(bot
, user
, chan
, realtarget
, *args
):
444 if chan
is not None: eplyto
= chan
447 if len(args
) != 0: who
= args
[0]
450 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
452 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
453 @lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
455 def give(bot
, user
, chan
, realtarget
, *args
):
458 numpoints
= int(args
[1])
461 balance
= state
.addpoint(whoto
, numpoints
)
463 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
465 @lib.hook(glevel
=1, needchan
=False)
466 @lib.help("<qid>", "sets next question to one in the database")
468 def setnextid(bot
, user
, chan
, realtarget
, *args
):
472 bot
.msg(user
, "Error: QID must be a number.")
474 if qid
>= len(state
.questions
):
475 bot
.msg(user
, "Error: no such QID.")
478 bot
.msg(user
, "Done. Next question is %d: %s" % (qid
, state
.questions
[qid
][0]))
480 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
481 @lib.help("<q>*<a>", "sets next question to one not in database")
483 def setnext(bot
, user
, chan
, realtarget
, *args
):
484 line
= ' '.join([str(arg
) for arg
in args
])
485 linepieces
= line
.split('*', 1)
486 if len(linepieces
) < 2:
487 bot
.msg(user
, "Error: need <question>*<answer>")
489 question
= linepieces
[0].strip()
490 answer
= linepieces
[1].strip()
491 state
.nextq
= [question
, answer
]
492 bot
.msg(user
, "Done.")
494 @lib.hook(glevel
=1, needchan
=False)
495 @lib.help(None, "skips to next question")
496 def skip(bot
, user
, chan
, realtarget
, *args
):
497 state
.nextquestion(qskipped
=True, skipwait
=True)
499 @lib.hook(needchan
=False, wantchan
=True)
500 @lib.help(None, "starts the trivia game")
501 def start(bot
, user
, chan
, realtarget
, *args
):
502 if chan
is not None: replyto
= chan
505 if chan
is not None and chan
.name
!= state
.db
['chan']:
506 bot
.msg(replyto
, "That command isn't valid here.")
509 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
510 bot
.msg(state
.db
['chan'], "%s has started the game!" % (user
))
511 state
.nextquestion(skipwait
=True)
512 elif state
.pointvote
is not None:
513 bot
.msg(user
, "There's a vote in progress!")
515 bot
.msg(user
, "Game is already started!")
517 @lib.hook('stop', glevel
=1, needchan
=False)
518 @lib.help(None, "stops the trivia game")
519 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
521 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
523 bot
.msg(user
, "Game isn't running.")
529 state
.steptimer
.cancel()
530 except Exception as e
:
531 print("!!! steptimer.cancel(): %s %r" % (e
,e
))
532 state
.steptimer
= None
534 state
.nextquestiontimer
.cancel()
535 except Exception as e
:
536 print("!!! nextquestiontimer.cancel(): %s %r" % (e
,e
))
537 state
.nextquestiontimer
= None
540 @lib.hook(needchan
=False)
541 @lib.help("<reason>", "reports a bad question to the admins")
543 def badq(bot
, user
, chan
, realtarget
, *args
):
544 lastqid
= state
.lastqid
545 curqid
= state
.curqid
547 reason
= ' '.join(args
)
548 state
.db
['badqs'].append([state
.db
['category'], lastqid
, curqid
, reason
])
549 bot
.msg(user
, "Reported bad question.")
551 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
552 @lib.help(None, "shows a list of BADQ reports")
553 def badqs(bot
, user
, chan
, realtarget
, *args
):
554 if len(state
.db
['badqs']) == 0:
555 bot
.msg(user
, "No reports.")
557 for i
in range(len(state
.db
['badqs'])):
559 report
= state
.db
['badqs'][i
]
560 bot
.msg(user
, "Report #%d: Cat=%s LastQ=%r CurQ=%r: %s" % (i
, report
[0], report
[1], report
[2], report
[3]))
561 try: lq
= state
.db
['questions'][report
[0]][int(report
[1])]
562 except Exception as e
: lq
= (None,None)
563 try: cq
= state
.db
['questions'][report
[0]][int(report
[2])]
564 except Exception as e
: cq
= (None, None)
565 bot
.msg(user
, "- Last: %s*%s" % (lq
[0], lq
[1]))
566 bot
.msg(user
, "- Curr: %s*%s" % (cq
[0], cq
[1]))
567 except Exception as e
:
568 bot
.msg(user
, "- Exception: %r" % (e
))
570 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
571 @lib.hook(None, "clears list of BADQ reports")
572 def clearbadqs(bot
, user
, chan
, realtarget
, *args
):
573 state
.db
['badqs'] = []
574 bot
.msg(user
, "Cleared reports.")
576 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
577 @lib.hook("<badqid>", "removes a BADQ report")
579 def delbadq(bot
, user
, chan
, realtarget
, *args
):
582 del state
.db
['badqs'][qid
]
583 bot
.msg(user
, "Removed report #%d" % (qid
))
585 bot
.msg(user
, "Failed!")
587 @lib.hook(needchan
=False, wantchan
=True)
588 @lib.help("[<user>]", "shows you or someone else's rank")
589 def rank(bot
, user
, chan
, realtarget
, *args
):
590 if chan
is not None: replyto
= chan
593 if len(args
) != 0: who
= args
[0]
596 bot
.msg(replyto
, "%s is in %d place (%s points). Target is: %s %s" % (who
, state
.rank(who
), state
.points(who
), state
.targetuser(who
), state
.targetpoints(who
)))
598 @lib.hook(needchan
=False)
599 @lib.help(None, "shows top10 list")
600 def top10(bot
, user
, chan
, realtarget
, *args
):
601 if len(state
.db
['ranks']) == 0:
602 return bot
.msg(state
.db
['chan'], "No one is ranked!")
604 max = len(state
.db
['ranks'])
607 replylist
= ', '.join(["%s (%s) %s" % (person(x
), country(x
), pts(x
)) for x
in range(max)])
608 bot
.msg(state
.db
['chan'], "Top 10: %s" % (replylist
))
610 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
611 @lib.help("<target score>", "changes the target score for this round")
612 def settarget(bot
, user
, chan
, realtarget
, *args
):
614 state
.db
['target'] = int(args
[0])
615 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
617 if state
.pointvote
is not None:
618 state
.pointvote
.cancel()
619 state
.pointvote
= None
620 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
621 except Exception as e
:
623 bot
.msg(user
, "Failed to set target.")
625 @lib.hook(needchan
=False)
626 @lib.help("<option>", "votes for a trarget score for next round")
627 def vote(bot
, user
, chan
, realtarget
, *args
):
628 if state
.pointvote
is not None:
629 if int(args
[0]) in state
.voteamounts
:
630 state
.voteamounts
[int(args
[0])] += 1
631 bot
.msg(user
, "Your vote has been recorded.")
633 bot
.msg(user
, "Sorry - that's not an option!")
635 bot
.msg(user
, "There's no vote in progress.")
637 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
638 @lib.help("<number>", "sets the max missed question before game stops")
639 def maxmissed(bot
, user
, chan
, realtarget
, *args
):
641 state
.db
['maxmissedquestions'] = int(args
[0])
642 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
644 bot
.msg(user
, "Failed to set maxmissed.")
646 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
647 @lib.help("<seconds>", "sets the time between hints")
648 def hinttimer(bot
, user
, chan
, realtarget
, *args
):
650 state
.db
['hinttimer'] = float(args
[0])
651 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
653 bot
.msg(user
, "Failed to set hint timer.")
655 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
656 @lib.help("<number>", "sets the number of hints given")
657 def hintnum(bot
, user
, chan
, realtarget
, *args
):
659 state
.db
['hintnum'] = int(args
[0])
660 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
662 bot
.msg(user
, "Failed to set hintnum.")
664 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
665 @lib.help("<seconds>", "sets the pause between questions")
666 def questionpause(bot
, user
, chan
, realtarget
, *args
):
668 state
.db
['questionpause'] = float(args
[0])
669 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
671 bot
.msg(user
, "Failed to set questionpause.")
673 @lib.hook(glevel
=1, needchan
=False)
674 @lib.help("<full question>", "finds a qid given a complete question")
675 def findq(bot
, user
, chan
, realtarget
, *args
):
677 if args
[0].startswith("@"):
678 cat
= args
.pop(0)[1:].lower()
679 questions
= state
.db
['questions'][cat
]
681 questions
= state
.questions
684 bot
.msg(user
, "You need to specify the question.")
687 searchkey
= ' '.join(args
).lower()
688 matches
= [str(i
) for i
in range(len(questions
)) if questions
[i
][0].lower() == searchkey
]
690 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
691 elif len(matches
) == 1:
692 bot
.msg(user
, "One match: %s" % (matches
[0]))
694 bot
.msg(user
, "No match.")
696 @lib.hook(glevel
=1, needchan
=False)
697 @lib.help("[@<category>] <regex>", "finds a qid given a regex or partial question")
698 def findqre(bot
, user
, chan
, realtarget
, *args
):
700 if args
[0].startswith("@"):
701 cat
= args
.pop(0)[1:].lower()
702 questions
= state
.db
['questions'][cat
]
704 questions
= state
.questions
707 bot
.msg(user
, "You need to specify a search string.")
710 searcher
= re
.compile(' '.join(args
), re
.IGNORECASE
)
711 matches
= [str(i
) for i
in range(len(questions
)) if searcher
.search(questions
[i
][0]) is not None]
712 if len(matches
) > 25:
713 bot
.msg(user
, "Too many matches! (>25)")
714 elif len(matches
) > 1:
715 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
716 elif len(matches
) == 1:
717 bot
.msg(user
, "One match: %s" % (matches
[0]))
719 bot
.msg(user
, "No match.")
721 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
722 @lib.help("[@<category>] <qid>", "displays the q*a for a qid", "category defaults to current")
723 def showq(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
734 bot
.msg(user
, "Specify a numeric question ID.")
739 bot
.msg(user
, "ID not valid.")
741 bot
.msg(user
, "%s: %s*%s" % (qid
, q
[0], q
[1]))
743 @lib.hook(('delq', 'deleteq'), glevel
=lib
.STAFF
, needchan
=False)
744 @lib.help("[@<category>] <qid>", "removes a question from the database")
745 def delq(bot
, user
, chan
, realtarget
, *args
):
747 if args
[0].startswith("@"):
748 cat
= args
.pop(0)[1:].lower()
749 questions
= state
.db
['questions'][cat
]
751 questions
= state
.questions
754 backup
= questions
[int(args
[0])]
755 del questions
[int(args
[0])]
756 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]))
758 bot
.msg(user
, "Couldn't delete that question. %r" % (e
))
760 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
761 @lib.help("[@<category>] <q>*<a>", "adds a question")
762 def addq(bot
, user
, chan
, realtarget
, *args
):
764 if args
[0].startswith("@"):
765 cat
= args
.pop(0)[1:].lower()
766 questions
= state
.db
['questions'][cat
]
768 questions
= state
.questions
770 line
= ' '.join([str(arg
) for arg
in args
])
771 linepieces
= line
.split('*', 1)
772 if len(linepieces
) < 2:
773 bot
.msg(user
, "Error: need <question>*<answer>")
775 question
= linepieces
[0].strip()
776 answer
= linepieces
[1].strip()
777 questions
.append([question
, answer
])
778 bot
.msg(user
, "Done. Question is #%s" % (len(questions
)-1))
780 @lib.hook(needchan
=False)
781 @lib.help(None, "show current category")
782 def showcat(bot
, user
, chan
, realtarget
, *args
):
783 bot
.msg(user
, "Current category: %s" % (state
.db
['category']))
785 @lib.hook(glevel
=1, needchan
=False)
786 @lib.help("<category>", "change category")
787 def setcat(bot
, user
, chan
, realtarget
, *args
):
788 category
= args
[0].lower()
789 if category
in state
.db
['questions']:
790 state
.db
['category'] = category
791 state
.questions
= state
.db
['questions'][category
]
792 bot
.msg(user
, "Changed category to %s" % (category
))
794 bot
.msg(user
, "That category doesn't exist.")
796 @lib.hook(needchan
=False)
797 @lib.help(None, "list categories", "the current category will be marked with a *")
798 def listcats(bot
, user
, chan
, realtarget
, *args
):
799 cats
= ["%s%s (%d)" % ("*" if c
== state
.db
['category'] else "", c
, len(state
.db
['questions'][c
])) for c
in state
.db
['questions'].keys()]
800 bot
.msg(user
, "Categories: %s" % (', '.join(cats
)))
802 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
803 @lib.help("<category>", "adds an empty category")
804 def addcat(bot
, user
, chan
, realtarget
, *args
):
805 category
= args
[0].lower()
806 if category
not in state
.db
['questions']:
807 state
.db
['questions'][category
] = []
808 bot
.msg(user
, "Added category %s" % (category
))
810 bot
.msg(user
, "Category already exists.")
812 @lib.hook(glevel
=lib
.MANAGER
, needchan
=False)
813 @lib.help("<category>", "deletes an entire category")
814 def delcat(bot
, user
, chan
, realtarget
, *args
):
815 category
= args
[0].lower()
816 if category
== state
.db
['category']:
817 bot
.msg(user
, "Category currently in use!")
818 elif category
in state
.db
['questions']:
819 length
= len(state
.db
['questions'][category
])
820 del state
.db
['questions'][category
]
821 bot
.msg(user
, "Deleted category %s (%d questions)" % (category
, length
))
823 bot
.msg(user
, "Category does not exist.")
825 @lib.hook(needchan
=False)
826 def triviahelp(bot
, user
, chan
, realtarget
, *args
):
827 bot
.slowmsg(user
, "START")
828 bot
.slowmsg(user
, "TOP10")
829 bot
.slowmsg(user
, "POINTS [<user>]")
830 bot
.slowmsg(user
, "RANK [<user>]")
831 bot
.slowmsg(user
, "BADQ <reason> (include info to identify question)")
833 bot
.slowmsg(user
, "SKIP (KNOWN)")
834 bot
.slowmsg(user
, "STOP (KNOWN)")
835 bot
.slowmsg(user
, "FINDQ <full question> (KNOWN)")
836 bot
.slowmsg(user
, "FINDQRE <regex> (KNOWN)")
837 bot
.slowmsg(user
, "SETNEXTID <qid> (KNOWN)")
838 if user
.glevel
>= lib
.STAFF
:
839 bot
.slowmsg(user
, "GIVE <user> [<points>] (STAFF)")
840 bot
.slowmsg(user
, "SETNEXT <q>*<a> (STAFF)")
841 bot
.slowmsg(user
, "ADDQ <q>*<a> (STAFF)")
842 bot
.slowmsg(user
, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
843 bot
.slowmsg(user
, "SHOWQ <qid> (STAFF)")
844 bot
.slowmsg(user
, "BADQS (STAFF)")
845 bot
.slowmsg(user
, "CLEARBADQS (STAFF)")
846 bot
.slowmsg(user
, "DELBADQ <reportid> (STAFF)")
847 if user
.glevel
>= lib
.ADMIN
:
848 bot
.slowmsg(user
, "SETTARGET <points> (ADMIN)")
849 bot
.slowmsg(user
, "MAXMISSED <questions> (ADMIN)")
850 bot
.slowmsg(user
, "HINTTIMER <float seconds> (ADMIN)")
851 bot
.slowmsg(user
, "HINTNUM <hints> (ADMIN)")
852 bot
.slowmsg(user
, "QUESTIONPAUSE <float seconds> (ADMIN)")
854 @lib.hooknum(332) # topic is...
855 @lib.hooknum(331) # no topic set
856 def num_TOPIC(bot
, textline
):
857 pieces
= textline
.split(None, 4)
859 if chan
!= state
.db
['chan']:
861 gottopic
= pieces
[4][1:]
863 formatted
= state
.db
['topicformat'] % {
864 'chan': state
.db
['chan'],
865 'top1': "%s (%s)" % (person(0), pts(0)),
867 "%s (%s)" % (person(x
), pts(x
))
868 for x
in range(3) if x
< len(state
.db
['ranks'])
871 "%s (%s) %s" % (person(x
), country(x
), pts(x
))
872 for x
in range(3) if x
< len(state
.db
['ranks'])
875 "%s (%s)" % (person(x
), pts(x
))
876 for x
in range(10) if x
< len(state
.db
['ranks'])
879 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
880 for x
in range(10) if x
< len(state
.db
['ranks'])
882 'lastwinner': state
.db
['lastwinner'],
883 'lastwon': time
.strftime("%b %d", time
.gmtime(state
.db
['lastwon'])),
884 'target': state
.db
['target'],
885 'category': state
.db
['category'],
887 if gottopic
!= formatted
:
888 state
.getbot().conn
.send(bot
.parent
.cfg
.get('trivia', 'topiccommand', default
="TOPIC %(chan)s :%(topic)s") % {'chan': state.db['chan'], 'topic': formatted}
)
891 def specialQuestion(oldq
):
892 newq
= [oldq
[0], oldq
[1]]
893 qtype
= oldq
[0].upper()
895 if qtype
== "!MONTH":
896 newq
[0] = "What month is it currently (in UTC)?"
897 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
898 elif qtype
== "!MATH+":
900 maxnum
= int(oldq
[1])
903 randnum1
= random
.randrange(0, maxnum
+1)
904 randnum2
= random
.randrange(0, maxnum
+1)
905 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
906 newq
[1] = spellout(randnum1
+randnum2
)
907 elif qtype
== "!ALGEBRA+":
909 num1
, num2
= [int(i
) for i
in oldq
[1].split('!')]
912 randnum1
= random
.randrange(0, num1
+1)
913 randnum2
= random
.randrange(randnum1
, num2
+1)
914 newq
[0] = "What is x? %d = %d + x" % (randnum2
, randnum1
)
915 newq
[1] = spellout(randnum2
-randnum1
)
916 else: pass #default to not modifying
920 ones
= ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
921 teens
= ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
922 tens
= ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
927 ihundreds
= num
/ 100
928 itens
= num
% 100 / 10
933 buf
.append("%s hundred" % (ones
[ihundreds
]))
935 buf
.append(tens
[itens
])
937 buf
.append(teens
[iones
])
939 buf
.append(ones
[iones
])
942 # "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
943 # "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
944 # "sixteen", "seventeen", "eighteen", "nineteen", "twenty"