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
.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
111 def savedb(self
): #returns whether or not it was able to save
112 if json
is not None and json
.dump
is not None:
113 # json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
114 dbjson
= json
.dumps(self
.db
)
116 os
.rename(self
.questionfile
, self
.questionfile
+".auto.bak")
117 tmpfn
= os
.tempnam('.', 'trivia')
122 os
.rename(tmpfn
, self
.questionfile
)
124 except: #if something happens, restore the backup
125 os
.rename(self
.questionfile
+".auto.bak", self
.questionfile
)
128 except OSError: # temp file is already gone
130 raise #TODO: we may be better off just swallowing exceptions?
134 return self
.parent
.channel(self
.chan
)
136 return self
.getchan().bot
138 def nexthint(self
, hintnum
):
139 answer
= self
.hintanswer
141 if self
.hintstr
is None or self
.revealpossibilities
is None or self
.reveal
is None:
143 self
.hintstr
= list(re
.sub(r
'[a-zA-Z0-9]', '*', answer
))
144 self
.revealpossibilities
= range(''.join(self
.hintstr
).count('*'))
145 self
.reveal
= int(round(''.join(self
.hintstr
).count('*') * (7/24.0)))
147 oldhintstr
= ''.join(self
.hintstr
)
149 for i
in range(self
.reveal
):
150 revealcount
= random
.choice(self
.revealpossibilities
)
151 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
152 self
.revealpossibilities
.remove(revealcount
)
153 self
.hintstr
[revealloc
] = answer
[revealloc
]
154 if oldhintstr
!= ''.join(self
.hintstr
): self
.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
158 if hintnum
< self
.db
['hintnum']:
159 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
160 self
.steptimer
.start()
162 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
163 self
.steptimer
.start()
165 def doGameOver(self
):
166 msg
= self
.getchan().msg
169 msg("\00312THE GAME IS OVER!!!")
170 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
171 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
172 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
173 [msg("%dth place: %s (%s)" % (i
+1, person(i
, True), pts(i
))) for i
in range(3,10)]
174 except IndexError: pass
175 except Exception as e
:
176 msg("DERP! %r" % (e
))
178 self
.db
['lastwinner'] = winner
179 self
.db
['lastwon'] = time
.time()
181 if self
.db
['hofpath'] is not None and self
.db
['hofpath'] != '':
184 self
.db
['users'] = {}
185 self
.db
['ranks'] = []
190 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
191 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
192 self
.getbot().parent
.cfg
.get('trivia', 'con'),
193 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
194 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
195 except: pass #don't care if errors happen updating twitter.
197 self
.__init
__(self
.parent
, True)
201 try: return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
202 except: return "none"
204 try: return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
209 f
= open(self
.db
['hofpath'], 'rb+')
210 for i
in range(self
.db
['hoflines']): #skip this many lines
215 f
.write((self
.db
['hofformat']+"\n") % {
216 'date': time
.strftime("%F", time
.gmtime()),
217 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['lastwon'])),
218 'targetscore': self
.db
['target'],
219 'firstperson': person(0),
220 'firstscore': pts(0),
221 'secondperson': person(1),
222 'secondscore': pts(1),
223 'thirdperson': person(2),
224 'thirdscore': pts(2),
228 except Exception as e
:
234 def endPointVote(self
):
235 self
.getchan().msg("Voting has ended!")
236 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
237 for i
in range(len(votelist
)-1):
239 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
240 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
242 self
.db
['target'] = votelist
[-1][0]
243 self
.pointvote
= None
245 self
.nextquestion() #start the game!
247 def nextquestion(self
, qskipped
=False, iteration
=0, skipwait
=False):
248 self
.lastqid
= self
.curqid
251 if self
.gameover
== True:
252 return self
.doGameOver()
254 self
.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
255 self
.missedquestions
+= 1
257 self
.missedquestions
= 0
258 if 'topicformat' in self
.db
and self
.db
['topicformat'] is not None:
259 self
.getbot().conn
.send("TOPIC %s" % (self
.db
['chan']))
261 if isinstance(self
.steptimer
, threading
._Timer
):
262 self
.steptimer
.cancel()
263 if isinstance(self
.nextquestiontimer
, threading
._Timer
):
264 self
.nextquestiontimer
.cancel()
265 self
.nextquestiontimer
= None
269 self
.revealpossibilities
= None
272 if self
.missedquestions
> self
.db
['maxmissedquestions']:
274 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game." % (self
.missedquestions
))
280 self
._nextquestion
(iteration
)
282 self
.nextquestiontimer
= MyTimer(self
.db
['questionpause'], self
._nextquestion
, args
=[iteration
])
283 self
.nextquestiontimer
.start()
285 def _nextquestion(self
, iteration
):
286 if self
.nextq
is not None:
291 nextqid
= random
.randrange(0, len(self
.db
['questions']))
292 nextq
= self
.db
['questions'][nextqid
]
294 if nextq
[0][0] == "!":
296 nextq
= specialQuestion(nextq
)
298 if len(nextq
) > 2 and nextq
[2] - time
.time() < 7*24*60*60 and iteration
< 10:
299 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
301 nextq
[2] = time
.time()
303 nextq
.append(time
.time())
305 if isinstance(nextq
[1], basestring
):
306 nextq
[1] = nextq
[1].lower()
308 nextq
[1] = [s
.lower() for s
in nextq
[1]]
310 qtext
= "\00312,01Next up: "
311 qtext
+= "(%5d)" % (random
.randint(0,99999))
312 qary
= nextq
[0].split(None)
315 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(random
.randrange(0x61,0x7A)) #a-z
316 self
.getbot().fastmsg(self
.chan
, qtext
)
319 self
.curqid
= nextqid
321 if isinstance(self
.curq
[1], basestring
): self
.hintanswer
= self
.curq
[1]
322 else: self
.hintanswer
= random
.choice(self
.curq
[1])
324 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
325 self
.steptimer
.start()
327 def checkanswer(self
, answer
):
328 if self
.curq
is None:
330 elif isinstance(self
.curq
[1], basestring
):
331 return answer
.lower() == self
.curq
[1]
332 else: # assume it's a list or something.
333 return answer
.lower() in self
.curq
[1]
335 def addpoint(self
, user_obj
, count
=1):
336 user_nick
= str(user_obj
)
337 user
= user_nick
.lower() # save this separately as we use both
338 if user
in self
.db
['users']:
339 self
.db
['users'][user
]['points'] += count
341 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
342 self
.db
['ranks'].append(user
)
344 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
345 for i
in range(0, len(self
.db
['ranks'])):
346 nick
= self
.db
['ranks'][i
]
347 self
.db
['users'][nick
]['rank'] = i
349 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
352 return self
.db
['users'][user
]['points']
354 def points(self
, user
):
355 user
= str(user
).lower()
356 if user
in self
.db
['users']:
357 return self
.db
['users'][user
]['points']
361 def rank(self
, user
):
362 user
= str(user
).lower()
363 if user
in self
.db
['users']:
364 return self
.db
['users'][user
]['rank']+1
366 return len(self
.db
['users'])+1
368 def targetuser(self
, user
):
369 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
371 user
= str(user
).lower()
372 if user
in self
.db
['users']:
373 rank
= self
.db
['users'][user
]['rank']
375 return "you're in the lead!"
377 return self
.db
['ranks'][rank
-1]
379 return self
.db
['ranks'][-1]
380 def targetpoints(self
, user
):
381 if len(self
.db
['ranks']) == 0: return 0
383 user
= str(user
).lower()
384 if user
in self
.db
['users']:
385 rank
= self
.db
['users'][user
]['rank']
389 return self
.db
['users'][self
.db
['ranks'][rank
-1]]['points']
391 return self
.db
['users'][self
.db
['ranks'][-1]]['points']
393 state
= TriviaState()
395 # we have to hook this in modstart, since we don't know the channel until then.
396 def trivia_checkanswer(bot
, user
, chan
, *args
):
397 line
= ' '.join([str(arg
) for arg
in args
])
398 if state
.checkanswer(line
):
400 if state
.hintanswer
.lower() == line
.lower():
401 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
)))
403 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
)))
404 if state
.hintsgiven
== 0:
405 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
408 @lib.hook(glevel
=1, needchan
=False)
409 @lib.help(None, "saves the trivia database")
410 def save(bot
, user
, chan
, realtarget
, *args
):
411 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
415 bot
.msg(replyto
, "Save successful.")
417 bot
.msg(replyto
, "Save failed!")
419 @lib.hook(needchan
=False)
420 @lib.help("[<user>]", "shows how many points you or someone has")
421 def points(bot
, user
, chan
, realtarget
, *args
):
422 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
425 if len(args
) != 0: who
= args
[0]
428 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
430 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
431 @lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
433 def give(bot
, user
, chan
, realtarget
, *args
):
436 numpoints
= int(args
[1])
439 balance
= state
.addpoint(whoto
, numpoints
)
441 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
443 @lib.hook(glevel
=1, needchan
=False)
444 @lib.help("<qid>", "sets next question to one in the database")
446 def setnextid(bot
, user
, chan
, realtarget
, *args
):
449 state
.nextq
= state
.db
['questions'][qid
]
450 if user
.glevel
>= lib
.STAFF
:
451 respstr
= "Done. Next question is: %s" % (state
.nextq
[0])
454 bot
.msg(user
, respstr
)
455 except Exception as e
:
456 bot
.msg(user
, "Error: %s" % (e
))
458 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
459 @lib.help("<q>*<a>", "sets next question to one not in database")
461 def setnext(bot
, user
, chan
, realtarget
, *args
):
462 line
= ' '.join([str(arg
) for arg
in args
])
463 linepieces
= line
.split('*')
464 if len(linepieces
) < 2:
465 bot
.msg(user
, "Error: need <question>*<answer>")
467 question
= linepieces
[0].strip()
468 answer
= linepieces
[1].strip()
469 state
.nextq
= [question
, answer
]
470 bot
.msg(user
, "Done.")
472 @lib.hook(glevel
=1, needchan
=False)
473 @lib.help(None, "skips to next question")
474 def skip(bot
, user
, chan
, realtarget
, *args
):
475 state
.nextquestion(qskipped
=True, skipwait
=True)
477 @lib.hook(needchan
=False)
478 @lib.help(None, "starts the trivia game")
479 def start(bot
, user
, chan
, realtarget
, *args
):
480 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
483 if chan
is not None and chan
.name
!= state
.db
['chan']:
484 bot
.msg(replyto
, "That command isn't valid here.")
487 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
488 bot
.msg(state
.db
['chan'], "%s has started the game!" % (user
))
489 state
.nextquestion(skipwait
=True)
490 elif state
.pointvote
is not None:
491 bot
.msg(user
, "There's a vote in progress!")
493 bot
.msg(user
, "Game is already started!")
495 @lib.hook('stop', glevel
=1, needchan
=False)
496 @lib.help(None, "stops the trivia game")
497 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
499 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
501 bot
.msg(user
, "Game isn't running.")
507 state
.steptimer
.cancel()
508 except Exception as e
:
509 print "!!! steptimer.cancel(): %s %r" % (e
,e
)
510 state
.steptimer
= None
512 state
.nextquestiontimer
.cancel()
513 except Exception as e
:
514 print "!!! nextquestiontimer.cancel(): %s %r" % (e
,e
)
515 state
.nextquestiontimer
= None
518 @lib.hook(needchan
=False)
519 @lib.help("<reason>", "reports a bad question to the admins")
521 def badq(bot
, user
, chan
, realtarget
, *args
):
522 lastqid
= state
.lastqid
523 curqid
= state
.curqid
525 reason
= ' '.join(args
)
526 state
.db
['badqs'].append([lastqid
, curqid
, reason
])
527 bot
.msg(user
, "Reported bad question.")
529 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
530 @lib.help(None, "shows a list of BADQ reports")
531 def badqs(bot
, user
, chan
, realtarget
, *args
):
532 if len(state
.db
['badqs']) == 0:
533 bot
.msg(user
, "No reports.")
535 for i
in range(len(state
.db
['badqs'])):
537 report
= state
.db
['badqs'][i
]
538 bot
.msg(user
, "Report #%d: LastQ=%r CurQ=%r: %s" % (i
, report
[0], report
[1], report
[2]))
539 try: lq
= state
.db
['questions'][int(report
[0])]
540 except Exception as e
: lq
= (None,None)
541 try: cq
= state
.db
['questions'][int(report
[1])]
542 except Exception as e
: cq
= (None, None)
543 bot
.msg(user
, "- Last: %s*%s" % (lq
[0], lq
[1]))
544 bot
.msg(user
, "- Curr: %s*%s" % (cq
[0], cq
[1]))
545 except Exception as e
:
546 bot
.msg(user
, "- Exception: %r" % (e
))
548 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
549 @lib.hook(None, "clears list of BADQ reports")
550 def clearbadqs(bot
, user
, chan
, realtarget
, *args
):
551 state
.db
['badqs'] = []
552 bot
.msg(user
, "Cleared reports.")
554 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
555 @lib.hook("<badqid>", "removes a BADQ report")
557 def delbadq(bot
, user
, chan
, realtarget
, *args
):
560 del state
.db
['badqs'][qid
]
561 bot
.msg(user
, "Removed report #%d" % (qid
))
563 bot
.msg(user
, "Failed!")
565 @lib.hook(needchan
=False)
566 @lib.help("[<user>]", "shows you or someone else's rank")
567 def rank(bot
, user
, chan
, realtarget
, *args
):
568 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
571 if len(args
) != 0: who
= args
[0]
574 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
)))
576 @lib.hook(needchan
=False)
577 @lib.help(None, "shows top10 list")
578 def top10(bot
, user
, chan
, realtarget
, *args
):
579 if len(state
.db
['ranks']) == 0:
580 return bot
.msg(state
.db
['chan'], "No one is ranked!")
582 max = len(state
.db
['ranks'])
585 replylist
= ', '.join(["%s (%s) %s" % (person(x
), country(x
), pts(x
)) for x
in range(max)])
586 bot
.msg(state
.db
['chan'], "Top 10: %s" % (replylist
))
588 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
589 @lib.help("<target score>", "changes the target score for this round")
590 def settarget(bot
, user
, chan
, realtarget
, *args
):
592 state
.db
['target'] = int(args
[0])
593 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
595 if state
.pointvote
is not None:
596 state
.pointvote
.cancel()
597 state
.pointvote
= None
598 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
599 except Exception as e
:
601 bot
.msg(user
, "Failed to set target.")
603 @lib.hook(needchan
=False)
604 @lib.help("<option>", "votes for a trarget score for next round")
605 def vote(bot
, user
, chan
, realtarget
, *args
):
606 if state
.pointvote
is not None:
607 if int(args
[0]) in state
.voteamounts
:
608 state
.voteamounts
[int(args
[0])] += 1
609 bot
.msg(user
, "Your vote has been recorded.")
611 bot
.msg(user
, "Sorry - that's not an option!")
613 bot
.msg(user
, "There's no vote in progress.")
615 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
616 @lib.help("<number>", "sets the max missed question before game stops")
617 def maxmissed(bot
, user
, chan
, realtarget
, *args
):
619 state
.db
['maxmissedquestions'] = int(args
[0])
620 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
622 bot
.msg(user
, "Failed to set maxmissed.")
624 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
625 @lib.help("<seconds>", "sets the time between hints")
626 def hinttimer(bot
, user
, chan
, realtarget
, *args
):
628 state
.db
['hinttimer'] = float(args
[0])
629 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
631 bot
.msg(user
, "Failed to set hint timer.")
633 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
634 @lib.help("<number>", "sets the number of hints given")
635 def hintnum(bot
, user
, chan
, realtarget
, *args
):
637 state
.db
['hintnum'] = int(args
[0])
638 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
640 bot
.msg(user
, "Failed to set hintnum.")
642 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
643 @lib.help("<seconds>", "sets the pause between questions")
644 def questionpause(bot
, user
, chan
, realtarget
, *args
):
646 state
.db
['questionpause'] = float(args
[0])
647 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
649 bot
.msg(user
, "Failed to set questionpause.")
651 @lib.hook(glevel
=1, needchan
=False)
652 @lib.help("<full question>", "finds a qid given a complete question")
653 def findq(bot
, user
, chan
, realtarget
, *args
):
655 bot
.msg(user
, "You need to specify the question.")
658 searchkey
= ' '.join(args
).lower()
659 matches
= [str(i
) for i
in range(len(state
.db
['questions'])) if state
.db
['questions'][i
][0].lower() == searchkey
]
661 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
662 elif len(matches
) == 1:
663 bot
.msg(user
, "One match: %s" % (matches
[0]))
665 bot
.msg(user
, "No match.")
667 @lib.hook(glevel
=1, needchan
=False)
668 @lib.help("<regex>", "finds a qid given a regex or partial question")
669 def findqre(bot
, user
, chan
, realtarget
, *args
):
671 bot
.msg(user
, "You need to specify a search string.")
674 searcher
= re
.compile(' '.join(args
), re
.IGNORECASE
)
675 matches
= [str(i
) for i
in range(len(state
.db
['questions'])) if searcher
.search(state
.db
['questions'][i
][0]) is not None]
676 if len(matches
) > 25:
677 bot
.msg(user
, "Too many matches! (>25)")
678 elif len(matches
) > 1:
679 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
680 elif len(matches
) == 1:
681 bot
.msg(user
, "One match: %s" % (matches
[0]))
683 bot
.msg(user
, "No match.")
685 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
686 @lib.help("<qid>", "displays the q*a for a qid")
687 def showq(bot
, user
, chan
, realtarget
, *args
):
691 bot
.msg(user
, "Specify a numeric question ID.")
694 q
= state
.db
['questions'][qid
]
696 bot
.msg(user
, "ID not valid.")
698 bot
.msg(user
, "%s: %s*%s" % (qid
, q
[0], q
[1]))
700 @lib.hook(('delq', 'deleteq'), glevel
=lib
.STAFF
, needchan
=False)
701 @lib.help("<qid>", "removes a question from the database")
702 def delq(bot
, user
, chan
, realtarget
, *args
):
704 backup
= state
.db
['questions'][int(args
[0])]
705 del state
.db
['questions'][int(args
[0])]
706 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]))
708 bot
.msg(user
, "Couldn't delete that question. %r" % (e
))
710 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
711 @lib.help("<q>*<a>", "adds a question")
712 def addq(bot
, user
, chan
, realtarget
, *args
):
713 line
= ' '.join([str(arg
) for arg
in args
])
714 linepieces
= line
.split('*')
715 if len(linepieces
) < 2:
716 bot
.msg(user
, "Error: need <question>*<answer>")
718 question
= linepieces
[0].strip()
719 answer
= linepieces
[1].strip()
720 state
.db
['questions'].append([question
, answer
])
721 bot
.msg(user
, "Done. Question is #%s" % (len(state
.db
['questions'])-1))
724 @lib.hook(needchan
=False)
725 def triviahelp(bot
, user
, chan
, realtarget
, *args
):
726 bot
.slowmsg(user
, "START")
727 bot
.slowmsg(user
, "TOP10")
728 bot
.slowmsg(user
, "POINTS [<user>]")
729 bot
.slowmsg(user
, "RANK [<user>]")
730 bot
.slowmsg(user
, "BADQ <reason> (include info to identify question)")
732 bot
.slowmsg(user
, "SKIP (KNOWN)")
733 bot
.slowmsg(user
, "STOP (KNOWN)")
734 bot
.slowmsg(user
, "FINDQ <full question> (KNOWN)")
735 bot
.slowmsg(user
, "FINDQRE <regex> (KNOWN)")
736 bot
.slowmsg(user
, "SETNEXTID <qid> (KNOWN)")
737 if user
.glevel
>= lib
.STAFF
:
738 bot
.slowmsg(user
, "GIVE <user> [<points>] (STAFF)")
739 bot
.slowmsg(user
, "SETNEXT <q>*<a> (STAFF)")
740 bot
.slowmsg(user
, "ADDQ <q>*<a> (STAFF)")
741 bot
.slowmsg(user
, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
742 bot
.slowmsg(user
, "SHOWQ <qid> (STAFF)")
743 bot
.slowmsg(user
, "BADQS (STAFF)")
744 bot
.slowmsg(user
, "CLEARBADQS (STAFF)")
745 bot
.slowmsg(user
, "DELBADQ <reportid> (STAFF)")
746 if user
.glevel
>= lib
.ADMIN
:
747 bot
.slowmsg(user
, "SETTARGET <points> (ADMIN)")
748 bot
.slowmsg(user
, "MAXMISSED <questions> (ADMIN)")
749 bot
.slowmsg(user
, "HINTTIMER <float seconds> (ADMIN)")
750 bot
.slowmsg(user
, "HINTNUM <hints> (ADMIN)")
751 bot
.slowmsg(user
, "QUESTIONPAUSE <float seconds> (ADMIN)")
754 def num_417(bot
, textline
):
755 # bot.fastmsg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
756 state
.nextquestion(qskipped
=False, skipwait
=True)
759 def num_TOPIC(bot
, textline
):
760 pieces
= textline
.split(None, 4)
762 if chan
!= state
.db
['chan']:
764 gottopic
= pieces
[4][1:]
766 formatted
= state
.db
['topicformat'] % {
767 'chan': state
.db
['chan'],
768 'top1': "%s (%s)" % (person(0), pts(0)),
770 "%s (%s)" % (person(x
), pts(x
))
771 for x
in range(3) if x
< len(state
.db
['ranks'])
774 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
775 for x
in range(3) if x
< len(state
.db
['ranks'])
778 "%s (%s)" % (person(x
), pts(x
))
779 for x
in range(10) if x
< len(state
.db
['ranks'])
782 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
783 for x
in range(10) if x
< len(state
.db
['ranks'])
785 'lastwinner': state
.db
['lastwinner'],
786 'lastwon': time
.strftime("%b %d", time
.gmtime(state
.db
['lastwon'])),
787 'target': state
.db
['target'],
789 if gottopic
!= formatted
:
790 state
.getbot().conn
.send("TOPIC %s :%s" % (state
.db
['chan'], formatted
))
793 def specialQuestion(oldq
):
794 newq
= [oldq
[0], oldq
[1]]
795 qtype
= oldq
[0].upper()
797 if qtype
== "!MONTH":
798 newq
[0] = "What month is it currently (in UTC)?"
799 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
800 elif qtype
== "!MATH+":
801 randnum1
= random
.randrange(0, 11)
802 randnum2
= random
.randrange(0, 11)
803 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
804 newq
[1] = spellout(randnum1
+randnum2
)
809 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
810 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
811 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"