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().fastmsg("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().fastmsg("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
)
163 for i
in range(self
.reveal
):
164 revealcount
= random
.choice(self
.revealpossibilities
)
165 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
166 self
.revealpossibilities
.remove(revealcount
)
167 self
.hintstr
[revealloc
] = answer
[revealloc
]
168 except IndexError: pass # if everything is revealed, random.choice will IndexError
169 if oldhintstr
!= ''.join(self
.hintstr
): self
.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
173 if hintnum
< self
.db
['hintnum']:
174 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
175 self
.steptimer
.start()
177 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
178 self
.steptimer
.start()
180 def doGameOver(self
):
181 msg
= self
.getchan().msg
184 msg("\00312THE GAME IS OVER!!!")
185 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
186 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
187 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
188 [msg("%dth place: %s (%s)" % (i
+1, person(i
, True), pts(i
))) for i
in range(3,10)]
189 except IndexError: pass
190 except Exception as e
:
191 msg("DERP! %r" % (e
))
193 self
.db
['lastwinner'] = winner
194 self
.db
['lastwon'] = time
.time()
196 if self
.db
['hofpath'] is not None and self
.db
['hofpath'] != '':
199 self
.db
['users'] = {}
200 self
.db
['ranks'] = []
206 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
207 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
208 self
.getbot().parent
.cfg
.get('trivia', 'con'),
209 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
210 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
211 except: pass #don't care if errors happen updating twitter.
213 self
.__init
__(self
.parent
, True)
217 try: return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
218 except: return "none"
220 try: return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
226 f
= open(self
.db
['hofpath'], 'rb+')
227 for i
in range(self
.db
['hoflines']): #skip this many lines
232 f
.write((self
.db
['hofformat']+"\n") % {
233 'date': time
.strftime("%F", time
.gmtime()),
234 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['lastwon'])),
235 'targetscore': self
.db
['target'],
236 'firstperson': person(0),
237 'firstscore': pts(0),
238 'secondperson': person(1),
239 'secondscore': pts(1),
240 'thirdperson': person(2),
241 'thirdscore': pts(2),
245 except Exception as e
:
252 def endPointVote(self
):
253 self
.getchan().msg("Voting has ended!")
254 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
255 for i
in range(len(votelist
)-1):
257 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
258 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
260 self
.db
['target'] = votelist
[-1][0]
261 self
.pointvote
= None
263 self
.nextquestion() #start the game!
265 def nextquestion(self
, qskipped
=False, iteration
=0, skipwait
=False):
266 self
.lastqid
= self
.curqid
269 if self
.gameover
== True:
270 return self
.doGameOver()
272 self
.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
273 self
.missedquestions
+= 1
275 self
.missedquestions
= 0
276 if 'topicformat' in self
.db
and self
.db
['topicformat'] is not None:
277 self
.getbot().conn
.send("TOPIC %s" % (self
.db
['chan']))
279 if isinstance(self
.steptimer
, MyTimer
):
280 self
.steptimer
.cancel()
281 if isinstance(self
.nextquestiontimer
, MyTimer
):
282 self
.nextquestiontimer
.cancel()
283 self
.nextquestiontimer
= None
287 self
.revealpossibilities
= None
292 if self
.missedquestions
> self
.db
['maxmissedquestions']:
294 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game." % (self
.missedquestions
))
298 self
._nextquestion
(iteration
)
300 self
.nextquestiontimer
= MyTimer(self
.db
['questionpause'], self
._nextquestion
, args
=[iteration
])
301 self
.nextquestiontimer
.start()
303 def _nextquestion(self
, iteration
):
304 if self
.nextq
is not None:
308 elif self
.nextqid
is not None:
309 nextqid
= self
.nextqid
310 nextq
= self
.questions
[nextqid
]
313 nextqid
= random
.randrange(0, len(self
.questions
))
314 nextq
= self
.questions
[nextqid
]
316 if nextq
[0].startswith("!"):
318 nextq
= specialQuestion(nextq
)
320 if len(nextq
) > 2 and time
.time() - nextq
[2] < 7*24*60*60 and iteration
< 10:
321 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
323 nextq
[2] = time
.time()
325 nextq
.append(time
.time())
327 if isinstance(nextq
[1], basestring
):
328 nextq
[1] = nextq
[1].lower()
330 nextq
[1] = [s
.lower() for s
in nextq
[1]]
332 qtext
= "\00312,01Next up: "
333 qtext
+= "(%5d)" % (random
.randint(0,99999))
334 qary
= nextq
[0].split(None)
337 spacer
= random
.choice(
338 range(0x61,0x7A) + ([0x20]*4)
340 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(spacer
) #a-z
341 if not self
.getbot().fastmsg(self
.chan
, qtext
): #if message is too long:
342 if not self
.getbot().fastmsg(self
.chan
, "\00312,01Next up: " + ("(%5d)" % (random
.randint(0,99999))) + "\00304,01" + nextq
[0]):
343 if nextqid
is None: nextqid
= "manual"
344 self
.getbot().slowmsg(self
.chan
, "(Unable to ask question #%s: line too long)" % (nextqid
))
345 return self
._nextquestion
(iteration
) #retry; don't increment the iteration
348 self
.curqid
= nextqid
350 if isinstance(self
.curq
[1], basestring
): self
.hintanswer
= self
.curq
[1]
351 else: self
.hintanswer
= random
.choice(self
.curq
[1])
353 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
354 self
.steptimer
.start()
356 def checkanswer(self
, answer
):
357 if self
.curq
is None:
359 elif isinstance(self
.curq
[1], basestring
):
360 return answer
.lower() == self
.curq
[1]
361 else: # assume it's a list or something.
362 return answer
.lower() in self
.curq
[1]
364 def addpoint(self
, user_obj
, count
=1):
365 user_nick
= str(user_obj
)
366 user
= user_nick
.lower() # save this separately as we use both
367 if user
in self
.db
['users']:
368 self
.db
['users'][user
]['points'] += count
370 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
371 self
.db
['ranks'].append(user
)
373 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
374 for i
in range(0, len(self
.db
['ranks'])):
375 nick
= self
.db
['ranks'][i
]
376 self
.db
['users'][nick
]['rank'] = i
378 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
381 return self
.db
['users'][user
]['points']
383 def points(self
, user
):
384 user
= str(user
).lower()
385 if user
in self
.db
['users']:
386 return self
.db
['users'][user
]['points']
390 def rank(self
, user
):
391 user
= str(user
).lower()
392 if user
in self
.db
['users']:
393 return self
.db
['users'][user
]['rank']+1
395 return len(self
.db
['users'])+1
397 def targetuser(self
, user
):
398 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
400 user
= str(user
).lower()
401 if user
in self
.db
['users']:
402 rank
= self
.db
['users'][user
]['rank']
404 return "you're in the lead!"
406 return self
.db
['ranks'][rank
-1]
408 return self
.db
['ranks'][-1]
409 def targetpoints(self
, user
):
410 if len(self
.db
['ranks']) == 0: return 0
412 user
= str(user
).lower()
413 if user
in self
.db
['users']:
414 rank
= self
.db
['users'][user
]['rank']
418 return "("+str(self
.db
['users'][self
.db
['ranks'][rank
-1]]['points'])+")"
420 return "("+str(self
.db
['users'][self
.db
['ranks'][-1]]['points'])+")"
422 state
= TriviaState()
424 # we have to hook this in modstart, since we don't know the channel until then.
425 def trivia_checkanswer(bot
, user
, chan
, *args
):
426 line
= ' '.join([str(arg
) for arg
in args
])
427 if state
.checkanswer(line
):
429 if state
.hintanswer
.lower() == line
.lower():
430 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
)))
432 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
)))
433 if state
.hintsgiven
== 0:
434 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
437 @lib.hook(glevel
=1, needchan
=False, wantchan
=True)
438 @lib.help(None, "saves the trivia database")
439 def save(bot
, user
, chan
, realtarget
, *args
):
440 if chan
is not None: replyto
= chan
444 bot
.msg(replyto
, "Save successful.")
446 bot
.msg(replyto
, "Save failed!")
448 @lib.hook(needchan
=False, wantchan
=True)
449 @lib.help("[<user>]", "shows how many points you or someone has")
450 def points(bot
, user
, chan
, realtarget
, *args
):
451 if chan
is not None: eplyto
= chan
454 if len(args
) != 0: who
= args
[0]
457 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
459 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
460 @lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
462 def give(bot
, user
, chan
, realtarget
, *args
):
465 numpoints
= int(args
[1])
468 balance
= state
.addpoint(whoto
, numpoints
)
470 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
472 @lib.hook(glevel
=1, needchan
=False)
473 @lib.help("<qid>", "sets next question to one in the database")
475 def setnextid(bot
, user
, chan
, realtarget
, *args
):
479 bot
.msg(user
, "Error: QID must be a number.")
481 if qid
>= len(state
.questions
):
482 bot
.msg(user
, "Error: no such QID.")
485 bot
.msg(user
, "Done. Next question is %d: %s" % (qid
, state
.questions
[qid
][0]), truncate
=True)
487 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
488 @lib.help("<q>*<a>", "sets next question to one not in database")
490 def setnext(bot
, user
, chan
, realtarget
, *args
):
491 line
= ' '.join([str(arg
) for arg
in args
])
492 linepieces
= line
.split('*', 1)
493 if len(linepieces
) < 2:
494 bot
.msg(user
, "Error: need <question>*<answer>")
496 question
= linepieces
[0].strip()
497 answer
= linepieces
[1].strip()
498 state
.nextq
= [question
, answer
]
499 bot
.msg(user
, "Done.")
501 @lib.hook(glevel
=1, needchan
=False)
502 @lib.help(None, "skips to next question")
503 def skip(bot
, user
, chan
, realtarget
, *args
):
504 state
.nextquestion(qskipped
=True, skipwait
=True)
506 @lib.hook(('start','trivia'), needchan
=False, wantchan
=True)
507 @lib.help(None, "starts the trivia game")
508 def start(bot
, user
, chan
, realtarget
, *args
):
509 if chan
is not None: replyto
= chan
512 if chan
is not None and chan
.name
!= state
.db
['chan']:
513 bot
.msg(replyto
, "That command isn't valid here.")
516 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
517 bot
.msg(state
.db
['chan'], "%s has started the game!" % (user
))
518 state
.nextquestion(skipwait
=True)
519 elif state
.pointvote
is not None:
520 bot
.msg(user
, "There's a vote in progress!")
522 bot
.msg(user
, "Game is already started!")
524 @lib.hook('stop', glevel
=1, needchan
=False)
525 @lib.help(None, "stops the trivia game")
526 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
528 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
530 bot
.msg(user
, "Game isn't running.")
536 state
.steptimer
.cancel()
537 except Exception as e
:
538 print("!!! steptimer.cancel(): %s %r" % (e
,e
))
539 state
.steptimer
= None
541 state
.nextquestiontimer
.cancel()
542 except Exception as e
:
543 print("!!! nextquestiontimer.cancel(): %s %r" % (e
,e
))
544 state
.nextquestiontimer
= None
547 @lib.hook(needchan
=False)
548 @lib.help("<reason>", "reports a bad question to the admins")
550 def badq(bot
, user
, chan
, realtarget
, *args
):
551 lastqid
= state
.lastqid
552 curqid
= state
.curqid
554 reason
= ' '.join(args
)
555 state
.db
['badqs'].append([state
.db
['category'], lastqid
, curqid
, reason
])
556 bot
.msg(user
, "Reported bad question.")
558 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
559 @lib.help(None, "shows a list of BADQ reports")
560 def badqs(bot
, user
, chan
, realtarget
, *args
):
561 if len(state
.db
['badqs']) == 0:
562 bot
.msg(user
, "No reports.")
564 for i
in range(len(state
.db
['badqs'])):
566 report
= state
.db
['badqs'][i
]
567 bot
.msg(user
, "Report #%d: Cat=%s LastQ=%r CurQ=%r: %s" % (i
, report
[0], report
[1], report
[2], report
[3]))
568 try: lq
= state
.db
['questions'][report
[0]][int(report
[1])]
569 except Exception as e
: lq
= (None,None)
570 try: cq
= state
.db
['questions'][report
[0]][int(report
[2])]
571 except Exception as e
: cq
= (None, None)
572 bot
.msg(user
, "- Last: %s*%s" % (lq
[0], lq
[1]))
573 bot
.msg(user
, "- Curr: %s*%s" % (cq
[0], cq
[1]))
574 except Exception as e
:
575 bot
.msg(user
, "- Exception: %r" % (e
))
577 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
578 @lib.hook(None, "clears list of BADQ reports")
579 def clearbadqs(bot
, user
, chan
, realtarget
, *args
):
580 state
.db
['badqs'] = []
581 bot
.msg(user
, "Cleared reports.")
583 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
584 @lib.hook("<badqid>", "removes a BADQ report")
586 def delbadq(bot
, user
, chan
, realtarget
, *args
):
589 del state
.db
['badqs'][qid
]
590 bot
.msg(user
, "Removed report #%d" % (qid
))
592 bot
.msg(user
, "Failed!")
594 @lib.hook(needchan
=False, wantchan
=True)
595 @lib.help("[<user>]", "shows you or someone else's rank")
596 def rank(bot
, user
, chan
, realtarget
, *args
):
597 if chan
is not None: replyto
= chan
600 if len(args
) != 0: who
= args
[0]
603 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
)))
605 @lib.hook(needchan
=False)
606 @lib.help(None, "shows top10 list")
607 def top10(bot
, user
, chan
, realtarget
, *args
):
608 if len(state
.db
['ranks']) == 0:
609 return bot
.msg(state
.db
['chan'], "No one is ranked!")
611 max = len(state
.db
['ranks'])
614 replylist
= ', '.join(["%s (%s) %s" % (person(x
), country(x
), pts(x
)) for x
in range(max)])
615 bot
.msg(state
.db
['chan'], "Game is to %s! Top 10: %s" % (state
.db
['target'], replylist
))
617 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
618 @lib.help("<target score>", "changes the target score for this round")
619 def settarget(bot
, user
, chan
, realtarget
, *args
):
621 state
.db
['target'] = int(args
[0])
622 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
624 if state
.pointvote
is not None:
625 state
.pointvote
.cancel()
626 state
.pointvote
= None
627 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
628 except Exception as e
:
630 bot
.msg(user
, "Failed to set target.")
632 @lib.hook(needchan
=False)
633 @lib.help("<option>", "votes for a trarget score for next round")
634 def vote(bot
, user
, chan
, realtarget
, *args
):
635 if state
.pointvote
is not None:
636 if int(args
[0]) in state
.voteamounts
:
637 state
.voteamounts
[int(args
[0])] += 1
638 bot
.msg(user
, "Your vote has been recorded.")
640 bot
.msg(user
, "Sorry - that's not an option!")
642 bot
.msg(user
, "There's no vote in progress.")
644 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
645 @lib.help("<number>", "sets the max missed question before game stops")
646 def maxmissed(bot
, user
, chan
, realtarget
, *args
):
648 state
.db
['maxmissedquestions'] = int(args
[0])
649 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
651 bot
.msg(user
, "Failed to set maxmissed.")
653 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
654 @lib.help("<seconds>", "sets the time between hints")
655 def hinttimer(bot
, user
, chan
, realtarget
, *args
):
657 state
.db
['hinttimer'] = float(args
[0])
658 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
660 bot
.msg(user
, "Failed to set hint timer.")
662 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
663 @lib.help("<number>", "sets the number of hints given")
664 def hintnum(bot
, user
, chan
, realtarget
, *args
):
666 state
.db
['hintnum'] = int(args
[0])
667 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
669 bot
.msg(user
, "Failed to set hintnum.")
671 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
672 @lib.help("<seconds>", "sets the pause between questions")
673 def questionpause(bot
, user
, chan
, realtarget
, *args
):
675 state
.db
['questionpause'] = float(args
[0])
676 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
678 bot
.msg(user
, "Failed to set questionpause.")
680 @lib.hook(glevel
=1, needchan
=False)
681 @lib.help("[@category] <full question>", "finds a qid given a complete question")
683 def findq(bot
, user
, chan
, realtarget
, *args
):
685 if args
[0].startswith("@"):
686 cat
= args
.pop(0)[1:].lower()
687 questions
= state
.db
['questions'][cat
]
689 questions
= state
.questions
692 bot
.msg(user
, "You need to specify the question.")
695 searchkey
= ' '.join(args
).lower()
696 matches
= [str(i
) for i
in range(len(questions
)) if questions
[i
][0].lower() == searchkey
]
698 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
699 elif len(matches
) == 1:
700 bot
.msg(user
, "One match: %s" % (matches
[0]))
702 bot
.msg(user
, "No match.")
704 @lib.hook(glevel
=1, needchan
=False)
705 @lib.help("[@<category>] <regex>", "finds a qid given a regex or partial question")
707 def findqre(bot
, user
, chan
, realtarget
, *args
):
709 if args
[0].startswith("@"):
710 cat
= args
.pop(0)[1:].lower()
711 questions
= state
.db
['questions'][cat
]
713 questions
= state
.questions
716 bot
.msg(user
, "You need to specify a search string.")
719 searcher
= re
.compile(' '.join(args
), re
.IGNORECASE
)
720 matches
= [str(i
) for i
in range(len(questions
)) if searcher
.search(questions
[i
][0]) is not None]
721 if len(matches
) > 25:
722 bot
.msg(user
, "Too many matches! (>25)")
723 elif len(matches
) > 1:
724 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
725 elif len(matches
) == 1:
726 bot
.msg(user
, "One match: %s" % (matches
[0]))
728 bot
.msg(user
, "No match.")
730 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
731 @lib.help("[@<category>] <qid>", "displays the q*a for a qid", "category defaults to current")
732 def showq(bot
, user
, chan
, realtarget
, *args
):
734 if args
[0].startswith("@"):
735 cat
= args
.pop(0)[1:].lower()
736 questions
= state
.db
['questions'][cat
]
738 questions
= state
.questions
743 bot
.msg(user
, "Specify a numeric question ID.")
748 bot
.msg(user
, "ID not valid.")
750 bot
.msg(user
, "%s: %s*%s" % (qid
, q
[0], q
[1]))
752 @lib.hook(('delq', 'deleteq'), glevel
=lib
.STAFF
, needchan
=False)
753 @lib.help("[@<category>] <qid>", "removes a question from the database")
754 def delq(bot
, user
, chan
, realtarget
, *args
):
756 if args
[0].startswith("@"):
757 cat
= args
.pop(0)[1:].lower()
758 questions
= state
.db
['questions'][cat
]
760 questions
= state
.questions
763 backup
= questions
[int(args
[0])]
764 del questions
[int(args
[0])]
765 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]))
767 bot
.msg(user
, "Couldn't delete that question. %r" % (e
))
769 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
770 @lib.help("[@<category>] <q>*<a>", "adds a question")
771 def addq(bot
, user
, chan
, realtarget
, *args
):
773 if args
[0].startswith("@"):
774 cat
= args
.pop(0)[1:].lower()
775 questions
= state
.db
['questions'][cat
]
777 questions
= state
.questions
779 line
= ' '.join([str(arg
) for arg
in args
])
780 linepieces
= line
.split('*', 1)
781 if len(linepieces
) < 2:
782 bot
.msg(user
, "Error: need <question>*<answer>")
784 question
= linepieces
[0].strip()
785 answer
= linepieces
[1].strip()
786 questions
.append([question
, answer
])
787 bot
.msg(user
, "Done. Question is #%s" % (len(questions
)-1))
789 @lib.hook(needchan
=False)
790 @lib.help(None, "show current category")
791 def showcat(bot
, user
, chan
, realtarget
, *args
):
792 bot
.msg(user
, "Current category: %s" % (state
.db
['category']))
794 @lib.hook(glevel
=1, needchan
=False)
795 @lib.help("<category>", "change category")
796 def setcat(bot
, user
, chan
, realtarget
, *args
):
797 category
= args
[0].lower()
798 if category
in state
.db
['questions']:
799 state
.db
['category'] = category
800 state
.questions
= state
.db
['questions'][category
]
801 bot
.msg(user
, "Changed category to %s" % (category
))
803 bot
.msg(user
, "That category doesn't exist.")
805 @lib.hook(needchan
=False)
806 @lib.help(None, "list categories", "the current category will be marked with a *")
807 def listcats(bot
, user
, chan
, realtarget
, *args
):
808 cats
= ["%s%s (%d)" % ("*" if c
== state
.db
['category'] else "", c
, len(state
.db
['questions'][c
])) for c
in state
.db
['questions'].keys()]
809 bot
.msg(user
, "Categories: %s" % (', '.join(cats
)))
811 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
812 @lib.help("<category>", "adds an empty category")
813 def addcat(bot
, user
, chan
, realtarget
, *args
):
814 category
= args
[0].lower()
815 if category
not in state
.db
['questions']:
816 state
.db
['questions'][category
] = []
817 bot
.msg(user
, "Added category %s" % (category
))
819 bot
.msg(user
, "Category already exists.")
821 @lib.hook(glevel
=lib
.MANAGER
, needchan
=False)
822 @lib.help("<category>", "deletes an entire category")
823 def delcat(bot
, user
, chan
, realtarget
, *args
):
824 category
= args
[0].lower()
825 if category
== state
.db
['category']:
826 bot
.msg(user
, "Category currently in use!")
827 elif category
in state
.db
['questions']:
828 length
= len(state
.db
['questions'][category
])
829 del state
.db
['questions'][category
]
830 bot
.msg(user
, "Deleted category %s (%d questions)" % (category
, length
))
832 bot
.msg(user
, "Category does not exist.")
834 @lib.hook(needchan
=False)
835 def triviahelp(bot
, user
, chan
, realtarget
, *args
):
836 bot
.slowmsg(user
, "START")
837 bot
.slowmsg(user
, "TOP10")
838 bot
.slowmsg(user
, "POINTS [<user>]")
839 bot
.slowmsg(user
, "RANK [<user>]")
840 bot
.slowmsg(user
, "BADQ <reason> (include info to identify question)")
842 bot
.slowmsg(user
, "SKIP (KNOWN)")
843 bot
.slowmsg(user
, "STOP (KNOWN)")
844 bot
.slowmsg(user
, "FINDQ <full question> (KNOWN)")
845 bot
.slowmsg(user
, "FINDQRE <regex> (KNOWN)")
846 bot
.slowmsg(user
, "SETNEXTID <qid> (KNOWN)")
847 if user
.glevel
>= lib
.STAFF
:
848 bot
.slowmsg(user
, "GIVE <user> [<points>] (STAFF)")
849 bot
.slowmsg(user
, "SETNEXT <q>*<a> (STAFF)")
850 bot
.slowmsg(user
, "ADDQ <q>*<a> (STAFF)")
851 bot
.slowmsg(user
, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
852 bot
.slowmsg(user
, "SHOWQ <qid> (STAFF)")
853 bot
.slowmsg(user
, "BADQS (STAFF)")
854 bot
.slowmsg(user
, "CLEARBADQS (STAFF)")
855 bot
.slowmsg(user
, "DELBADQ <reportid> (STAFF)")
856 if user
.glevel
>= lib
.ADMIN
:
857 bot
.slowmsg(user
, "SETTARGET <points> (ADMIN)")
858 bot
.slowmsg(user
, "MAXMISSED <questions> (ADMIN)")
859 bot
.slowmsg(user
, "HINTTIMER <float seconds> (ADMIN)")
860 bot
.slowmsg(user
, "HINTNUM <hints> (ADMIN)")
861 bot
.slowmsg(user
, "QUESTIONPAUSE <float seconds> (ADMIN)")
863 @lib.hooknum(332) # topic is...
864 @lib.hooknum(331) # no topic set
865 def num_TOPIC(bot
, textline
):
866 pieces
= textline
.split(None, 4)
868 if chan
!= state
.db
['chan']:
870 gottopic
= pieces
[4][1:]
872 formatted
= state
.db
['topicformat'] % {
873 'chan': state
.db
['chan'],
874 'top1': "%s (%s)" % (person(0), pts(0)),
876 "%s (%s)" % (person(x
), pts(x
))
877 for x
in range(3) if x
< len(state
.db
['ranks'])
880 "%s (%s) %s" % (person(x
), country(x
), pts(x
))
881 for x
in range(3) if x
< len(state
.db
['ranks'])
884 "%s (%s)" % (person(x
), pts(x
))
885 for x
in range(10) if x
< len(state
.db
['ranks'])
888 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
889 for x
in range(10) if x
< len(state
.db
['ranks'])
891 'lastwinner': state
.db
['lastwinner'],
892 'lastwon': time
.strftime("%b %d", time
.gmtime(state
.db
['lastwon'])),
893 'target': state
.db
['target'],
894 'category': state
.db
['category'],
896 if gottopic
!= formatted
:
897 state
.getbot().conn
.send(bot
.parent
.cfg
.get('trivia', 'topiccommand', default
="TOPIC %(chan)s :%(topic)s") % {'chan': state.db['chan'], 'topic': formatted}
)
900 def specialQuestion(oldq
):
901 newq
= [oldq
[0], oldq
[1]]
902 qtype
= oldq
[0].upper()
904 if qtype
== "!MONTH":
905 newq
[0] = "What month is it currently (in UTC)?"
906 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
907 elif qtype
== "!MATH+":
909 maxnum
= int(oldq
[1])
912 randnum1
= random
.randrange(0, maxnum
+1)
913 randnum2
= random
.randrange(0, maxnum
+1)
914 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
915 newq
[1] = spellout(randnum1
+randnum2
)
916 elif qtype
== "!ALGEBRA+":
918 num1
, num2
= [int(i
) for i
in oldq
[1].split('!')]
921 randnum1
= random
.randrange(0, num1
+1)
922 randnum2
= random
.randrange(randnum1
, num2
+1)
923 newq
[0] = "What is x? %d = %d + x" % (randnum2
, randnum1
)
924 newq
[1] = spellout(randnum2
-randnum1
)
925 else: pass #default to not modifying
929 ones
= ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
930 teens
= ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
931 tens
= ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
936 ihundreds
= num
/ 100
937 itens
= num
% 100 / 10
942 buf
.append("%s hundred" % (ones
[ihundreds
]))
944 buf
.append(tens
[itens
])
946 buf
.append(teens
[iones
])
948 buf
.append(ones
[iones
])
951 # "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
952 # "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
953 # "sixteen", "seventeen", "eighteen", "nineteen", "twenty"