1 # Erebus IRC bot - Author: Erebus Team
3 # This file is released into the public domain; see http://unlicense.org/
7 'author': 'Erebus Team',
8 'license': 'public domain',
9 'compatible': [1], # compatible module API versions
10 'depends': ['userinfo'], # other modules required to work properly?
15 lib
= modlib
.modlib(__name__
)
16 def modstart(parent
, *args
, **kwargs
):
17 state
.gotParent(parent
)
18 lib
.hookchan(state
.db
['chan'])(trivia_checkanswer
) # we need parent for this. so it goes here.
19 return lib
.modstart(parent
, *args
, **kwargs
)
20 def modstop(*args
, **kwargs
):
26 except Exception: pass
27 return lib
.modstop(*args
, **kwargs
)
30 import json
, random
, threading
, re
, time
, datetime
, os
34 except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
36 def findnth(haystack
, needle
, n
): #http://stackoverflow.com/a/1884151
37 parts
= haystack
.split(needle
, n
+1)
40 return len(haystack
)-len(parts
[-1])-len(needle
)
42 def person(num
, throwindexerror
=False):
44 return state
.db
['users'][state
.db
['ranks'][num
]]['realnick']
53 return str(state
.db
['users'][state
.db
['ranks'][num
]]['points'])
57 def country(num
, default
="??"):
58 return lib
.mod('userinfo')._get
(person(num
), 'country', default
=default
).upper()
60 class MyTimer(threading
._Timer
):
61 def __init__(self
, *args
, **kwargs
):
62 threading
._Timer
.__init
__(self
, *args
, **kwargs
)
65 class TriviaState(object):
66 def __init__(self
, parent
=None, pointvote
=False):
67 if parent
is not None:
68 self
.gotParent(parent
, pointvote
)
70 def gotParent(self
, parent
, pointvote
=False):
72 self
.questionfile
= self
.parent
.cfg
.get('trivia', 'jsonpath', default
="./modules/trivia.json")
73 self
.db
= json
.load(open(self
.questionfile
, "r"))
74 self
.questions
= self
.db
['questions'][self
.db
['category']]
75 self
.chan
= self
.db
['chan']
78 self
.nextquestiontimer
= None
81 self
.hintanswer
= None
83 self
.revealpossibilities
= None
85 self
.missedquestions
= 0
89 if 'lastwon' not in self
.db
or self
.db
['lastwon'] is None:
90 self
.db
['lastwon'] = time
.time()
93 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']])))
94 self
.getchan().msg("You have %s seconds." % (self
.db
['votetimer']))
95 self
.voteamounts
= dict([(x
, 0) for x
in self
.db
['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
96 self
.pointvote
= MyTimer(self
.db
['votetimer'], self
.endPointVote
)
97 self
.pointvote
.start()
105 self
.steptimer
.cancel()
106 self
.steptimer
= None
109 self
.nextquestiontimer
.cancel()
110 self
.nextquestiontimer
= None
112 #TODO remove if the replacement works
113 # if threading is not None and threading._Timer is not None:
114 # if isinstance(self.steptimer, threading._Timer):
115 # self.steptimer.cancel()
116 # if isinstance(self.nextquestiontimer, threading._Timer):
117 # self.nextquestiontimer.cancel()
118 # self.nextquestiontimer = None
121 def savedb(self
): #returns whether or not it was able to save
122 if json
is not None and json
.dump
is not None:
123 # json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
124 dbjson
= json
.dumps(self
.db
)
126 os
.rename(self
.questionfile
, self
.questionfile
+".auto.bak")
127 tmpfn
= os
.tempnam('.', 'trivia')
132 os
.rename(tmpfn
, self
.questionfile
)
134 except: #if something happens, restore the backup
135 os
.rename(self
.questionfile
+".auto.bak", self
.questionfile
)
138 except OSError: # temp file is already gone
140 raise #TODO: we may be better off just swallowing exceptions?
144 return self
.parent
.channel(self
.chan
)
146 return self
.getchan().bot
148 def nexthint(self
, hintnum
):
149 answer
= self
.hintanswer
151 if self
.hintstr
is None or self
.revealpossibilities
is None or self
.reveal
is None:
153 self
.hintstr
= list(re
.sub(r
'[a-zA-Z0-9]', '*', answer
))
154 self
.revealpossibilities
= range(''.join(self
.hintstr
).count('*'))
155 self
.reveal
= int(round(''.join(self
.hintstr
).count('*') * (7/24.0)))
157 oldhintstr
= ''.join(self
.hintstr
)
159 for i
in range(self
.reveal
):
160 revealcount
= random
.choice(self
.revealpossibilities
)
161 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
162 self
.revealpossibilities
.remove(revealcount
)
163 self
.hintstr
[revealloc
] = answer
[revealloc
]
164 if oldhintstr
!= ''.join(self
.hintstr
): self
.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
168 if hintnum
< self
.db
['hintnum']:
169 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
170 self
.steptimer
.start()
172 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
173 self
.steptimer
.start()
175 def doGameOver(self
):
176 msg
= self
.getchan().msg
179 msg("\00312THE GAME IS OVER!!!")
180 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
181 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
182 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
183 [msg("%dth place: %s (%s)" % (i
+1, person(i
, True), pts(i
))) for i
in range(3,10)]
184 except IndexError: pass
185 except Exception as e
:
186 msg("DERP! %r" % (e
))
188 self
.db
['lastwinner'] = winner
189 self
.db
['lastwon'] = time
.time()
191 if self
.db
['hofpath'] is not None and self
.db
['hofpath'] != '':
194 self
.db
['users'] = {}
195 self
.db
['ranks'] = []
200 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
201 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
202 self
.getbot().parent
.cfg
.get('trivia', 'con'),
203 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
204 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
205 except: pass #don't care if errors happen updating twitter.
207 self
.__init
__(self
.parent
, True)
211 try: return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
212 except: return "none"
214 try: return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
219 f
= open(self
.db
['hofpath'], 'rb+')
220 for i
in range(self
.db
['hoflines']): #skip this many lines
225 f
.write((self
.db
['hofformat']+"\n") % {
226 'date': time
.strftime("%F", time
.gmtime()),
227 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['lastwon'])),
228 'targetscore': self
.db
['target'],
229 'firstperson': person(0),
230 'firstscore': pts(0),
231 'secondperson': person(1),
232 'secondscore': pts(1),
233 'thirdperson': person(2),
234 'thirdscore': pts(2),
238 except Exception as e
:
244 def endPointVote(self
):
245 self
.getchan().msg("Voting has ended!")
246 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
247 for i
in range(len(votelist
)-1):
249 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
250 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
252 self
.db
['target'] = votelist
[-1][0]
253 self
.pointvote
= None
255 self
.nextquestion() #start the game!
257 def nextquestion(self
, qskipped
=False, iteration
=0, skipwait
=False):
258 self
.lastqid
= self
.curqid
261 if self
.gameover
== True:
262 return self
.doGameOver()
264 self
.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
265 self
.missedquestions
+= 1
267 self
.missedquestions
= 0
268 if 'topicformat' in self
.db
and self
.db
['topicformat'] is not None:
269 self
.getbot().conn
.send("TOPIC %s" % (self
.db
['chan']))
271 if isinstance(self
.steptimer
, threading
._Timer
):
272 self
.steptimer
.cancel()
273 if isinstance(self
.nextquestiontimer
, threading
._Timer
):
274 self
.nextquestiontimer
.cancel()
275 self
.nextquestiontimer
= None
279 self
.revealpossibilities
= None
284 if self
.missedquestions
> self
.db
['maxmissedquestions']:
286 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game." % (self
.missedquestions
))
290 self
._nextquestion
(iteration
)
292 self
.nextquestiontimer
= MyTimer(self
.db
['questionpause'], self
._nextquestion
, args
=[iteration
])
293 self
.nextquestiontimer
.start()
295 def _nextquestion(self
, iteration
):
296 if self
.nextq
is not None:
301 nextqid
= random
.randrange(0, len(self
.questions
))
302 nextq
= self
.questions
[nextqid
]
304 if nextq
[0][0] == "!":
306 nextq
= specialQuestion(nextq
)
308 if len(nextq
) > 2 and nextq
[2] - time
.time() < 7*24*60*60 and iteration
< 10:
309 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
311 nextq
[2] = time
.time()
313 nextq
.append(time
.time())
315 if isinstance(nextq
[1], basestring
):
316 nextq
[1] = nextq
[1].lower()
318 nextq
[1] = [s
.lower() for s
in nextq
[1]]
320 qtext
= "\00312,01Next up: "
321 qtext
+= "(%5d)" % (random
.randint(0,99999))
322 qary
= nextq
[0].split(None)
325 spacer
= random
.choice(
326 range(0x61,0x7A) + ([0x20]*4)
328 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(spacer
) #a-z
329 self
.getbot().fastmsg(self
.chan
, qtext
)
332 self
.curqid
= nextqid
334 if isinstance(self
.curq
[1], basestring
): self
.hintanswer
= self
.curq
[1]
335 else: self
.hintanswer
= random
.choice(self
.curq
[1])
337 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
338 self
.steptimer
.start()
340 def checkanswer(self
, answer
):
341 if self
.curq
is None:
343 elif isinstance(self
.curq
[1], basestring
):
344 return answer
.lower() == self
.curq
[1]
345 else: # assume it's a list or something.
346 return answer
.lower() in self
.curq
[1]
348 def addpoint(self
, user_obj
, count
=1):
349 user_nick
= str(user_obj
)
350 user
= user_nick
.lower() # save this separately as we use both
351 if user
in self
.db
['users']:
352 self
.db
['users'][user
]['points'] += count
354 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
355 self
.db
['ranks'].append(user
)
357 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
358 for i
in range(0, len(self
.db
['ranks'])):
359 nick
= self
.db
['ranks'][i
]
360 self
.db
['users'][nick
]['rank'] = i
362 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
365 return self
.db
['users'][user
]['points']
367 def points(self
, user
):
368 user
= str(user
).lower()
369 if user
in self
.db
['users']:
370 return self
.db
['users'][user
]['points']
374 def rank(self
, user
):
375 user
= str(user
).lower()
376 if user
in self
.db
['users']:
377 return self
.db
['users'][user
]['rank']+1
379 return len(self
.db
['users'])+1
381 def targetuser(self
, user
):
382 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
384 user
= str(user
).lower()
385 if user
in self
.db
['users']:
386 rank
= self
.db
['users'][user
]['rank']
388 return "you're in the lead!"
390 return self
.db
['ranks'][rank
-1]
392 return self
.db
['ranks'][-1]
393 def targetpoints(self
, user
):
394 if len(self
.db
['ranks']) == 0: return 0
396 user
= str(user
).lower()
397 if user
in self
.db
['users']:
398 rank
= self
.db
['users'][user
]['rank']
402 return "("+str(self
.db
['users'][self
.db
['ranks'][rank
-1]]['points'])+")"
404 return "("+str(self
.db
['users'][self
.db
['ranks'][-1]]['points'])+")"
406 state
= TriviaState()
408 # we have to hook this in modstart, since we don't know the channel until then.
409 def trivia_checkanswer(bot
, user
, chan
, *args
):
410 line
= ' '.join([str(arg
) for arg
in args
])
411 if state
.checkanswer(line
):
413 if state
.hintanswer
.lower() == line
.lower():
414 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
)))
416 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
)))
417 if state
.hintsgiven
== 0:
418 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
421 @lib.hook(glevel
=1, needchan
=False)
422 @lib.help(None, "saves the trivia database")
423 def save(bot
, user
, chan
, realtarget
, *args
):
424 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
428 bot
.msg(replyto
, "Save successful.")
430 bot
.msg(replyto
, "Save failed!")
432 @lib.hook(needchan
=False)
433 @lib.help("[<user>]", "shows how many points you or someone has")
434 def points(bot
, user
, chan
, realtarget
, *args
):
435 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
438 if len(args
) != 0: who
= args
[0]
441 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
443 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
444 @lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
446 def give(bot
, user
, chan
, realtarget
, *args
):
449 numpoints
= int(args
[1])
452 balance
= state
.addpoint(whoto
, numpoints
)
454 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
456 @lib.hook(glevel
=1, needchan
=False)
457 @lib.help("<qid>", "sets next question to one in the database")
459 def setnextid(bot
, user
, chan
, realtarget
, *args
):
462 state
.nextq
= state
.questions
[qid
]
463 if user
.glevel
>= lib
.STAFF
:
464 respstr
= "Done. Next question is: %s" % (state
.nextq
[0])
467 bot
.msg(user
, respstr
)
468 except Exception as e
:
469 bot
.msg(user
, "Error: %s" % (e
))
471 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
472 @lib.help("<q>*<a>", "sets next question to one not in database")
474 def setnext(bot
, user
, chan
, realtarget
, *args
):
475 line
= ' '.join([str(arg
) for arg
in args
])
476 linepieces
= line
.split('*')
477 if len(linepieces
) < 2:
478 bot
.msg(user
, "Error: need <question>*<answer>")
480 question
= linepieces
[0].strip()
481 answer
= linepieces
[1].strip()
482 state
.nextq
= [question
, answer
]
483 bot
.msg(user
, "Done.")
485 @lib.hook(glevel
=1, needchan
=False)
486 @lib.help(None, "skips to next question")
487 def skip(bot
, user
, chan
, realtarget
, *args
):
488 state
.nextquestion(qskipped
=True, skipwait
=True)
490 @lib.hook(needchan
=False)
491 @lib.help(None, "starts the trivia game")
492 def start(bot
, user
, chan
, realtarget
, *args
):
493 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
496 if chan
is not None and chan
.name
!= state
.db
['chan']:
497 bot
.msg(replyto
, "That command isn't valid here.")
500 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
501 bot
.msg(state
.db
['chan'], "%s has started the game!" % (user
))
502 state
.nextquestion(skipwait
=True)
503 elif state
.pointvote
is not None:
504 bot
.msg(user
, "There's a vote in progress!")
506 bot
.msg(user
, "Game is already started!")
508 @lib.hook('stop', glevel
=1, needchan
=False)
509 @lib.help(None, "stops the trivia game")
510 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
512 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
514 bot
.msg(user
, "Game isn't running.")
520 state
.steptimer
.cancel()
521 except Exception as e
:
522 print "!!! steptimer.cancel(): %s %r" % (e
,e
)
523 state
.steptimer
= None
525 state
.nextquestiontimer
.cancel()
526 except Exception as e
:
527 print "!!! nextquestiontimer.cancel(): %s %r" % (e
,e
)
528 state
.nextquestiontimer
= None
531 @lib.hook(needchan
=False)
532 @lib.help("<reason>", "reports a bad question to the admins")
534 def badq(bot
, user
, chan
, realtarget
, *args
):
535 lastqid
= state
.lastqid
536 curqid
= state
.curqid
538 reason
= ' '.join(args
)
539 state
.db
['badqs'].append([state
.db
['category'], lastqid
, curqid
, reason
])
540 bot
.msg(user
, "Reported bad question.")
542 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
543 @lib.help(None, "shows a list of BADQ reports")
544 def badqs(bot
, user
, chan
, realtarget
, *args
):
545 if len(state
.db
['badqs']) == 0:
546 bot
.msg(user
, "No reports.")
548 for i
in range(len(state
.db
['badqs'])):
550 report
= state
.db
['badqs'][i
]
551 bot
.msg(user
, "Report #%d: Cat=%s LastQ=%r CurQ=%r: %s" % (i
, report
[0], report
[1], report
[2], report
[3]))
552 try: lq
= state
.db
['questions'][report
[0]][int(report
[1])]
553 except Exception as e
: lq
= (None,None)
554 try: cq
= state
.db
['questions'][report
[0]][int(report
[2])]
555 except Exception as e
: cq
= (None, None)
556 bot
.msg(user
, "- Last: %s*%s" % (lq
[0], lq
[1]))
557 bot
.msg(user
, "- Curr: %s*%s" % (cq
[0], cq
[1]))
558 except Exception as e
:
559 bot
.msg(user
, "- Exception: %r" % (e
))
561 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
562 @lib.hook(None, "clears list of BADQ reports")
563 def clearbadqs(bot
, user
, chan
, realtarget
, *args
):
564 state
.db
['badqs'] = []
565 bot
.msg(user
, "Cleared reports.")
567 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
568 @lib.hook("<badqid>", "removes a BADQ report")
570 def delbadq(bot
, user
, chan
, realtarget
, *args
):
573 del state
.db
['badqs'][qid
]
574 bot
.msg(user
, "Removed report #%d" % (qid
))
576 bot
.msg(user
, "Failed!")
578 @lib.hook(needchan
=False)
579 @lib.help("[<user>]", "shows you or someone else's rank")
580 def rank(bot
, user
, chan
, realtarget
, *args
):
581 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
584 if len(args
) != 0: who
= args
[0]
587 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
)))
589 @lib.hook(needchan
=False)
590 @lib.help(None, "shows top10 list")
591 def top10(bot
, user
, chan
, realtarget
, *args
):
592 if len(state
.db
['ranks']) == 0:
593 return bot
.msg(state
.db
['chan'], "No one is ranked!")
595 max = len(state
.db
['ranks'])
598 replylist
= ', '.join(["%s (%s) %s" % (person(x
), country(x
), pts(x
)) for x
in range(max)])
599 bot
.msg(state
.db
['chan'], "Top 10: %s" % (replylist
))
601 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
602 @lib.help("<target score>", "changes the target score for this round")
603 def settarget(bot
, user
, chan
, realtarget
, *args
):
605 state
.db
['target'] = int(args
[0])
606 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
608 if state
.pointvote
is not None:
609 state
.pointvote
.cancel()
610 state
.pointvote
= None
611 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
612 except Exception as e
:
614 bot
.msg(user
, "Failed to set target.")
616 @lib.hook(needchan
=False)
617 @lib.help("<option>", "votes for a trarget score for next round")
618 def vote(bot
, user
, chan
, realtarget
, *args
):
619 if state
.pointvote
is not None:
620 if int(args
[0]) in state
.voteamounts
:
621 state
.voteamounts
[int(args
[0])] += 1
622 bot
.msg(user
, "Your vote has been recorded.")
624 bot
.msg(user
, "Sorry - that's not an option!")
626 bot
.msg(user
, "There's no vote in progress.")
628 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
629 @lib.help("<number>", "sets the max missed question before game stops")
630 def maxmissed(bot
, user
, chan
, realtarget
, *args
):
632 state
.db
['maxmissedquestions'] = int(args
[0])
633 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
635 bot
.msg(user
, "Failed to set maxmissed.")
637 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
638 @lib.help("<seconds>", "sets the time between hints")
639 def hinttimer(bot
, user
, chan
, realtarget
, *args
):
641 state
.db
['hinttimer'] = float(args
[0])
642 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
644 bot
.msg(user
, "Failed to set hint timer.")
646 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
647 @lib.help("<number>", "sets the number of hints given")
648 def hintnum(bot
, user
, chan
, realtarget
, *args
):
650 state
.db
['hintnum'] = int(args
[0])
651 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
653 bot
.msg(user
, "Failed to set hintnum.")
655 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
656 @lib.help("<seconds>", "sets the pause between questions")
657 def questionpause(bot
, user
, chan
, realtarget
, *args
):
659 state
.db
['questionpause'] = float(args
[0])
660 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
662 bot
.msg(user
, "Failed to set questionpause.")
664 @lib.hook(glevel
=1, needchan
=False)
665 @lib.help("<full question>", "finds a qid given a complete question")
666 def findq(bot
, user
, chan
, realtarget
, *args
):
668 if args
[0][0] == "@":
669 cat
= args
.pop(0)[1:].lower()
670 questions
= state
.db
['questions'][cat
]
672 questions
= state
.questions
675 bot
.msg(user
, "You need to specify the question.")
678 searchkey
= ' '.join(args
).lower()
679 matches
= [str(i
) for i
in range(len(questions
)) if questions
[i
][0].lower() == searchkey
]
681 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
682 elif len(matches
) == 1:
683 bot
.msg(user
, "One match: %s" % (matches
[0]))
685 bot
.msg(user
, "No match.")
687 @lib.hook(glevel
=1, needchan
=False)
688 @lib.help("[@<category>] <regex>", "finds a qid given a regex or partial question")
689 def findqre(bot
, user
, chan
, realtarget
, *args
):
691 if args
[0][0] == "@":
692 cat
= args
.pop(0)[1:].lower()
693 questions
= state
.db
['questions'][cat
]
695 questions
= state
.questions
698 bot
.msg(user
, "You need to specify a search string.")
701 searcher
= re
.compile(' '.join(args
), re
.IGNORECASE
)
702 matches
= [str(i
) for i
in range(len(questions
)) if searcher
.search(questions
[i
][0]) is not None]
703 if len(matches
) > 25:
704 bot
.msg(user
, "Too many matches! (>25)")
705 elif len(matches
) > 1:
706 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
707 elif len(matches
) == 1:
708 bot
.msg(user
, "One match: %s" % (matches
[0]))
710 bot
.msg(user
, "No match.")
712 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
713 @lib.help("[@<category>] <qid>", "displays the q*a for a qid", "category defaults to current")
714 def showq(bot
, user
, chan
, realtarget
, *args
):
716 if args
[0][0] == "@":
717 cat
= args
.pop(0)[1:].lower()
718 questions
= state
.db
['questions'][cat
]
720 questions
= state
.questions
725 bot
.msg(user
, "Specify a numeric question ID.")
730 bot
.msg(user
, "ID not valid.")
732 bot
.msg(user
, "%s: %s*%s" % (qid
, q
[0], q
[1]))
734 @lib.hook(('delq', 'deleteq'), glevel
=lib
.STAFF
, needchan
=False)
735 @lib.help("[@<category>] <qid>", "removes a question from the database")
736 def delq(bot
, user
, chan
, realtarget
, *args
):
738 if args
[0][0] == "@":
739 cat
= args
.pop(0)[1:].lower()
740 questions
= state
.db
['questions'][cat
]
742 questions
= state
.questions
745 backup
= questions
[int(args
[0])]
746 del questions
[int(args
[0])]
747 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]))
749 bot
.msg(user
, "Couldn't delete that question. %r" % (e
))
751 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
752 @lib.help("[@<category>] <q>*<a>", "adds a question")
753 def addq(bot
, user
, chan
, realtarget
, *args
):
755 if args
[0][0] == "@":
756 cat
= args
.pop(0)[1:].lower()
757 questions
= state
.db
['questions'][cat
]
759 questions
= state
.questions
761 line
= ' '.join([str(arg
) for arg
in args
])
762 linepieces
= line
.split('*')
763 if len(linepieces
) < 2:
764 bot
.msg(user
, "Error: need <question>*<answer>")
766 question
= linepieces
[0].strip()
767 answer
= linepieces
[1].strip()
768 questions
.append([question
, answer
])
769 bot
.msg(user
, "Done. Question is #%s" % (len(questions
)-1))
771 @lib.hook(glevel
=1, needchan
=False)
772 @lib.help("<category>", "change category")
773 def setcat(bot
, user
, chan
, realtarget
, *args
):
774 category
= args
[0].lower()
775 if category
in state
.db
['questions']:
776 state
.db
['category'] = category
777 state
.questions
= state
.db
['questions'][category
]
778 bot
.msg(user
, "Changed category to %s" % (category
))
780 bot
.msg(user
, "That category doesn't exist.")
782 @lib.hook(needchan
=False)
783 @lib.help(None, "list categories")
784 def listcats(bot
, user
, chan
, realtarget
, *args
):
785 cats
= ["%s (%d)" % (c
, len(state
.db
['questions'][c
])) for c
in state
.db
['questions'].keys()]
786 bot
.msg(user
, "Categories: %s" % (', '.join(cats
)))
788 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
789 @lib.help("<category>", "adds an empty category")
790 def addcat(bot
, user
, chan
, realtarget
, *args
):
791 category
= args
[0].lower()
792 if category
not in state
.db
['questions']:
793 state
.db
['questions'][category
] = []
794 bot
.msg(user
, "Added category %s" % (category
))
796 bot
.msg(user
, "Category already exists.")
798 @lib.hook(glevel
=lib
.MANAGER
, needchan
=False)
799 @lib.help("<category>", "deletes an entire category")
800 def delcat(bot
, user
, chan
, realtarget
, *args
):
801 category
= args
[0].lower()
802 if category
== state
.db
['category']:
803 bot
.msg(user
, "Category currently in use!")
804 elif category
in state
.db
['questions']:
805 length
= len(state
.db
['questions'][category
])
806 del state
.db
['questions'][category
]
807 bot
.msg(user
, "Deleted category %s (%d questions)" % (category
, length
))
809 bot
.msg(user
, "Category does not exist.")
811 @lib.hook(needchan
=False)
812 def triviahelp(bot
, user
, chan
, realtarget
, *args
):
813 bot
.slowmsg(user
, "START")
814 bot
.slowmsg(user
, "TOP10")
815 bot
.slowmsg(user
, "POINTS [<user>]")
816 bot
.slowmsg(user
, "RANK [<user>]")
817 bot
.slowmsg(user
, "BADQ <reason> (include info to identify question)")
819 bot
.slowmsg(user
, "SKIP (KNOWN)")
820 bot
.slowmsg(user
, "STOP (KNOWN)")
821 bot
.slowmsg(user
, "FINDQ <full question> (KNOWN)")
822 bot
.slowmsg(user
, "FINDQRE <regex> (KNOWN)")
823 bot
.slowmsg(user
, "SETNEXTID <qid> (KNOWN)")
824 if user
.glevel
>= lib
.STAFF
:
825 bot
.slowmsg(user
, "GIVE <user> [<points>] (STAFF)")
826 bot
.slowmsg(user
, "SETNEXT <q>*<a> (STAFF)")
827 bot
.slowmsg(user
, "ADDQ <q>*<a> (STAFF)")
828 bot
.slowmsg(user
, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
829 bot
.slowmsg(user
, "SHOWQ <qid> (STAFF)")
830 bot
.slowmsg(user
, "BADQS (STAFF)")
831 bot
.slowmsg(user
, "CLEARBADQS (STAFF)")
832 bot
.slowmsg(user
, "DELBADQ <reportid> (STAFF)")
833 if user
.glevel
>= lib
.ADMIN
:
834 bot
.slowmsg(user
, "SETTARGET <points> (ADMIN)")
835 bot
.slowmsg(user
, "MAXMISSED <questions> (ADMIN)")
836 bot
.slowmsg(user
, "HINTTIMER <float seconds> (ADMIN)")
837 bot
.slowmsg(user
, "HINTNUM <hints> (ADMIN)")
838 bot
.slowmsg(user
, "QUESTIONPAUSE <float seconds> (ADMIN)")
841 def num_417(bot
, textline
):
842 # bot.fastmsg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
843 state
.nextquestion(qskipped
=False, skipwait
=True)
846 def num_TOPIC(bot
, textline
):
847 pieces
= textline
.split(None, 4)
849 if chan
!= state
.db
['chan']:
851 gottopic
= pieces
[4][1:]
853 formatted
= state
.db
['topicformat'] % {
854 'chan': state
.db
['chan'],
855 'top1': "%s (%s)" % (person(0), pts(0)),
857 "%s (%s)" % (person(x
), pts(x
))
858 for x
in range(3) if x
< len(state
.db
['ranks'])
861 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
862 for x
in range(3) if x
< len(state
.db
['ranks'])
865 "%s (%s)" % (person(x
), pts(x
))
866 for x
in range(10) if x
< len(state
.db
['ranks'])
869 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
870 for x
in range(10) if x
< len(state
.db
['ranks'])
872 'lastwinner': state
.db
['lastwinner'],
873 'lastwon': time
.strftime("%b %d", time
.gmtime(state
.db
['lastwon'])),
874 'target': state
.db
['target'],
876 if gottopic
!= formatted
:
877 state
.getbot().conn
.send("TOPIC %s :%s" % (state
.db
['chan'], formatted
))
880 def specialQuestion(oldq
):
881 newq
= [oldq
[0], oldq
[1]]
882 qtype
= oldq
[0].upper()
884 if qtype
== "!MONTH":
885 newq
[0] = "What month is it currently (in UTC)?"
886 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
887 elif qtype
== "!MATH+":
888 randnum1
= random
.randrange(0, 11)
889 randnum2
= random
.randrange(0, 11)
890 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
891 newq
[1] = spellout(randnum1
+randnum2
)
896 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
897 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
898 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"