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
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
.chan
= self
.db
['chan']
77 self
.nextquestiontimer
= None
80 self
.hintanswer
= None
82 self
.revealpossibilities
= None
84 self
.missedquestions
= 0
88 if 'lastwon' not in self
.db
or self
.db
['lastwon'] is None:
89 self
.db
['lastwon'] = time
.time()
92 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']])))
93 self
.getchan().msg("You have %s seconds." % (self
.db
['votetimer']))
94 self
.voteamounts
= dict([(x
, 0) for x
in self
.db
['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
95 self
.pointvote
= MyTimer(self
.db
['votetimer'], self
.endPointVote
)
96 self
.pointvote
.start()
103 if threading
is not None and threading
._Timer
is not None:
104 if isinstance(self
.steptimer
, threading
._Timer
):
105 self
.steptimer
.cancel()
106 if isinstance(self
.nextquestiontimer
, threading
._Timer
):
107 self
.nextquestiontimer
.cancel()
108 self
.nextquestiontimer
= None
112 if json
is not None and json
.dump
is not None:
113 json
.dump(self
.db
, open(self
.questionfile
, "w"))#, indent=4, separators=(',', ': '))
116 return self
.parent
.channel(self
.chan
)
118 return self
.getchan().bot
120 def nexthint(self
, hintnum
):
121 answer
= self
.hintanswer
123 if self
.hintstr
is None or self
.revealpossibilities
is None or self
.reveal
is None:
125 self
.hintstr
= list(re
.sub(r
'[a-zA-Z0-9]', '*', answer
))
126 self
.revealpossibilities
= range(''.join(self
.hintstr
).count('*'))
127 self
.reveal
= int(round(''.join(self
.hintstr
).count('*') * (7/24.0)))
129 oldhintstr
= ''.join(self
.hintstr
)
131 for i
in range(self
.reveal
):
132 revealcount
= random
.choice(self
.revealpossibilities
)
133 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
134 self
.revealpossibilities
.remove(revealcount
)
135 self
.hintstr
[revealloc
] = answer
[revealloc
]
136 if oldhintstr
!= ''.join(self
.hintstr
): self
.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
140 if hintnum
< self
.db
['hintnum']:
141 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
142 self
.steptimer
.start()
144 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
145 self
.steptimer
.start()
147 def doGameOver(self
):
148 msg
= self
.getchan().msg
151 msg("\00312THE GAME IS OVER!!!")
152 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
153 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
154 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
155 [msg("%dth place: %s (%s)" % (i
+1, person(i
, True), pts(i
))) for i
in range(3,10)]
156 except IndexError: pass
157 except Exception as e
:
158 msg("DERP! %r" % (e
))
160 self
.db
['lastwinner'] = winner
161 self
.db
['lastwon'] = time
.time()
163 if self
.db
['hofpath'] is not None and self
.db
['hofpath'] != '':
166 self
.db
['users'] = {}
167 self
.db
['ranks'] = []
172 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
173 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
174 self
.getbot().parent
.cfg
.get('trivia', 'con'),
175 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
176 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
177 except: pass #don't care if errors happen updating twitter.
179 self
.__init
__(self
.parent
, True)
183 try: return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
184 except: return "none"
186 try: return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
191 f
= open(self
.db
['hofpath'], 'rb+')
192 for i
in range(self
.db
['hoflines']): #skip this many lines
197 f
.write((self
.db
['hofformat']+"\n") % {
198 'date': time
.strftime("%F", time
.gmtime()),
199 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['lastwon'])),
200 'targetscore': self
.db
['target'],
201 'firstperson': person(0),
202 'firstscore': pts(0),
203 'secondperson': person(1),
204 'secondscore': pts(1),
205 'thirdperson': person(2),
206 'thirdscore': pts(2),
210 except Exception as e
:
216 def endPointVote(self
):
217 self
.getchan().msg("Voting has ended!")
218 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
219 for i
in range(len(votelist
)-1):
221 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
222 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
224 self
.db
['target'] = votelist
[-1][0]
225 self
.pointvote
= None
227 self
.nextquestion() #start the game!
229 def nextquestion(self
, qskipped
=False, iteration
=0, skipwait
=False):
230 self
.lastqid
= self
.curqid
233 if self
.gameover
== True:
234 return self
.doGameOver()
236 self
.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
237 self
.missedquestions
+= 1
239 self
.missedquestions
= 0
240 if 'topicformat' in self
.db
and self
.db
['topicformat'] is not None:
241 self
.getbot().conn
.send("TOPIC %s" % (self
.db
['chan']))
243 if isinstance(self
.steptimer
, threading
._Timer
):
244 self
.steptimer
.cancel()
245 if isinstance(self
.nextquestiontimer
, threading
._Timer
):
246 self
.nextquestiontimer
.cancel()
247 self
.nextquestiontimer
= None
251 self
.revealpossibilities
= None
254 if self
.missedquestions
> self
.db
['maxmissedquestions']:
256 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game." % (self
.missedquestions
))
260 self
._nextquestion
(iteration
)
262 self
.nextquestiontimer
= MyTimer(self
.db
['questionpause'], self
._nextquestion
, args
=[iteration
])
263 self
.nextquestiontimer
.start()
265 def _nextquestion(self
, iteration
):
266 if self
.nextq
is not None:
271 nextqid
= random
.randrange(0, len(self
.db
['questions']))
272 nextq
= self
.db
['questions'][nextqid
]
274 if nextq
[0][0] == "!":
276 nextq
= specialQuestion(nextq
)
278 if len(nextq
) > 2 and nextq
[2] - time
.time() < 7*24*60*60 and iteration
< 10:
279 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
281 nextq
[2] = time
.time()
283 nextq
.append(time
.time())
285 if isinstance(nextq
[1], basestring
):
286 nextq
[1] = nextq
[1].lower()
288 nextq
[1] = [s
.lower() for s
in nextq
[1]]
290 qtext
= "\00312,01Next up: "
291 qtext
+= "(%5d)" % (random
.randint(0,99999))
292 qary
= nextq
[0].split(None)
295 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(random
.randrange(0x61,0x7A)) #a-z
296 self
.getbot().fastmsg(self
.chan
, qtext
)
299 self
.curqid
= nextqid
301 if isinstance(self
.curq
[1], basestring
): self
.hintanswer
= self
.curq
[1]
302 else: self
.hintanswer
= random
.choice(self
.curq
[1])
304 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
305 self
.steptimer
.start()
307 def checkanswer(self
, answer
):
308 if self
.curq
is None:
310 elif isinstance(self
.curq
[1], basestring
):
311 return answer
.lower() == self
.curq
[1]
312 else: # assume it's a list or something.
313 return answer
.lower() in self
.curq
[1]
315 def addpoint(self
, user_obj
, count
=1):
316 user_nick
= str(user_obj
)
317 user
= user_nick
.lower() # save this separately as we use both
318 if user
in self
.db
['users']:
319 self
.db
['users'][user
]['points'] += count
321 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
322 self
.db
['ranks'].append(user
)
324 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
325 for i
in range(0, len(self
.db
['ranks'])):
326 nick
= self
.db
['ranks'][i
]
327 self
.db
['users'][nick
]['rank'] = i
329 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
332 return self
.db
['users'][user
]['points']
334 def points(self
, user
):
335 user
= str(user
).lower()
336 if user
in self
.db
['users']:
337 return self
.db
['users'][user
]['points']
341 def rank(self
, user
):
342 user
= str(user
).lower()
343 if user
in self
.db
['users']:
344 return self
.db
['users'][user
]['rank']+1
346 return len(self
.db
['users'])+1
348 def targetuser(self
, user
):
349 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
351 user
= str(user
).lower()
352 if user
in self
.db
['users']:
353 rank
= self
.db
['users'][user
]['rank']
355 return "you're in the lead!"
357 return self
.db
['ranks'][rank
-1]
359 return self
.db
['ranks'][-1]
360 def targetpoints(self
, user
):
361 if len(self
.db
['ranks']) == 0: return 0
363 user
= str(user
).lower()
364 if user
in self
.db
['users']:
365 rank
= self
.db
['users'][user
]['rank']
369 return self
.db
['users'][self
.db
['ranks'][rank
-1]]['points']
371 return self
.db
['users'][self
.db
['ranks'][-1]]['points']
373 state
= TriviaState()
375 # we have to hook this in modstart, since we don't know the channel until then.
376 def trivia_checkanswer(bot
, user
, chan
, *args
):
377 line
= ' '.join([str(arg
) for arg
in args
])
378 if state
.checkanswer(line
):
380 if state
.hintanswer
.lower() == line
.lower():
381 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
)))
383 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
)))
384 if state
.hintsgiven
== 0:
385 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
388 @lib.hook(needchan
=False)
389 @lib.help("[<user>]", "shows how many points you or someone has")
390 def points(bot
, user
, chan
, realtarget
, *args
):
391 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
394 if len(args
) != 0: who
= args
[0]
397 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
399 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
400 @lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
402 def give(bot
, user
, chan
, realtarget
, *args
):
405 numpoints
= int(args
[1])
408 balance
= state
.addpoint(whoto
, numpoints
)
410 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
412 @lib.hook(glevel
=1, needchan
=False)
413 @lib.help("<qid>", "sets next question to one in the database")
415 def setnextid(bot
, user
, chan
, realtarget
, *args
):
418 state
.nextq
= state
.db
['questions'][qid
]
419 if user
.glevel
>= lib
.STAFF
:
420 respstr
= "Done. Next question is: %s" % (state
.nextq
[0])
423 bot
.msg(user
, respstr
)
424 except Exception as e
:
425 bot
.msg(user
, "Error: %s" % (e
))
427 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
428 @lib.help("<q>*<a>", "sets next question to one not in database")
430 def setnext(bot
, user
, chan
, realtarget
, *args
):
431 line
= ' '.join([str(arg
) for arg
in args
])
432 linepieces
= line
.split('*')
433 if len(linepieces
) < 2:
434 bot
.msg(user
, "Error: need <question>*<answer>")
436 question
= linepieces
[0].strip()
437 answer
= linepieces
[1].strip()
438 state
.nextq
= [question
, answer
]
439 bot
.msg(user
, "Done.")
441 @lib.hook(glevel
=1, needchan
=False)
442 @lib.help(None, "skips to next question")
443 def skip(bot
, user
, chan
, realtarget
, *args
):
444 state
.nextquestion(qskipped
=True, skipwait
=True)
446 @lib.hook(needchan
=False)
447 @lib.help(None, "starts the trivia game")
448 def start(bot
, user
, chan
, realtarget
, *args
):
449 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
452 if chan
is not None and chan
.name
!= state
.db
['chan']:
453 bot
.msg(replyto
, "That command isn't valid here.")
456 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
457 bot
.msg(state
.db
['chan'], "%s has started the game!" % (user
))
458 state
.nextquestion(skipwait
=True)
459 elif state
.pointvote
is not None:
460 bot
.msg(user
, "There's a vote in progress!")
462 bot
.msg(user
, "Game is already started!")
464 @lib.hook('stop', glevel
=1, needchan
=False)
465 @lib.help(None, "stops the trivia game")
466 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
468 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
470 bot
.msg(user
, "Game isn't running.")
476 state
.steptimer
.cancel()
477 except Exception as e
:
478 print "!!! steptimer.cancel(): %s %r" % (e
,e
)
479 state
.steptimer
= None
481 state
.nextquestiontimer
.cancel()
482 except Exception as e
:
483 print "!!! nextquestiontimer.cancel(): %s %r" % (e
,e
)
484 state
.nextquestiontimer
= None
487 @lib.hook(needchan
=False)
488 @lib.help("<reason>", "reports a bad question to the admins")
490 def badq(bot
, user
, chan
, realtarget
, *args
):
491 lastqid
= state
.lastqid
492 curqid
= state
.curqid
494 reason
= ' '.join(args
)
495 state
.db
['badqs'].append([lastqid
, curqid
, reason
])
497 bot
.msg(user
, "Reported bad question.")
499 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
500 @lib.help(None, "shows a list of BADQ reports")
501 def badqs(bot
, user
, chan
, realtarget
, *args
):
502 if len(state
.db
['badqs']) == 0:
503 bot
.msg(user
, "No reports.")
505 for i
in range(len(state
.db
['badqs'])):
507 report
= state
.db
['badqs'][i
]
508 bot
.msg(user
, "Report #%d: LastQ=%r CurQ=%r: %s" % (i
, report
[0], report
[1], report
[2]))
509 try: lq
= state
.db
['questions'][int(report
[0])]
510 except Exception as e
: lq
= (None,None)
511 try: cq
= state
.db
['questions'][int(report
[1])]
512 except Exception as e
: cq
= (None, None)
513 bot
.msg(user
, "- Last: %s*%s" % (lq
[0], lq
[1]))
514 bot
.msg(user
, "- Curr: %s*%s" % (cq
[0], cq
[1]))
515 except Exception as e
:
516 bot
.msg(user
, "- Exception: %r" % (e
))
518 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
519 @lib.hook(None, "clears list of BADQ reports")
520 def clearbadqs(bot
, user
, chan
, realtarget
, *args
):
521 state
.db
['badqs'] = []
523 bot
.msg(user
, "Cleared reports.")
525 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
526 @lib.hook("<badqid>", "removes a BADQ report")
528 def delbadq(bot
, user
, chan
, realtarget
, *args
):
531 del state
.db
['badqs'][qid
]
533 bot
.msg(user
, "Removed report #%d" % (qid
))
535 bot
.msg(user
, "Failed!")
537 @lib.hook(needchan
=False)
538 @lib.help("[<user>]", "shows you or someone else's rank")
539 def rank(bot
, user
, chan
, realtarget
, *args
):
540 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
543 if len(args
) != 0: who
= args
[0]
546 bot
.msg(replyto
, "%s is in %d place (%s points). Target is: %s (%s points)." % (who
, state
.rank(who
), state
.points(who
), state
.targetuser(who
), state
.targetpoints(who
)))
548 @lib.hook(needchan
=False)
549 @lib.help(None, "shows top10 list")
550 def top10(bot
, user
, chan
, realtarget
, *args
):
551 if len(state
.db
['ranks']) == 0:
552 return bot
.msg(state
.db
['chan'], "No one is ranked!")
554 max = len(state
.db
['ranks'])
557 replylist
= ', '.join(["%s (%s) %s" % (person(x
), country(x
), pts(x
)) for x
in range(max)])
558 bot
.msg(state
.db
['chan'], "Top 10: %s" % (replylist
))
560 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
561 @lib.help("<target score>", "changes the target score for this round")
562 def settarget(bot
, user
, chan
, realtarget
, *args
):
564 state
.db
['target'] = int(args
[0])
565 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
567 if state
.pointvote
is not None:
568 state
.pointvote
.cancel()
569 state
.pointvote
= None
570 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
571 except Exception as e
:
573 bot
.msg(user
, "Failed to set target.")
575 @lib.hook(needchan
=False)
576 @lib.help("<option>", "votes for a trarget score for next round")
577 def vote(bot
, user
, chan
, realtarget
, *args
):
578 if state
.pointvote
is not None:
579 if int(args
[0]) in state
.voteamounts
:
580 state
.voteamounts
[int(args
[0])] += 1
581 bot
.msg(user
, "Your vote has been recorded.")
583 bot
.msg(user
, "Sorry - that's not an option!")
585 bot
.msg(user
, "There's no vote in progress.")
587 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
588 @lib.help("<number>", "sets the max missed question before game stops")
589 def maxmissed(bot
, user
, chan
, realtarget
, *args
):
591 state
.db
['maxmissedquestions'] = int(args
[0])
592 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
594 bot
.msg(user
, "Failed to set maxmissed.")
596 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
597 @lib.help("<seconds>", "sets the time between hints")
598 def hinttimer(bot
, user
, chan
, realtarget
, *args
):
600 state
.db
['hinttimer'] = float(args
[0])
601 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
603 bot
.msg(user
, "Failed to set hint timer.")
605 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
606 @lib.help("<number>", "sets the number of hints given")
607 def hintnum(bot
, user
, chan
, realtarget
, *args
):
609 state
.db
['hintnum'] = int(args
[0])
610 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
612 bot
.msg(user
, "Failed to set hintnum.")
614 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
615 @lib.help("<seconds>", "sets the pause between questions")
616 def questionpause(bot
, user
, chan
, realtarget
, *args
):
618 state
.db
['questionpause'] = float(args
[0])
619 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
621 bot
.msg(user
, "Failed to set questionpause.")
623 @lib.hook(glevel
=1, needchan
=False)
624 @lib.help("<full question>", "finds a qid given a complete question")
625 def findq(bot
, user
, chan
, realtarget
, *args
):
627 bot
.msg(user
, "You need to specify the question.")
630 searchkey
= ' '.join(args
).lower()
631 matches
= [str(i
) for i
in range(len(state
.db
['questions'])) if state
.db
['questions'][i
][0].lower() == searchkey
]
633 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
634 elif len(matches
) == 1:
635 bot
.msg(user
, "One match: %s" % (matches
[0]))
637 bot
.msg(user
, "No match.")
639 @lib.hook(glevel
=1, needchan
=False)
640 @lib.help("<regex>", "finds a qid given a regex or partial question")
641 def findqre(bot
, user
, chan
, realtarget
, *args
):
643 bot
.msg(user
, "You need to specify a search string.")
646 searcher
= re
.compile(' '.join(args
), re
.IGNORECASE
)
647 matches
= [str(i
) for i
in range(len(state
.db
['questions'])) if searcher
.search(state
.db
['questions'][i
][0]) is not None]
648 if len(matches
) > 25:
649 bot
.msg(user
, "Too many matches! (>25)")
650 elif len(matches
) > 1:
651 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
652 elif len(matches
) == 1:
653 bot
.msg(user
, "One match: %s" % (matches
[0]))
655 bot
.msg(user
, "No match.")
657 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
658 @lib.help("<qid>", "displays the q*a for a qid")
659 def showq(bot
, user
, chan
, realtarget
, *args
):
663 bot
.msg(user
, "Specify a numeric question ID.")
666 q
= state
.db
['questions'][qid
]
668 bot
.msg(user
, "ID not valid.")
670 bot
.msg(user
, "%s: %s*%s" % (qid
, q
[0], q
[1]))
672 @lib.hook(('delq', 'deleteq'), glevel
=lib
.STAFF
, needchan
=False)
673 @lib.help("<qid>", "removes a question from the database")
674 def delq(bot
, user
, chan
, realtarget
, *args
):
676 backup
= state
.db
['questions'][int(args
[0])]
677 del state
.db
['questions'][int(args
[0])]
679 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]))
681 bot
.msg(user
, "Couldn't delete that question. %r" % (e
))
683 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
684 @lib.help("<q>*<a>", "adds a question")
685 def addq(bot
, user
, chan
, realtarget
, *args
):
686 line
= ' '.join([str(arg
) for arg
in args
])
687 linepieces
= line
.split('*')
688 if len(linepieces
) < 2:
689 bot
.msg(user
, "Error: need <question>*<answer>")
691 question
= linepieces
[0].strip()
692 answer
= linepieces
[1].strip()
693 state
.db
['questions'].append([question
, answer
])
695 bot
.msg(user
, "Done. Question is #%s" % (len(state
.db
['questions'])-1))
698 @lib.hook(needchan
=False)
699 def triviahelp(bot
, user
, chan
, realtarget
, *args
):
700 bot
.slowmsg(user
, "START")
701 bot
.slowmsg(user
, "TOP10")
702 bot
.slowmsg(user
, "POINTS [<user>]")
703 bot
.slowmsg(user
, "RANK [<user>]")
704 bot
.slowmsg(user
, "BADQ <reason> (include info to identify question)")
706 bot
.slowmsg(user
, "SKIP (KNOWN)")
707 bot
.slowmsg(user
, "STOP (KNOWN)")
708 bot
.slowmsg(user
, "FINDQ <full question> (KNOWN)")
709 bot
.slowmsg(user
, "FINDQRE <regex> (KNOWN)")
710 bot
.slowmsg(user
, "SETNEXTID <qid> (KNOWN)")
711 if user
.glevel
>= lib
.STAFF
:
712 bot
.slowmsg(user
, "GIVE <user> [<points>] (STAFF)")
713 bot
.slowmsg(user
, "SETNEXT <q>*<a> (STAFF)")
714 bot
.slowmsg(user
, "ADDQ <q>*<a> (STAFF)")
715 bot
.slowmsg(user
, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
716 bot
.slowmsg(user
, "SHOWQ <qid> (STAFF)")
717 bot
.slowmsg(user
, "BADQS (STAFF)")
718 bot
.slowmsg(user
, "CLEARBADQS (STAFF)")
719 bot
.slowmsg(user
, "DELBADQ <reportid> (STAFF)")
720 if user
.glevel
>= lib
.ADMIN
:
721 bot
.slowmsg(user
, "SETTARGET <points> (ADMIN)")
722 bot
.slowmsg(user
, "MAXMISSED <questions> (ADMIN)")
723 bot
.slowmsg(user
, "HINTTIMER <float seconds> (ADMIN)")
724 bot
.slowmsg(user
, "HINTNUM <hints> (ADMIN)")
725 bot
.slowmsg(user
, "QUESTIONPAUSE <float seconds> (ADMIN)")
728 def num_417(bot
, textline
):
729 # bot.fastmsg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
730 state
.nextquestion(qskipped
=False, skipwait
=True)
733 def num_TOPIC(bot
, textline
):
734 pieces
= textline
.split(None, 4)
736 if chan
!= state
.db
['chan']:
738 gottopic
= pieces
[4][1:]
740 formatted
= state
.db
['topicformat'] % {
741 'chan': state
.db
['chan'],
742 'top1': "%s (%s)" % (person(0), pts(0)),
744 "%s (%s)" % (person(x
), pts(x
))
745 for x
in range(3) if x
< len(state
.db
['ranks'])
748 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
749 for x
in range(3) if x
< len(state
.db
['ranks'])
752 "%s (%s)" % (person(x
), pts(x
))
753 for x
in range(10) if x
< len(state
.db
['ranks'])
756 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
757 for x
in range(10) if x
< len(state
.db
['ranks'])
759 'lastwinner': state
.db
['lastwinner'],
760 'lastwon': time
.strftime("%b %d", time
.gmtime(state
.db
['lastwon'])),
761 'target': state
.db
['target'],
763 if gottopic
!= formatted
:
764 state
.getbot().conn
.send("TOPIC %s :%s" % (state
.db
['chan'], formatted
))
767 def specialQuestion(oldq
):
768 newq
= [oldq
[0], oldq
[1]]
769 qtype
= oldq
[0].upper()
771 if qtype
== "!MONTH":
772 newq
[0] = "What month is it currently (in UTC)?"
773 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
774 elif qtype
== "!MATH+":
775 randnum1
= random
.randrange(0, 11)
776 randnum2
= random
.randrange(0, 11)
777 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
778 newq
[1] = spellout(randnum1
+randnum2
)
783 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
784 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
785 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"