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',
10 'depends': ['userinfo'],
16 lib
= modlib
.modlib(__name__
)
17 def modstart(parent
, *args
, **kwargs
):
18 state
.gotParent(parent
)
19 lib
.hookchan(state
.db
['chan'])(trivia_checkanswer
) # we need parent for this. so it goes here.
20 return lib
.modstart(parent
, *args
, **kwargs
)
21 def modstop(*args
, **kwargs
):
27 except Exception: pass
28 return lib
.modstop(*args
, **kwargs
)
31 import json
, random
, threading
, re
, time
, datetime
, os
35 except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
37 def findnth(haystack
, needle
, n
): #http://stackoverflow.com/a/1884151
38 parts
= haystack
.split(needle
, n
+1)
41 return len(haystack
)-len(parts
[-1])-len(needle
)
43 def person(num
, throwindexerror
=False):
45 return state
.db
['users'][state
.db
['ranks'][num
]]['realnick']
54 return str(state
.db
['users'][state
.db
['ranks'][num
]]['points'])
58 def country(num
, default
="??"):
59 return lib
.mod('userinfo')._get
(person(num
), 'country', default
=default
).upper()
61 class MyTimer(threading
._Timer
):
62 def __init__(self
, *args
, **kwargs
):
63 threading
._Timer
.__init
__(self
, *args
, **kwargs
)
66 class TriviaState(object):
67 def __init__(self
, parent
=None, pointvote
=False):
68 if parent
is not None:
69 self
.gotParent(parent
, pointvote
)
71 def gotParent(self
, parent
, pointvote
=False):
73 self
.questionfile
= self
.parent
.cfg
.get('trivia', 'jsonpath', default
="./modules/trivia.json")
74 self
.db
= json
.load(open(self
.questionfile
, "r"))
75 self
.questions
= self
.db
['questions'][self
.db
['category']]
76 self
.chan
= self
.db
['chan']
79 self
.nextquestiontimer
= None
82 self
.hintanswer
= None
84 self
.revealpossibilities
= None
86 self
.missedquestions
= 0
90 if 'lastwon' not in self
.db
or self
.db
['lastwon'] is None:
91 self
.db
['lastwon'] = time
.time()
94 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']])))
95 self
.getchan().msg("You have %s seconds." % (self
.db
['votetimer']))
96 self
.voteamounts
= dict([(x
, 0) for x
in self
.db
['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
97 self
.pointvote
= MyTimer(self
.db
['votetimer'], self
.endPointVote
)
98 self
.pointvote
.start()
100 self
.pointvote
= None
106 self
.steptimer
.cancel()
107 self
.steptimer
= None
110 self
.nextquestiontimer
.cancel()
111 self
.nextquestiontimer
= None
114 def savedb(self
): #returns whether or not it was able to save
115 if json
is not None and json
.dump
is not None:
116 # json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
117 dbjson
= json
.dumps(self
.db
)
119 os
.rename(self
.questionfile
, self
.questionfile
+".auto.bak")
120 tmpfn
= os
.tempnam('.', 'trivia')
125 os
.rename(tmpfn
, self
.questionfile
)
127 except: #if something happens, restore the backup
128 os
.rename(self
.questionfile
+".auto.bak", self
.questionfile
)
131 except OSError: # temp file is already gone
133 raise # we may be better off just swallowing exceptions?
137 return self
.parent
.channel(self
.chan
)
139 return self
.getchan().bot
141 def nexthint(self
, hintnum
):
142 answer
= self
.hintanswer
144 if self
.hintstr
is None or self
.revealpossibilities
is None or self
.reveal
is None:
146 self
.hintstr
= list(re
.sub(r
'[a-zA-Z0-9]', '*', answer
))
147 self
.revealpossibilities
= range(''.join(self
.hintstr
).count('*'))
148 self
.reveal
= int(round(''.join(self
.hintstr
).count('*') * (7/24.0)))
150 oldhintstr
= ''.join(self
.hintstr
)
152 for i
in range(self
.reveal
):
153 revealcount
= random
.choice(self
.revealpossibilities
)
154 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
155 self
.revealpossibilities
.remove(revealcount
)
156 self
.hintstr
[revealloc
] = answer
[revealloc
]
157 if oldhintstr
!= ''.join(self
.hintstr
): self
.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
161 if hintnum
< self
.db
['hintnum']:
162 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
163 self
.steptimer
.start()
165 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
166 self
.steptimer
.start()
168 def doGameOver(self
):
169 msg
= self
.getchan().msg
172 msg("\00312THE GAME IS OVER!!!")
173 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
174 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
175 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
176 [msg("%dth place: %s (%s)" % (i
+1, person(i
, True), pts(i
))) for i
in range(3,10)]
177 except IndexError: pass
178 except Exception as e
:
179 msg("DERP! %r" % (e
))
181 self
.db
['lastwinner'] = winner
182 self
.db
['lastwon'] = time
.time()
184 if self
.db
['hofpath'] is not None and self
.db
['hofpath'] != '':
187 self
.db
['users'] = {}
188 self
.db
['ranks'] = []
193 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
194 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
195 self
.getbot().parent
.cfg
.get('trivia', 'con'),
196 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
197 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
198 except: pass #don't care if errors happen updating twitter.
200 self
.__init
__(self
.parent
, True)
204 try: return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
205 except: return "none"
207 try: return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
212 f
= open(self
.db
['hofpath'], 'rb+')
213 for i
in range(self
.db
['hoflines']): #skip this many lines
218 f
.write((self
.db
['hofformat']+"\n") % {
219 'date': time
.strftime("%F", time
.gmtime()),
220 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['lastwon'])),
221 'targetscore': self
.db
['target'],
222 'firstperson': person(0),
223 'firstscore': pts(0),
224 'secondperson': person(1),
225 'secondscore': pts(1),
226 'thirdperson': person(2),
227 'thirdscore': pts(2),
231 except Exception as e
:
237 def endPointVote(self
):
238 self
.getchan().msg("Voting has ended!")
239 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
240 for i
in range(len(votelist
)-1):
242 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
243 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
245 self
.db
['target'] = votelist
[-1][0]
246 self
.pointvote
= None
248 self
.nextquestion() #start the game!
250 def nextquestion(self
, qskipped
=False, iteration
=0, skipwait
=False):
251 self
.lastqid
= self
.curqid
254 if self
.gameover
== True:
255 return self
.doGameOver()
257 self
.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
258 self
.missedquestions
+= 1
260 self
.missedquestions
= 0
261 if 'topicformat' in self
.db
and self
.db
['topicformat'] is not None:
262 self
.getbot().conn
.send("TOPIC %s" % (self
.db
['chan']))
264 if isinstance(self
.steptimer
, MyTimer
):
265 self
.steptimer
.cancel()
266 if isinstance(self
.nextquestiontimer
, MyTimer
):
267 self
.nextquestiontimer
.cancel()
268 self
.nextquestiontimer
= None
272 self
.revealpossibilities
= None
277 if self
.missedquestions
> self
.db
['maxmissedquestions']:
279 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game." % (self
.missedquestions
))
283 self
._nextquestion
(iteration
)
285 self
.nextquestiontimer
= MyTimer(self
.db
['questionpause'], self
._nextquestion
, args
=[iteration
])
286 self
.nextquestiontimer
.start()
288 def _nextquestion(self
, iteration
):
289 if self
.nextq
is not None:
294 nextqid
= random
.randrange(0, len(self
.questions
))
295 nextq
= self
.questions
[nextqid
]
297 if nextq
[0].startswith("!"):
299 nextq
= specialQuestion(nextq
)
301 if len(nextq
) > 2 and nextq
[2] - time
.time() < 7*24*60*60 and iteration
< 10:
302 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
304 nextq
[2] = time
.time()
306 nextq
.append(time
.time())
308 if isinstance(nextq
[1], basestring
):
309 nextq
[1] = nextq
[1].lower()
311 nextq
[1] = [s
.lower() for s
in nextq
[1]]
313 qtext
= "\00312,01Next up: "
314 qtext
+= "(%5d)" % (random
.randint(0,99999))
315 qary
= nextq
[0].split(None)
318 spacer
= random
.choice(
319 range(0x61,0x7A) + ([0x20]*4)
321 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(spacer
) #a-z
322 self
.getbot().fastmsg(self
.chan
, qtext
)
325 self
.curqid
= nextqid
327 if isinstance(self
.curq
[1], basestring
): self
.hintanswer
= self
.curq
[1]
328 else: self
.hintanswer
= random
.choice(self
.curq
[1])
330 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
331 self
.steptimer
.start()
333 def checkanswer(self
, answer
):
334 if self
.curq
is None:
336 elif isinstance(self
.curq
[1], basestring
):
337 return answer
.lower() == self
.curq
[1]
338 else: # assume it's a list or something.
339 return answer
.lower() in self
.curq
[1]
341 def addpoint(self
, user_obj
, count
=1):
342 user_nick
= str(user_obj
)
343 user
= user_nick
.lower() # save this separately as we use both
344 if user
in self
.db
['users']:
345 self
.db
['users'][user
]['points'] += count
347 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
348 self
.db
['ranks'].append(user
)
350 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
351 for i
in range(0, len(self
.db
['ranks'])):
352 nick
= self
.db
['ranks'][i
]
353 self
.db
['users'][nick
]['rank'] = i
355 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
358 return self
.db
['users'][user
]['points']
360 def points(self
, user
):
361 user
= str(user
).lower()
362 if user
in self
.db
['users']:
363 return self
.db
['users'][user
]['points']
367 def rank(self
, user
):
368 user
= str(user
).lower()
369 if user
in self
.db
['users']:
370 return self
.db
['users'][user
]['rank']+1
372 return len(self
.db
['users'])+1
374 def targetuser(self
, user
):
375 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
377 user
= str(user
).lower()
378 if user
in self
.db
['users']:
379 rank
= self
.db
['users'][user
]['rank']
381 return "you're in the lead!"
383 return self
.db
['ranks'][rank
-1]
385 return self
.db
['ranks'][-1]
386 def targetpoints(self
, user
):
387 if len(self
.db
['ranks']) == 0: return 0
389 user
= str(user
).lower()
390 if user
in self
.db
['users']:
391 rank
= self
.db
['users'][user
]['rank']
395 return "("+str(self
.db
['users'][self
.db
['ranks'][rank
-1]]['points'])+")"
397 return "("+str(self
.db
['users'][self
.db
['ranks'][-1]]['points'])+")"
399 state
= TriviaState()
401 # we have to hook this in modstart, since we don't know the channel until then.
402 def trivia_checkanswer(bot
, user
, chan
, *args
):
403 line
= ' '.join([str(arg
) for arg
in args
])
404 if state
.checkanswer(line
):
406 if state
.hintanswer
.lower() == line
.lower():
407 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
)))
409 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
)))
410 if state
.hintsgiven
== 0:
411 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
414 @lib.hook(glevel
=1, needchan
=False, wantchan
=True)
415 @lib.help(None, "saves the trivia database")
416 def save(bot
, user
, chan
, realtarget
, *args
):
417 if chan
is not None: replyto
= chan
421 bot
.msg(replyto
, "Save successful.")
423 bot
.msg(replyto
, "Save failed!")
425 @lib.hook(needchan
=False, wantchan
=True)
426 @lib.help("[<user>]", "shows how many points you or someone has")
427 def points(bot
, user
, chan
, realtarget
, *args
):
428 if chan
is not None: eplyto
= chan
431 if len(args
) != 0: who
= args
[0]
434 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
436 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
437 @lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
439 def give(bot
, user
, chan
, realtarget
, *args
):
442 numpoints
= int(args
[1])
445 balance
= state
.addpoint(whoto
, numpoints
)
447 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
449 @lib.hook(glevel
=1, needchan
=False)
450 @lib.help("<qid>", "sets next question to one in the database")
452 def setnextid(bot
, user
, chan
, realtarget
, *args
):
455 state
.nextq
= state
.questions
[qid
]
456 if user
.glevel
>= lib
.STAFF
:
457 respstr
= "Done. Next question is: %s" % (state
.nextq
[0])
460 bot
.msg(user
, respstr
)
461 except Exception as e
:
462 bot
.msg(user
, "Error: %s" % (e
))
464 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
465 @lib.help("<q>*<a>", "sets next question to one not in database")
467 def setnext(bot
, user
, chan
, realtarget
, *args
):
468 line
= ' '.join([str(arg
) for arg
in args
])
469 linepieces
= line
.split('*')
470 if len(linepieces
) < 2:
471 bot
.msg(user
, "Error: need <question>*<answer>")
473 question
= linepieces
[0].strip()
474 answer
= linepieces
[1].strip()
475 state
.nextq
= [question
, answer
]
476 bot
.msg(user
, "Done.")
478 @lib.hook(glevel
=1, needchan
=False)
479 @lib.help(None, "skips to next question")
480 def skip(bot
, user
, chan
, realtarget
, *args
):
481 state
.nextquestion(qskipped
=True, skipwait
=True)
483 @lib.hook(needchan
=False, wantchan
=True)
484 @lib.help(None, "starts the trivia game")
485 def start(bot
, user
, chan
, realtarget
, *args
):
486 if chan
is not None: replyto
= chan
489 if chan
is not None and chan
.name
!= state
.db
['chan']:
490 bot
.msg(replyto
, "That command isn't valid here.")
493 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
494 bot
.msg(state
.db
['chan'], "%s has started the game!" % (user
))
495 state
.nextquestion(skipwait
=True)
496 elif state
.pointvote
is not None:
497 bot
.msg(user
, "There's a vote in progress!")
499 bot
.msg(user
, "Game is already started!")
501 @lib.hook('stop', glevel
=1, needchan
=False)
502 @lib.help(None, "stops the trivia game")
503 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
505 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
507 bot
.msg(user
, "Game isn't running.")
513 state
.steptimer
.cancel()
514 except Exception as e
:
515 print "!!! steptimer.cancel(): %s %r" % (e
,e
)
516 state
.steptimer
= None
518 state
.nextquestiontimer
.cancel()
519 except Exception as e
:
520 print "!!! nextquestiontimer.cancel(): %s %r" % (e
,e
)
521 state
.nextquestiontimer
= None
524 @lib.hook(needchan
=False)
525 @lib.help("<reason>", "reports a bad question to the admins")
527 def badq(bot
, user
, chan
, realtarget
, *args
):
528 lastqid
= state
.lastqid
529 curqid
= state
.curqid
531 reason
= ' '.join(args
)
532 state
.db
['badqs'].append([state
.db
['category'], lastqid
, curqid
, reason
])
533 bot
.msg(user
, "Reported bad question.")
535 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
536 @lib.help(None, "shows a list of BADQ reports")
537 def badqs(bot
, user
, chan
, realtarget
, *args
):
538 if len(state
.db
['badqs']) == 0:
539 bot
.msg(user
, "No reports.")
541 for i
in range(len(state
.db
['badqs'])):
543 report
= state
.db
['badqs'][i
]
544 bot
.msg(user
, "Report #%d: Cat=%s LastQ=%r CurQ=%r: %s" % (i
, report
[0], report
[1], report
[2], report
[3]))
545 try: lq
= state
.db
['questions'][report
[0]][int(report
[1])]
546 except Exception as e
: lq
= (None,None)
547 try: cq
= state
.db
['questions'][report
[0]][int(report
[2])]
548 except Exception as e
: cq
= (None, None)
549 bot
.msg(user
, "- Last: %s*%s" % (lq
[0], lq
[1]))
550 bot
.msg(user
, "- Curr: %s*%s" % (cq
[0], cq
[1]))
551 except Exception as e
:
552 bot
.msg(user
, "- Exception: %r" % (e
))
554 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
555 @lib.hook(None, "clears list of BADQ reports")
556 def clearbadqs(bot
, user
, chan
, realtarget
, *args
):
557 state
.db
['badqs'] = []
558 bot
.msg(user
, "Cleared reports.")
560 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
561 @lib.hook("<badqid>", "removes a BADQ report")
563 def delbadq(bot
, user
, chan
, realtarget
, *args
):
566 del state
.db
['badqs'][qid
]
567 bot
.msg(user
, "Removed report #%d" % (qid
))
569 bot
.msg(user
, "Failed!")
571 @lib.hook(needchan
=False, wantchan
=True)
572 @lib.help("[<user>]", "shows you or someone else's rank")
573 def rank(bot
, user
, chan
, realtarget
, *args
):
574 if chan
is not None: replyto
= chan
577 if len(args
) != 0: who
= args
[0]
580 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
)))
582 @lib.hook(needchan
=False)
583 @lib.help(None, "shows top10 list")
584 def top10(bot
, user
, chan
, realtarget
, *args
):
585 if len(state
.db
['ranks']) == 0:
586 return bot
.msg(state
.db
['chan'], "No one is ranked!")
588 max = len(state
.db
['ranks'])
591 replylist
= ', '.join(["%s (%s) %s" % (person(x
), country(x
), pts(x
)) for x
in range(max)])
592 bot
.msg(state
.db
['chan'], "Top 10: %s" % (replylist
))
594 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
595 @lib.help("<target score>", "changes the target score for this round")
596 def settarget(bot
, user
, chan
, realtarget
, *args
):
598 state
.db
['target'] = int(args
[0])
599 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
601 if state
.pointvote
is not None:
602 state
.pointvote
.cancel()
603 state
.pointvote
= None
604 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
605 except Exception as e
:
607 bot
.msg(user
, "Failed to set target.")
609 @lib.hook(needchan
=False)
610 @lib.help("<option>", "votes for a trarget score for next round")
611 def vote(bot
, user
, chan
, realtarget
, *args
):
612 if state
.pointvote
is not None:
613 if int(args
[0]) in state
.voteamounts
:
614 state
.voteamounts
[int(args
[0])] += 1
615 bot
.msg(user
, "Your vote has been recorded.")
617 bot
.msg(user
, "Sorry - that's not an option!")
619 bot
.msg(user
, "There's no vote in progress.")
621 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
622 @lib.help("<number>", "sets the max missed question before game stops")
623 def maxmissed(bot
, user
, chan
, realtarget
, *args
):
625 state
.db
['maxmissedquestions'] = int(args
[0])
626 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
628 bot
.msg(user
, "Failed to set maxmissed.")
630 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
631 @lib.help("<seconds>", "sets the time between hints")
632 def hinttimer(bot
, user
, chan
, realtarget
, *args
):
634 state
.db
['hinttimer'] = float(args
[0])
635 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
637 bot
.msg(user
, "Failed to set hint timer.")
639 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
640 @lib.help("<number>", "sets the number of hints given")
641 def hintnum(bot
, user
, chan
, realtarget
, *args
):
643 state
.db
['hintnum'] = int(args
[0])
644 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
646 bot
.msg(user
, "Failed to set hintnum.")
648 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
649 @lib.help("<seconds>", "sets the pause between questions")
650 def questionpause(bot
, user
, chan
, realtarget
, *args
):
652 state
.db
['questionpause'] = float(args
[0])
653 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
655 bot
.msg(user
, "Failed to set questionpause.")
657 @lib.hook(glevel
=1, needchan
=False)
658 @lib.help("<full question>", "finds a qid given a complete question")
659 def findq(bot
, user
, chan
, realtarget
, *args
):
661 if args
[0].startswith("@"):
662 cat
= args
.pop(0)[1:].lower()
663 questions
= state
.db
['questions'][cat
]
665 questions
= state
.questions
668 bot
.msg(user
, "You need to specify the question.")
671 searchkey
= ' '.join(args
).lower()
672 matches
= [str(i
) for i
in range(len(questions
)) if questions
[i
][0].lower() == searchkey
]
674 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
675 elif len(matches
) == 1:
676 bot
.msg(user
, "One match: %s" % (matches
[0]))
678 bot
.msg(user
, "No match.")
680 @lib.hook(glevel
=1, needchan
=False)
681 @lib.help("[@<category>] <regex>", "finds a qid given a regex or partial question")
682 def findqre(bot
, user
, chan
, realtarget
, *args
):
684 if args
[0].startswith("@"):
685 cat
= args
.pop(0)[1:].lower()
686 questions
= state
.db
['questions'][cat
]
688 questions
= state
.questions
691 bot
.msg(user
, "You need to specify a search string.")
694 searcher
= re
.compile(' '.join(args
), re
.IGNORECASE
)
695 matches
= [str(i
) for i
in range(len(questions
)) if searcher
.search(questions
[i
][0]) is not None]
696 if len(matches
) > 25:
697 bot
.msg(user
, "Too many matches! (>25)")
698 elif len(matches
) > 1:
699 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
700 elif len(matches
) == 1:
701 bot
.msg(user
, "One match: %s" % (matches
[0]))
703 bot
.msg(user
, "No match.")
705 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
706 @lib.help("[@<category>] <qid>", "displays the q*a for a qid", "category defaults to current")
707 def showq(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
718 bot
.msg(user
, "Specify a numeric question ID.")
723 bot
.msg(user
, "ID not valid.")
725 bot
.msg(user
, "%s: %s*%s" % (qid
, q
[0], q
[1]))
727 @lib.hook(('delq', 'deleteq'), glevel
=lib
.STAFF
, needchan
=False)
728 @lib.help("[@<category>] <qid>", "removes a question from the database")
729 def delq(bot
, user
, chan
, realtarget
, *args
):
731 if args
[0].startswith("@"):
732 cat
= args
.pop(0)[1:].lower()
733 questions
= state
.db
['questions'][cat
]
735 questions
= state
.questions
738 backup
= questions
[int(args
[0])]
739 del questions
[int(args
[0])]
740 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]))
742 bot
.msg(user
, "Couldn't delete that question. %r" % (e
))
744 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
745 @lib.help("[@<category>] <q>*<a>", "adds a question")
746 def addq(bot
, user
, chan
, realtarget
, *args
):
748 if args
[0].startswith("@"):
749 cat
= args
.pop(0)[1:].lower()
750 questions
= state
.db
['questions'][cat
]
752 questions
= state
.questions
754 line
= ' '.join([str(arg
) for arg
in args
])
755 linepieces
= line
.split('*')
756 if len(linepieces
) < 2:
757 bot
.msg(user
, "Error: need <question>*<answer>")
759 question
= linepieces
[0].strip()
760 answer
= linepieces
[1].strip()
761 questions
.append([question
, answer
])
762 bot
.msg(user
, "Done. Question is #%s" % (len(questions
)-1))
764 @lib.hook(needchan
=False)
765 @lib.help(None, "show current category")
766 def showcat(bot
, user
, chan
, realtarget
, *args
):
767 bot
.msg(user
, "Current category: %s" % (state
.db
['category']))
769 @lib.hook(glevel
=1, needchan
=False)
770 @lib.help("<category>", "change category")
771 def setcat(bot
, user
, chan
, realtarget
, *args
):
772 category
= args
[0].lower()
773 if category
in state
.db
['questions']:
774 state
.db
['category'] = category
775 state
.questions
= state
.db
['questions'][category
]
776 bot
.msg(user
, "Changed category to %s" % (category
))
778 bot
.msg(user
, "That category doesn't exist.")
780 @lib.hook(needchan
=False)
781 @lib.help(None, "list categories", "the current category will be marked with a *")
782 def listcats(bot
, user
, chan
, realtarget
, *args
):
783 cats
= ["%s%s (%d)" % ("*" if c
== state
.db
['category'] else "", c
, len(state
.db
['questions'][c
])) for c
in state
.db
['questions'].keys()]
784 bot
.msg(user
, "Categories: %s" % (', '.join(cats
)))
786 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
787 @lib.help("<category>", "adds an empty category")
788 def addcat(bot
, user
, chan
, realtarget
, *args
):
789 category
= args
[0].lower()
790 if category
not in state
.db
['questions']:
791 state
.db
['questions'][category
] = []
792 bot
.msg(user
, "Added category %s" % (category
))
794 bot
.msg(user
, "Category already exists.")
796 @lib.hook(glevel
=lib
.MANAGER
, needchan
=False)
797 @lib.help("<category>", "deletes an entire category")
798 def delcat(bot
, user
, chan
, realtarget
, *args
):
799 category
= args
[0].lower()
800 if category
== state
.db
['category']:
801 bot
.msg(user
, "Category currently in use!")
802 elif category
in state
.db
['questions']:
803 length
= len(state
.db
['questions'][category
])
804 del state
.db
['questions'][category
]
805 bot
.msg(user
, "Deleted category %s (%d questions)" % (category
, length
))
807 bot
.msg(user
, "Category does not exist.")
809 @lib.hook(needchan
=False)
810 def triviahelp(bot
, user
, chan
, realtarget
, *args
):
811 bot
.slowmsg(user
, "START")
812 bot
.slowmsg(user
, "TOP10")
813 bot
.slowmsg(user
, "POINTS [<user>]")
814 bot
.slowmsg(user
, "RANK [<user>]")
815 bot
.slowmsg(user
, "BADQ <reason> (include info to identify question)")
817 bot
.slowmsg(user
, "SKIP (KNOWN)")
818 bot
.slowmsg(user
, "STOP (KNOWN)")
819 bot
.slowmsg(user
, "FINDQ <full question> (KNOWN)")
820 bot
.slowmsg(user
, "FINDQRE <regex> (KNOWN)")
821 bot
.slowmsg(user
, "SETNEXTID <qid> (KNOWN)")
822 if user
.glevel
>= lib
.STAFF
:
823 bot
.slowmsg(user
, "GIVE <user> [<points>] (STAFF)")
824 bot
.slowmsg(user
, "SETNEXT <q>*<a> (STAFF)")
825 bot
.slowmsg(user
, "ADDQ <q>*<a> (STAFF)")
826 bot
.slowmsg(user
, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
827 bot
.slowmsg(user
, "SHOWQ <qid> (STAFF)")
828 bot
.slowmsg(user
, "BADQS (STAFF)")
829 bot
.slowmsg(user
, "CLEARBADQS (STAFF)")
830 bot
.slowmsg(user
, "DELBADQ <reportid> (STAFF)")
831 if user
.glevel
>= lib
.ADMIN
:
832 bot
.slowmsg(user
, "SETTARGET <points> (ADMIN)")
833 bot
.slowmsg(user
, "MAXMISSED <questions> (ADMIN)")
834 bot
.slowmsg(user
, "HINTTIMER <float seconds> (ADMIN)")
835 bot
.slowmsg(user
, "HINTNUM <hints> (ADMIN)")
836 bot
.slowmsg(user
, "QUESTIONPAUSE <float seconds> (ADMIN)")
839 def num_417(bot
, textline
):
840 # bot.fastmsg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
841 state
.nextquestion(qskipped
=False, skipwait
=True)
844 def num_TOPIC(bot
, textline
):
845 pieces
= textline
.split(None, 4)
847 if chan
!= state
.db
['chan']:
849 gottopic
= pieces
[4][1:]
851 formatted
= state
.db
['topicformat'] % {
852 'chan': state
.db
['chan'],
853 'top1': "%s (%s)" % (person(0), pts(0)),
855 "%s (%s)" % (person(x
), pts(x
))
856 for x
in range(3) if x
< len(state
.db
['ranks'])
859 "%s (%s) %s" % (person(x
), country(x
), pts(x
))
860 for x
in range(3) if x
< len(state
.db
['ranks'])
863 "%s (%s)" % (person(x
), pts(x
))
864 for x
in range(10) if x
< len(state
.db
['ranks'])
867 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
868 for x
in range(10) if x
< len(state
.db
['ranks'])
870 'lastwinner': state
.db
['lastwinner'],
871 'lastwon': time
.strftime("%b %d", time
.gmtime(state
.db
['lastwon'])),
872 'target': state
.db
['target'],
873 'category': state
.db
['category'],
875 if gottopic
!= formatted
:
876 state
.getbot().conn
.send("TOPIC %s :%s" % (state
.db
['chan'], formatted
))
879 def specialQuestion(oldq
):
880 newq
= [oldq
[0], oldq
[1]]
881 qtype
= oldq
[0].upper()
883 if qtype
== "!MONTH":
884 newq
[0] = "What month is it currently (in UTC)?"
885 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
886 elif qtype
== "!MATH+":
887 randnum1
= random
.randrange(0, 11)
888 randnum2
= random
.randrange(0, 11)
889 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
890 newq
[1] = spellout(randnum1
+randnum2
)
891 else: pass #default to not modifying
896 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
897 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
898 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"