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
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
="??"):
69 return lib
.mod('userinfo').get(person(num
), 'country', default
=default
).upper()
71 return default
.upper()
73 class MyTimer(timerbase
):
74 def __init__(self
, *args
, **kwargs
):
75 timerbase
.__init
__(self
, *args
, **kwargs
)
78 class TriviaState(object):
79 def __init__(self
, parent
=None, pointvote
=False):
80 if parent
is not None:
81 self
.gotParent(parent
, pointvote
)
83 def gotParent(self
, parent
, pointvote
=False):
85 self
.questionfile
= self
.parent
.cfg
.get('trivia', 'jsonpath', default
="./modules/trivia.json")
86 self
.db
= json
.load(open(self
.questionfile
, "r"))
87 self
.questions
= self
.db
['questions'][self
.db
['category']]
88 self
.chan
= self
.db
['chan']
92 self
.nextquestiontimer
= None
95 self
.hintanswer
= None
97 self
.revealpossibilities
= None
99 self
.missedquestions
= 0
103 if 'lastwon' not in self
.db
or self
.db
['lastwon'] is None:
104 self
.db
['lastwon'] = time
.time()
107 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']])))
108 self
.getchan().fastmsg("You have %s seconds." % (self
.db
['votetimer']))
109 self
.voteamounts
= dict([(x
, 0) for x
in self
.db
['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
110 self
.pointvote
= MyTimer(self
.db
['votetimer'], self
.endPointVote
)
111 self
.pointvote
.start()
113 self
.pointvote
= None
119 self
.steptimer
.cancel()
120 self
.steptimer
= None
123 self
.nextquestiontimer
.cancel()
124 self
.nextquestiontimer
= None
127 def savedb(self
): #returns whether or not it was able to save
128 if json
is not None and json
.dump
is not None:
129 # json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
130 dbjson
= json
.dumps(self
.db
)
132 os
.rename(self
.questionfile
, self
.questionfile
+".auto.bak")
133 tmpfn
= os
.tempnam('.', 'trivia')
138 os
.rename(tmpfn
, self
.questionfile
)
140 except: #if something happens, restore the backup
141 os
.rename(self
.questionfile
+".auto.bak", self
.questionfile
)
144 except OSError: # temp file is already gone
146 raise # we may be better off just swallowing exceptions?
150 return self
.parent
.channel(self
.chan
)
152 return self
.getchan().bot
154 def nexthint(self
, hintnum
):
155 answer
= self
.hintanswer
157 if self
.hintstr
is None or self
.revealpossibilities
is None or self
.reveal
is None:
159 self
.hintstr
= list(re
.sub(r
'[a-zA-Z0-9]', '*', answer
))
160 self
.revealpossibilities
= range(''.join(self
.hintstr
).count('*'))
161 self
.reveal
= int(round(''.join(self
.hintstr
).count('*') * (7/24.0)))
163 oldhintstr
= ''.join(self
.hintstr
)
166 for i
in range(self
.reveal
):
167 revealcount
= random
.choice(self
.revealpossibilities
)
168 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
169 self
.revealpossibilities
.remove(revealcount
)
170 self
.hintstr
[revealloc
] = answer
[revealloc
]
171 except IndexError: pass # if everything is revealed, random.choice will IndexError
172 if oldhintstr
!= ''.join(self
.hintstr
): self
.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
176 if hintnum
< self
.db
['hintnum']:
177 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
178 self
.steptimer
.start()
180 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
181 self
.steptimer
.start()
183 def doGameOver(self
):
184 msg
= self
.getchan().msg
187 msg("\00312THE GAME IS OVER!!!")
188 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
189 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
190 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
191 [msg("%dth place: %s (%s)" % (i
+1, person(i
, True), pts(i
))) for i
in range(3,10)]
192 except IndexError: pass
193 except Exception as e
:
194 msg("DERP! %r" % (e
))
196 self
.db
['lastwinner'] = winner
197 self
.db
['lastwon'] = time
.time()
199 if self
.db
['hofpath'] is not None and self
.db
['hofpath'] != '':
202 self
.db
['users'] = {}
203 self
.db
['ranks'] = []
209 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
210 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
211 self
.getbot().parent
.cfg
.get('trivia', 'con'),
212 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
213 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
214 except: pass #don't care if errors happen updating twitter.
216 self
.__init
__(self
.parent
, True)
220 try: return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
221 except: return "none"
223 try: return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
229 f
= open(self
.db
['hofpath'], 'rb+')
230 for i
in range(self
.db
['hoflines']): #skip this many lines
235 f
.write((self
.db
['hofformat']+"\n") % {
236 'date': time
.strftime("%F", time
.gmtime()),
237 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['lastwon'])),
238 'targetscore': self
.db
['target'],
239 'firstperson': person(0),
240 'firstscore': pts(0),
241 'secondperson': person(1),
242 'secondscore': pts(1),
243 'thirdperson': person(2),
244 'thirdscore': pts(2),
248 except Exception as e
:
255 def endPointVote(self
):
256 self
.getchan().msg("Voting has ended!")
257 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
258 for i
in range(len(votelist
)-1):
260 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
261 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
263 self
.db
['target'] = votelist
[-1][0]
264 self
.pointvote
= None
266 self
.nextquestion() #start the game!
268 def nextquestion(self
, qskipped
=False, iteration
=0, skipwait
=False):
269 self
.lastqid
= self
.curqid
272 if self
.gameover
== True:
273 return self
.doGameOver()
275 self
.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
276 self
.missedquestions
+= 1
278 self
.missedquestions
= 0
279 if 'topicformat' in self
.db
and self
.db
['topicformat'] is not None:
280 self
.getbot().conn
.send("TOPIC %s" % (self
.db
['chan']))
282 if isinstance(self
.steptimer
, MyTimer
):
283 self
.steptimer
.cancel()
284 if isinstance(self
.nextquestiontimer
, MyTimer
):
285 self
.nextquestiontimer
.cancel()
286 self
.nextquestiontimer
= None
290 self
.revealpossibilities
= None
295 if self
.missedquestions
> self
.db
['maxmissedquestions']:
297 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game." % (self
.missedquestions
))
301 self
._nextquestion
(iteration
)
303 self
.nextquestiontimer
= MyTimer(self
.db
['questionpause'], self
._nextquestion
, args
=[iteration
])
304 self
.nextquestiontimer
.start()
306 def _nextquestion(self
, iteration
):
307 if self
.nextq
is not None:
311 elif self
.nextqid
is not None:
312 nextqid
= self
.nextqid
313 nextq
= self
.questions
[nextqid
]
316 nextqid
= random
.randrange(0, len(self
.questions
))
317 nextq
= self
.questions
[nextqid
]
319 if nextq
[0].startswith("!"):
321 nextq
= specialQuestion(nextq
)
323 if len(nextq
) > 2 and time
.time() - nextq
[2] < 7*24*60*60 and iteration
< 10:
324 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
326 nextq
[2] = time
.time()
328 nextq
.append(time
.time())
330 if isinstance(nextq
[1], basestring
):
331 nextq
[1] = nextq
[1].lower()
333 nextq
[1] = [s
.lower() for s
in nextq
[1]]
335 qtext
= "\00312,01Next up: "
336 qtext
+= "(%5d)" % (random
.randint(0,99999))
337 qary
= nextq
[0].split(None)
340 spacer
= random
.choice(
341 range(0x61,0x7A) + ([0x20]*4)
343 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(spacer
) #a-z
344 if not self
.getbot().fastmsg(self
.chan
, qtext
): #if message is too long:
345 if not self
.getbot().fastmsg(self
.chan
, "\00312,01Next up: " + ("(%5d)" % (random
.randint(0,99999))) + "\00304,01" + nextq
[0]):
346 if nextqid
is None: nextqid
= "manual"
347 self
.getbot().slowmsg(self
.chan
, "(Unable to ask question #%s: line too long)" % (nextqid
))
348 return self
._nextquestion
(iteration
) #retry; don't increment the iteration
351 self
.curqid
= nextqid
353 if isinstance(self
.curq
[1], basestring
): self
.hintanswer
= self
.curq
[1]
354 else: self
.hintanswer
= random
.choice(self
.curq
[1])
356 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
357 self
.steptimer
.start()
359 def checkanswer(self
, answer
):
360 if self
.curq
is None:
362 elif isinstance(self
.curq
[1], basestring
):
363 return answer
.lower() == self
.curq
[1]
364 else: # assume it's a list or something.
365 return answer
.lower() in self
.curq
[1]
367 def addpoint(self
, user_obj
, count
=1):
368 user_nick
= str(user_obj
)
369 user
= user_nick
.lower() # save this separately as we use both
370 if user
in self
.db
['users']:
371 self
.db
['users'][user
]['points'] += count
373 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
374 self
.db
['ranks'].append(user
)
376 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
377 for i
in range(0, len(self
.db
['ranks'])):
378 nick
= self
.db
['ranks'][i
]
379 self
.db
['users'][nick
]['rank'] = i
381 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
384 return self
.db
['users'][user
]['points']
386 def points(self
, user
):
387 user
= str(user
).lower()
388 if user
in self
.db
['users']:
389 return self
.db
['users'][user
]['points']
393 def rank(self
, user
):
394 user
= str(user
).lower()
395 if user
in self
.db
['users']:
396 return self
.db
['users'][user
]['rank']+1
398 return len(self
.db
['users'])+1
400 def targetuser(self
, user
):
401 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
403 user
= str(user
).lower()
404 if user
in self
.db
['users']:
405 rank
= self
.db
['users'][user
]['rank']
407 return "you're in the lead!"
409 return self
.db
['ranks'][rank
-1]
411 return self
.db
['ranks'][-1]
412 def targetpoints(self
, user
):
413 if len(self
.db
['ranks']) == 0: return 0
415 user
= str(user
).lower()
416 if user
in self
.db
['users']:
417 rank
= self
.db
['users'][user
]['rank']
421 return "("+str(self
.db
['users'][self
.db
['ranks'][rank
-1]]['points'])+")"
423 return "("+str(self
.db
['users'][self
.db
['ranks'][-1]]['points'])+")"
425 state
= TriviaState()
427 # we have to hook this in modstart, since we don't know the channel until then.
428 def trivia_checkanswer(bot
, user
, chan
, *args
):
429 line
= ' '.join([str(arg
) for arg
in args
])
430 if state
.checkanswer(line
):
432 if state
.hintanswer
.lower() == line
.lower():
433 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
)))
435 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
)))
436 if state
.hintsgiven
== 0:
437 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
440 @lib.hook(glevel
=1, needchan
=False, wantchan
=True)
441 @lib.help(None, "saves the trivia database")
442 def save(bot
, user
, chan
, realtarget
, *args
):
443 if chan
is not None: replyto
= chan
447 bot
.msg(replyto
, "Save successful.")
449 bot
.msg(replyto
, "Save failed!")
451 @lib.hook(needchan
=False, wantchan
=True)
452 @lib.help("[<user>]", "shows how many points you or someone has")
453 def points(bot
, user
, chan
, realtarget
, *args
):
454 if chan
is not None: eplyto
= chan
457 if len(args
) != 0: who
= args
[0]
460 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
462 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
463 @lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
465 def give(bot
, user
, chan
, realtarget
, *args
):
468 numpoints
= int(args
[1])
471 balance
= state
.addpoint(whoto
, numpoints
)
473 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
475 @lib.hook(glevel
=1, needchan
=False)
476 @lib.help("<qid>", "sets next question to one in the database")
478 def setnextid(bot
, user
, chan
, realtarget
, *args
):
482 bot
.msg(user
, "Error: QID must be a number.")
484 if qid
>= len(state
.questions
):
485 bot
.msg(user
, "Error: no such QID.")
488 bot
.msg(user
, "Done. Next question is %d: %s" % (qid
, state
.questions
[qid
][0]), truncate
=True)
490 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
491 @lib.help("<q>*<a>", "sets next question to one not in database")
493 def setnext(bot
, user
, chan
, realtarget
, *args
):
494 line
= ' '.join([str(arg
) for arg
in args
])
495 linepieces
= line
.split('*', 1)
496 if len(linepieces
) < 2:
497 bot
.msg(user
, "Error: need <question>*<answer>")
499 question
= linepieces
[0].strip()
500 answer
= linepieces
[1].strip()
501 state
.nextq
= [question
, answer
]
502 bot
.msg(user
, "Done.")
504 @lib.hook(glevel
=1, needchan
=False)
505 @lib.help(None, "skips to next question")
506 def skip(bot
, user
, chan
, realtarget
, *args
):
507 state
.nextquestion(qskipped
=True, skipwait
=True)
509 @lib.hook(('start','trivia'), needchan
=False, wantchan
=True)
510 @lib.help(None, "starts the trivia game")
511 def start(bot
, user
, chan
, realtarget
, *args
):
512 if chan
is not None: replyto
= chan
515 if chan
is not None and chan
.name
!= state
.db
['chan']:
516 bot
.msg(replyto
, "That command isn't valid here.")
519 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
520 bot
.msg(state
.db
['chan'], "%s has started the game!" % (user
))
521 state
.nextquestion(skipwait
=True)
522 elif state
.pointvote
is not None:
523 bot
.msg(user
, "There's a vote in progress!")
525 bot
.msg(user
, "Game is already started!")
527 @lib.hook('stop', glevel
=1, needchan
=False)
528 @lib.help(None, "stops the trivia game")
529 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
531 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
533 bot
.msg(user
, "Game isn't running.")
539 state
.steptimer
.cancel()
540 except Exception as e
:
541 print("!!! steptimer.cancel(): %s %r" % (e
,e
))
542 state
.steptimer
= None
544 state
.nextquestiontimer
.cancel()
545 except Exception as e
:
546 print("!!! nextquestiontimer.cancel(): %s %r" % (e
,e
))
547 state
.nextquestiontimer
= None
550 @lib.hook(needchan
=False)
551 @lib.help("<reason>", "reports a bad question to the admins")
553 def badq(bot
, user
, chan
, realtarget
, *args
):
554 lastqid
= state
.lastqid
555 curqid
= state
.curqid
557 reason
= ' '.join(args
)
558 state
.db
['badqs'].append([state
.db
['category'], lastqid
, curqid
, reason
])
559 bot
.msg(user
, "Reported bad question.")
561 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
562 @lib.help(None, "shows a list of BADQ reports")
563 def badqs(bot
, user
, chan
, realtarget
, *args
):
564 if len(state
.db
['badqs']) == 0:
565 bot
.msg(user
, "No reports.")
567 for i
in range(len(state
.db
['badqs'])):
569 report
= state
.db
['badqs'][i
]
570 bot
.msg(user
, "Report #%d: Cat=%s LastQ=%r CurQ=%r: %s" % (i
, report
[0], report
[1], report
[2], report
[3]))
571 try: lq
= state
.db
['questions'][report
[0]][int(report
[1])]
572 except Exception as e
: lq
= (None,None)
573 try: cq
= state
.db
['questions'][report
[0]][int(report
[2])]
574 except Exception as e
: cq
= (None, None)
575 bot
.msg(user
, "- Last: %s*%s" % (lq
[0], lq
[1]))
576 bot
.msg(user
, "- Curr: %s*%s" % (cq
[0], cq
[1]))
577 except Exception as e
:
578 bot
.msg(user
, "- Exception: %r" % (e
))
580 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
581 @lib.hook(None, "clears list of BADQ reports")
582 def clearbadqs(bot
, user
, chan
, realtarget
, *args
):
583 state
.db
['badqs'] = []
584 bot
.msg(user
, "Cleared reports.")
586 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
587 @lib.hook("<badqid>", "removes a BADQ report")
589 def delbadq(bot
, user
, chan
, realtarget
, *args
):
592 del state
.db
['badqs'][qid
]
593 bot
.msg(user
, "Removed report #%d" % (qid
))
595 bot
.msg(user
, "Failed!")
597 @lib.hook(needchan
=False, wantchan
=True)
598 @lib.help("[<user>]", "shows you or someone else's rank")
599 def rank(bot
, user
, chan
, realtarget
, *args
):
600 if chan
is not None: replyto
= chan
603 if len(args
) != 0: who
= args
[0]
606 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
)))
608 @lib.hook(needchan
=False)
609 @lib.help(None, "shows top10 list")
610 def top10(bot
, user
, chan
, realtarget
, *args
):
611 if len(state
.db
['ranks']) == 0:
612 return bot
.msg(state
.db
['chan'], "No one is ranked!")
614 max = len(state
.db
['ranks'])
617 replylist
= ', '.join(["%s (%s) %s" % (person(x
), country(x
), pts(x
)) for x
in range(max)])
618 bot
.msg(state
.db
['chan'], "Game is to %s! Top 10: %s" % (state
.db
['target'], replylist
))
620 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
621 @lib.help("<target score>", "changes the target score for this round")
622 def settarget(bot
, user
, chan
, realtarget
, *args
):
624 state
.db
['target'] = int(args
[0])
625 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
627 if state
.pointvote
is not None:
628 state
.pointvote
.cancel()
629 state
.pointvote
= None
630 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
631 except Exception as e
:
633 bot
.msg(user
, "Failed to set target.")
635 @lib.hook(needchan
=False)
636 @lib.help("<option>", "votes for a trarget score for next round")
637 def vote(bot
, user
, chan
, realtarget
, *args
):
638 if state
.pointvote
is not None:
639 if int(args
[0]) in state
.voteamounts
:
640 state
.voteamounts
[int(args
[0])] += 1
641 bot
.msg(user
, "Your vote has been recorded.")
643 bot
.msg(user
, "Sorry - that's not an option!")
645 bot
.msg(user
, "There's no vote in progress.")
647 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
648 @lib.help("<number>", "sets the max missed question before game stops")
649 def maxmissed(bot
, user
, chan
, realtarget
, *args
):
651 state
.db
['maxmissedquestions'] = int(args
[0])
652 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
654 bot
.msg(user
, "Failed to set maxmissed.")
656 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
657 @lib.help("<seconds>", "sets the time between hints")
658 def hinttimer(bot
, user
, chan
, realtarget
, *args
):
660 state
.db
['hinttimer'] = float(args
[0])
661 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
663 bot
.msg(user
, "Failed to set hint timer.")
665 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
666 @lib.help("<number>", "sets the number of hints given")
667 def hintnum(bot
, user
, chan
, realtarget
, *args
):
669 state
.db
['hintnum'] = int(args
[0])
670 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
672 bot
.msg(user
, "Failed to set hintnum.")
674 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
675 @lib.help("<seconds>", "sets the pause between questions")
676 def questionpause(bot
, user
, chan
, realtarget
, *args
):
678 state
.db
['questionpause'] = float(args
[0])
679 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
681 bot
.msg(user
, "Failed to set questionpause.")
683 @lib.hook(glevel
=1, needchan
=False)
684 @lib.help("[@category] <full question>", "finds a qid given a complete question")
686 def findq(bot
, user
, chan
, realtarget
, *args
):
688 if args
[0].startswith("@"):
689 cat
= args
.pop(0)[1:].lower()
690 questions
= state
.db
['questions'][cat
]
692 questions
= state
.questions
695 bot
.msg(user
, "You need to specify the question.")
698 searchkey
= ' '.join(args
).lower()
699 matches
= [str(i
) for i
in range(len(questions
)) if questions
[i
][0].lower() == searchkey
]
701 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
702 elif len(matches
) == 1:
703 bot
.msg(user
, "One match: %s" % (matches
[0]))
705 bot
.msg(user
, "No match.")
707 @lib.hook(glevel
=1, needchan
=False)
708 @lib.help("[@<category>] <regex>", "finds a qid given a regex or partial question")
710 def findqre(bot
, user
, chan
, realtarget
, *args
):
712 if args
[0].startswith("@"):
713 cat
= args
.pop(0)[1:].lower()
714 questions
= state
.db
['questions'][cat
]
716 questions
= state
.questions
719 bot
.msg(user
, "You need to specify a search string.")
722 searcher
= re
.compile(' '.join(args
), re
.IGNORECASE
)
723 matches
= [str(i
) for i
in range(len(questions
)) if searcher
.search(questions
[i
][0]) is not None]
724 if len(matches
) > 25:
725 bot
.msg(user
, "Too many matches! (>25)")
726 elif len(matches
) > 1:
727 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
728 elif len(matches
) == 1:
729 bot
.msg(user
, "One match: %s" % (matches
[0]))
731 bot
.msg(user
, "No match.")
733 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
734 @lib.help("[@<category>] <qid>", "displays the q*a for a qid", "category defaults to current")
735 def showq(bot
, user
, chan
, realtarget
, *args
):
737 if args
[0].startswith("@"):
738 cat
= args
.pop(0)[1:].lower()
739 questions
= state
.db
['questions'][cat
]
741 questions
= state
.questions
746 bot
.msg(user
, "Specify a numeric question ID.")
751 bot
.msg(user
, "ID not valid.")
753 bot
.msg(user
, "%s: %s*%s" % (qid
, q
[0], q
[1]), True)
755 @lib.hook(('delq', 'deleteq'), glevel
=lib
.STAFF
, needchan
=False)
756 @lib.help("[@<category>] <qid>", "removes a question from the database")
757 def delq(bot
, user
, chan
, realtarget
, *args
):
759 if args
[0].startswith("@"):
760 cat
= args
.pop(0)[1:].lower()
761 questions
= state
.db
['questions'][cat
]
763 questions
= state
.questions
766 backup
= questions
[int(args
[0])]
767 del questions
[int(args
[0])]
768 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]))
770 bot
.msg(user
, "Couldn't delete that question. %r" % (e
))
772 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
773 @lib.help("[@<category>] <q>*<a>", "adds a question")
774 def addq(bot
, user
, chan
, realtarget
, *args
):
776 if args
[0].startswith("@"):
777 cat
= args
.pop(0)[1:].lower()
778 questions
= state
.db
['questions'][cat
]
780 questions
= state
.questions
782 line
= ' '.join([str(arg
) for arg
in args
])
783 linepieces
= line
.split('*', 1)
784 if len(linepieces
) < 2:
785 bot
.msg(user
, "Error: need <question>*<answer>")
787 question
= linepieces
[0].strip()
788 answer
= linepieces
[1].strip()
789 questions
.append([question
, answer
])
790 bot
.msg(user
, "Done. Question is #%s" % (len(questions
)-1))
792 @lib.hook(needchan
=False)
793 @lib.help(None, "show current category")
794 def showcat(bot
, user
, chan
, realtarget
, *args
):
795 bot
.msg(user
, "Current category: %s" % (state
.db
['category']))
797 @lib.hook(glevel
=1, needchan
=False)
798 @lib.help("<category>", "change category")
799 def setcat(bot
, user
, chan
, realtarget
, *args
):
800 category
= args
[0].lower()
801 if category
in state
.db
['questions']:
802 state
.db
['category'] = category
803 state
.questions
= state
.db
['questions'][category
]
804 bot
.msg(user
, "Changed category to %s" % (category
))
806 bot
.msg(user
, "That category doesn't exist.")
808 @lib.hook(needchan
=False)
809 @lib.help(None, "list categories", "the current category will be marked with a *")
810 def listcats(bot
, user
, chan
, realtarget
, *args
):
811 cats
= ["%s%s (%d)" % ("*" if c
== state
.db
['category'] else "", c
, len(state
.db
['questions'][c
])) for c
in state
.db
['questions'].keys()]
812 bot
.msg(user
, "Categories: %s" % (', '.join(cats
)))
814 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
815 @lib.help("<category>", "adds an empty category")
816 def addcat(bot
, user
, chan
, realtarget
, *args
):
817 category
= args
[0].lower()
818 if category
not in state
.db
['questions']:
819 state
.db
['questions'][category
] = []
820 bot
.msg(user
, "Added category %s" % (category
))
822 bot
.msg(user
, "Category already exists.")
824 @lib.hook(glevel
=lib
.MANAGER
, needchan
=False)
825 @lib.help("<category>", "deletes an entire category")
826 def delcat(bot
, user
, chan
, realtarget
, *args
):
827 category
= args
[0].lower()
828 if category
== state
.db
['category']:
829 bot
.msg(user
, "Category currently in use!")
830 elif category
in state
.db
['questions']:
831 length
= len(state
.db
['questions'][category
])
832 del state
.db
['questions'][category
]
833 bot
.msg(user
, "Deleted category %s (%d questions)" % (category
, length
))
835 bot
.msg(user
, "Category does not exist.")
837 @lib.hook(needchan
=False)
838 def triviahelp(bot
, user
, chan
, realtarget
, *args
):
839 bot
.slowmsg(user
, "START")
840 bot
.slowmsg(user
, "TOP10")
841 bot
.slowmsg(user
, "POINTS [<user>]")
842 bot
.slowmsg(user
, "RANK [<user>]")
843 bot
.slowmsg(user
, "BADQ <reason> (include info to identify question)")
845 bot
.slowmsg(user
, "SKIP (KNOWN)")
846 bot
.slowmsg(user
, "STOP (KNOWN)")
847 bot
.slowmsg(user
, "FINDQ <full question> (KNOWN)")
848 bot
.slowmsg(user
, "FINDQRE <regex> (KNOWN)")
849 bot
.slowmsg(user
, "SETNEXTID <qid> (KNOWN)")
850 if user
.glevel
>= lib
.STAFF
:
851 bot
.slowmsg(user
, "GIVE <user> [<points>] (STAFF)")
852 bot
.slowmsg(user
, "SETNEXT <q>*<a> (STAFF)")
853 bot
.slowmsg(user
, "ADDQ <q>*<a> (STAFF)")
854 bot
.slowmsg(user
, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
855 bot
.slowmsg(user
, "SHOWQ <qid> (STAFF)")
856 bot
.slowmsg(user
, "BADQS (STAFF)")
857 bot
.slowmsg(user
, "CLEARBADQS (STAFF)")
858 bot
.slowmsg(user
, "DELBADQ <reportid> (STAFF)")
859 if user
.glevel
>= lib
.ADMIN
:
860 bot
.slowmsg(user
, "SETTARGET <points> (ADMIN)")
861 bot
.slowmsg(user
, "MAXMISSED <questions> (ADMIN)")
862 bot
.slowmsg(user
, "HINTTIMER <float seconds> (ADMIN)")
863 bot
.slowmsg(user
, "HINTNUM <hints> (ADMIN)")
864 bot
.slowmsg(user
, "QUESTIONPAUSE <float seconds> (ADMIN)")
866 @lib.hooknum(332) # topic is...
867 @lib.hooknum(331) # no topic set
868 def num_TOPIC(bot
, textline
):
869 pieces
= textline
.split(None, 4)
871 if chan
!= state
.db
['chan']:
873 gottopic
= pieces
[4][1:]
875 formatted
= state
.db
['topicformat'] % {
876 'chan': state
.db
['chan'],
877 'top1': "%s (%s)" % (person(0), pts(0)),
879 "%s (%s)" % (person(x
), pts(x
))
880 for x
in range(3) if x
< len(state
.db
['ranks'])
883 "%s (%s) %s" % (person(x
), country(x
), pts(x
))
884 for x
in range(3) if x
< len(state
.db
['ranks'])
887 "%s (%s)" % (person(x
), pts(x
))
888 for x
in range(10) if x
< len(state
.db
['ranks'])
891 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
892 for x
in range(10) if x
< len(state
.db
['ranks'])
894 'lastwinner': state
.db
['lastwinner'],
895 'lastwon': time
.strftime("%b %d", time
.gmtime(state
.db
['lastwon'])),
896 'target': state
.db
['target'],
897 'category': state
.db
['category'],
899 if gottopic
!= formatted
:
900 state
.getbot().conn
.send(bot
.parent
.cfg
.get('trivia', 'topiccommand', default
="TOPIC %(chan)s :%(topic)s") % {'chan': state.db['chan'], 'topic': formatted}
)
903 def specialQuestion(oldq
):
904 newq
= [oldq
[0], oldq
[1]]
905 qtype
= oldq
[0].upper()
907 if qtype
== "!MONTH":
908 newq
[0] = "What month is it currently (in UTC)?"
909 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
910 elif qtype
== "!MATH+":
912 maxnum
= int(oldq
[1])
915 randnum1
= random
.randrange(0, maxnum
+1)
916 randnum2
= random
.randrange(0, maxnum
+1)
917 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
918 newq
[1] = spellout(randnum1
+randnum2
)
919 elif qtype
== "!ALGEBRA+":
921 num1
, num2
= [int(i
) for i
in oldq
[1].split('!')]
924 randnum1
= random
.randrange(0, num1
+1)
925 randnum2
= random
.randrange(randnum1
, num2
+1)
926 newq
[0] = "What is x? %d = %d + x" % (randnum2
, randnum1
)
927 newq
[1] = spellout(randnum2
-randnum1
)
928 else: pass #default to not modifying
932 ones
= ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
933 teens
= ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
934 tens
= ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
939 ihundreds
= num
/ 100
940 itens
= num
% 100 / 10
945 buf
.append("%s hundred" % (ones
[ihundreds
]))
947 buf
.append(tens
[itens
])
949 buf
.append(teens
[iones
])
951 buf
.append(ones
[iones
])
954 # "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
955 # "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
956 # "sixteen", "seventeen", "eighteen", "nineteen", "twenty"