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()
104 self
.steptimer
.cancel()
105 self
.steptimer
= None
108 self
.nextquestiontimer
.cancel()
109 self
.nextquestiontimer
= None
111 #TODO remove if the replacement works
112 # if threading is not None and threading._Timer is not None:
113 # if isinstance(self.steptimer, threading._Timer):
114 # self.steptimer.cancel()
115 # if isinstance(self.nextquestiontimer, threading._Timer):
116 # self.nextquestiontimer.cancel()
117 # self.nextquestiontimer = None
120 def savedb(self
): #returns whether or not it was able to save
121 if json
is not None and json
.dump
is not None:
122 # json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
123 dbjson
= json
.dumps(self
.db
)
125 os
.rename(self
.questionfile
, self
.questionfile
+".auto.bak")
126 tmpfn
= os
.tempnam('.', 'trivia')
131 os
.rename(tmpfn
, self
.questionfile
)
133 except: #if something happens, restore the backup
134 os
.rename(self
.questionfile
+".auto.bak", self
.questionfile
)
137 except OSError: # temp file is already gone
139 raise #TODO: we may be better off just swallowing exceptions?
143 return self
.parent
.channel(self
.chan
)
145 return self
.getchan().bot
147 def nexthint(self
, hintnum
):
148 answer
= self
.hintanswer
150 if self
.hintstr
is None or self
.revealpossibilities
is None or self
.reveal
is None:
152 self
.hintstr
= list(re
.sub(r
'[a-zA-Z0-9]', '*', answer
))
153 self
.revealpossibilities
= range(''.join(self
.hintstr
).count('*'))
154 self
.reveal
= int(round(''.join(self
.hintstr
).count('*') * (7/24.0)))
156 oldhintstr
= ''.join(self
.hintstr
)
158 for i
in range(self
.reveal
):
159 revealcount
= random
.choice(self
.revealpossibilities
)
160 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
161 self
.revealpossibilities
.remove(revealcount
)
162 self
.hintstr
[revealloc
] = answer
[revealloc
]
163 if oldhintstr
!= ''.join(self
.hintstr
): self
.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
167 if hintnum
< self
.db
['hintnum']:
168 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
169 self
.steptimer
.start()
171 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
172 self
.steptimer
.start()
174 def doGameOver(self
):
175 msg
= self
.getchan().msg
178 msg("\00312THE GAME IS OVER!!!")
179 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
180 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
181 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
182 [msg("%dth place: %s (%s)" % (i
+1, person(i
, True), pts(i
))) for i
in range(3,10)]
183 except IndexError: pass
184 except Exception as e
:
185 msg("DERP! %r" % (e
))
187 self
.db
['lastwinner'] = winner
188 self
.db
['lastwon'] = time
.time()
190 if self
.db
['hofpath'] is not None and self
.db
['hofpath'] != '':
193 self
.db
['users'] = {}
194 self
.db
['ranks'] = []
199 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
200 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
201 self
.getbot().parent
.cfg
.get('trivia', 'con'),
202 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
203 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
204 except: pass #don't care if errors happen updating twitter.
206 self
.__init
__(self
.parent
, True)
210 try: return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
211 except: return "none"
213 try: return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
218 f
= open(self
.db
['hofpath'], 'rb+')
219 for i
in range(self
.db
['hoflines']): #skip this many lines
224 f
.write((self
.db
['hofformat']+"\n") % {
225 'date': time
.strftime("%F", time
.gmtime()),
226 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['lastwon'])),
227 'targetscore': self
.db
['target'],
228 'firstperson': person(0),
229 'firstscore': pts(0),
230 'secondperson': person(1),
231 'secondscore': pts(1),
232 'thirdperson': person(2),
233 'thirdscore': pts(2),
237 except Exception as e
:
243 def endPointVote(self
):
244 self
.getchan().msg("Voting has ended!")
245 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
246 for i
in range(len(votelist
)-1):
248 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
249 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
251 self
.db
['target'] = votelist
[-1][0]
252 self
.pointvote
= None
254 self
.nextquestion() #start the game!
256 def nextquestion(self
, qskipped
=False, iteration
=0, skipwait
=False):
257 self
.lastqid
= self
.curqid
260 if self
.gameover
== True:
261 return self
.doGameOver()
263 self
.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
264 self
.missedquestions
+= 1
266 self
.missedquestions
= 0
267 if 'topicformat' in self
.db
and self
.db
['topicformat'] is not None:
268 self
.getbot().conn
.send("TOPIC %s" % (self
.db
['chan']))
270 if isinstance(self
.steptimer
, threading
._Timer
):
271 self
.steptimer
.cancel()
272 if isinstance(self
.nextquestiontimer
, threading
._Timer
):
273 self
.nextquestiontimer
.cancel()
274 self
.nextquestiontimer
= None
278 self
.revealpossibilities
= None
283 if self
.missedquestions
> self
.db
['maxmissedquestions']:
285 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game." % (self
.missedquestions
))
289 self
._nextquestion
(iteration
)
291 self
.nextquestiontimer
= MyTimer(self
.db
['questionpause'], self
._nextquestion
, args
=[iteration
])
292 self
.nextquestiontimer
.start()
294 def _nextquestion(self
, iteration
):
295 if self
.nextq
is not None:
300 nextqid
= random
.randrange(0, len(self
.db
['questions']))
301 nextq
= self
.db
['questions'][nextqid
]
303 if nextq
[0][0] == "!":
305 nextq
= specialQuestion(nextq
)
307 if len(nextq
) > 2 and nextq
[2] - time
.time() < 7*24*60*60 and iteration
< 10:
308 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
310 nextq
[2] = time
.time()
312 nextq
.append(time
.time())
314 if isinstance(nextq
[1], basestring
):
315 nextq
[1] = nextq
[1].lower()
317 nextq
[1] = [s
.lower() for s
in nextq
[1]]
319 qtext
= "\00312,01Next up: "
320 qtext
+= "(%5d)" % (random
.randint(0,99999))
321 qary
= nextq
[0].split(None)
324 spacer
= random
.choice(
325 range(0x61,0x7A) + ([0x20]*4)
327 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(spacer
) #a-z
328 self
.getbot().fastmsg(self
.chan
, qtext
)
331 self
.curqid
= nextqid
333 if isinstance(self
.curq
[1], basestring
): self
.hintanswer
= self
.curq
[1]
334 else: self
.hintanswer
= random
.choice(self
.curq
[1])
336 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
337 self
.steptimer
.start()
339 def checkanswer(self
, answer
):
340 if self
.curq
is None:
342 elif isinstance(self
.curq
[1], basestring
):
343 return answer
.lower() == self
.curq
[1]
344 else: # assume it's a list or something.
345 return answer
.lower() in self
.curq
[1]
347 def addpoint(self
, user_obj
, count
=1):
348 user_nick
= str(user_obj
)
349 user
= user_nick
.lower() # save this separately as we use both
350 if user
in self
.db
['users']:
351 self
.db
['users'][user
]['points'] += count
353 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
354 self
.db
['ranks'].append(user
)
356 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
357 for i
in range(0, len(self
.db
['ranks'])):
358 nick
= self
.db
['ranks'][i
]
359 self
.db
['users'][nick
]['rank'] = i
361 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
364 return self
.db
['users'][user
]['points']
366 def points(self
, user
):
367 user
= str(user
).lower()
368 if user
in self
.db
['users']:
369 return self
.db
['users'][user
]['points']
373 def rank(self
, user
):
374 user
= str(user
).lower()
375 if user
in self
.db
['users']:
376 return self
.db
['users'][user
]['rank']+1
378 return len(self
.db
['users'])+1
380 def targetuser(self
, user
):
381 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
383 user
= str(user
).lower()
384 if user
in self
.db
['users']:
385 rank
= self
.db
['users'][user
]['rank']
387 return "you're in the lead!"
389 return self
.db
['ranks'][rank
-1]
391 return self
.db
['ranks'][-1]
392 def targetpoints(self
, user
):
393 if len(self
.db
['ranks']) == 0: return 0
395 user
= str(user
).lower()
396 if user
in self
.db
['users']:
397 rank
= self
.db
['users'][user
]['rank']
401 return "("+str(self
.db
['users'][self
.db
['ranks'][rank
-1]]['points'])+")"
403 return "("+str(self
.db
['users'][self
.db
['ranks'][-1]]['points'])+")"
405 state
= TriviaState()
407 # we have to hook this in modstart, since we don't know the channel until then.
408 def trivia_checkanswer(bot
, user
, chan
, *args
):
409 line
= ' '.join([str(arg
) for arg
in args
])
410 if state
.checkanswer(line
):
412 if state
.hintanswer
.lower() == line
.lower():
413 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
)))
415 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
)))
416 if state
.hintsgiven
== 0:
417 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
420 @lib.hook(glevel
=1, needchan
=False)
421 @lib.help(None, "saves the trivia database")
422 def save(bot
, user
, chan
, realtarget
, *args
):
423 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
427 bot
.msg(replyto
, "Save successful.")
429 bot
.msg(replyto
, "Save failed!")
431 @lib.hook(needchan
=False)
432 @lib.help("[<user>]", "shows how many points you or someone has")
433 def points(bot
, user
, chan
, realtarget
, *args
):
434 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
437 if len(args
) != 0: who
= args
[0]
440 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
442 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
443 @lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
445 def give(bot
, user
, chan
, realtarget
, *args
):
448 numpoints
= int(args
[1])
451 balance
= state
.addpoint(whoto
, numpoints
)
453 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
455 @lib.hook(glevel
=1, needchan
=False)
456 @lib.help("<qid>", "sets next question to one in the database")
458 def setnextid(bot
, user
, chan
, realtarget
, *args
):
461 state
.nextq
= state
.db
['questions'][qid
]
462 if user
.glevel
>= lib
.STAFF
:
463 respstr
= "Done. Next question is: %s" % (state
.nextq
[0])
466 bot
.msg(user
, respstr
)
467 except Exception as e
:
468 bot
.msg(user
, "Error: %s" % (e
))
470 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
471 @lib.help("<q>*<a>", "sets next question to one not in database")
473 def setnext(bot
, user
, chan
, realtarget
, *args
):
474 line
= ' '.join([str(arg
) for arg
in args
])
475 linepieces
= line
.split('*')
476 if len(linepieces
) < 2:
477 bot
.msg(user
, "Error: need <question>*<answer>")
479 question
= linepieces
[0].strip()
480 answer
= linepieces
[1].strip()
481 state
.nextq
= [question
, answer
]
482 bot
.msg(user
, "Done.")
484 @lib.hook(glevel
=1, needchan
=False)
485 @lib.help(None, "skips to next question")
486 def skip(bot
, user
, chan
, realtarget
, *args
):
487 state
.nextquestion(qskipped
=True, skipwait
=True)
489 @lib.hook(needchan
=False)
490 @lib.help(None, "starts the trivia game")
491 def start(bot
, user
, chan
, realtarget
, *args
):
492 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
495 if chan
is not None and chan
.name
!= state
.db
['chan']:
496 bot
.msg(replyto
, "That command isn't valid here.")
499 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
500 bot
.msg(state
.db
['chan'], "%s has started the game!" % (user
))
501 state
.nextquestion(skipwait
=True)
502 elif state
.pointvote
is not None:
503 bot
.msg(user
, "There's a vote in progress!")
505 bot
.msg(user
, "Game is already started!")
507 @lib.hook('stop', glevel
=1, needchan
=False)
508 @lib.help(None, "stops the trivia game")
509 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
511 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
513 bot
.msg(user
, "Game isn't running.")
519 state
.steptimer
.cancel()
520 except Exception as e
:
521 print "!!! steptimer.cancel(): %s %r" % (e
,e
)
522 state
.steptimer
= None
524 state
.nextquestiontimer
.cancel()
525 except Exception as e
:
526 print "!!! nextquestiontimer.cancel(): %s %r" % (e
,e
)
527 state
.nextquestiontimer
= None
530 @lib.hook(needchan
=False)
531 @lib.help("<reason>", "reports a bad question to the admins")
533 def badq(bot
, user
, chan
, realtarget
, *args
):
534 lastqid
= state
.lastqid
535 curqid
= state
.curqid
537 reason
= ' '.join(args
)
538 state
.db
['badqs'].append([lastqid
, curqid
, reason
])
539 bot
.msg(user
, "Reported bad question.")
541 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
542 @lib.help(None, "shows a list of BADQ reports")
543 def badqs(bot
, user
, chan
, realtarget
, *args
):
544 if len(state
.db
['badqs']) == 0:
545 bot
.msg(user
, "No reports.")
547 for i
in range(len(state
.db
['badqs'])):
549 report
= state
.db
['badqs'][i
]
550 bot
.msg(user
, "Report #%d: LastQ=%r CurQ=%r: %s" % (i
, report
[0], report
[1], report
[2]))
551 try: lq
= state
.db
['questions'][int(report
[0])]
552 except Exception as e
: lq
= (None,None)
553 try: cq
= state
.db
['questions'][int(report
[1])]
554 except Exception as e
: cq
= (None, None)
555 bot
.msg(user
, "- Last: %s*%s" % (lq
[0], lq
[1]))
556 bot
.msg(user
, "- Curr: %s*%s" % (cq
[0], cq
[1]))
557 except Exception as e
:
558 bot
.msg(user
, "- Exception: %r" % (e
))
560 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
561 @lib.hook(None, "clears list of BADQ reports")
562 def clearbadqs(bot
, user
, chan
, realtarget
, *args
):
563 state
.db
['badqs'] = []
564 bot
.msg(user
, "Cleared reports.")
566 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
567 @lib.hook("<badqid>", "removes a BADQ report")
569 def delbadq(bot
, user
, chan
, realtarget
, *args
):
572 del state
.db
['badqs'][qid
]
573 bot
.msg(user
, "Removed report #%d" % (qid
))
575 bot
.msg(user
, "Failed!")
577 @lib.hook(needchan
=False)
578 @lib.help("[<user>]", "shows you or someone else's rank")
579 def rank(bot
, user
, chan
, realtarget
, *args
):
580 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
583 if len(args
) != 0: who
= args
[0]
586 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
)))
588 @lib.hook(needchan
=False)
589 @lib.help(None, "shows top10 list")
590 def top10(bot
, user
, chan
, realtarget
, *args
):
591 if len(state
.db
['ranks']) == 0:
592 return bot
.msg(state
.db
['chan'], "No one is ranked!")
594 max = len(state
.db
['ranks'])
597 replylist
= ', '.join(["%s (%s) %s" % (person(x
), country(x
), pts(x
)) for x
in range(max)])
598 bot
.msg(state
.db
['chan'], "Top 10: %s" % (replylist
))
600 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
601 @lib.help("<target score>", "changes the target score for this round")
602 def settarget(bot
, user
, chan
, realtarget
, *args
):
604 state
.db
['target'] = int(args
[0])
605 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
607 if state
.pointvote
is not None:
608 state
.pointvote
.cancel()
609 state
.pointvote
= None
610 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
611 except Exception as e
:
613 bot
.msg(user
, "Failed to set target.")
615 @lib.hook(needchan
=False)
616 @lib.help("<option>", "votes for a trarget score for next round")
617 def vote(bot
, user
, chan
, realtarget
, *args
):
618 if state
.pointvote
is not None:
619 if int(args
[0]) in state
.voteamounts
:
620 state
.voteamounts
[int(args
[0])] += 1
621 bot
.msg(user
, "Your vote has been recorded.")
623 bot
.msg(user
, "Sorry - that's not an option!")
625 bot
.msg(user
, "There's no vote in progress.")
627 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
628 @lib.help("<number>", "sets the max missed question before game stops")
629 def maxmissed(bot
, user
, chan
, realtarget
, *args
):
631 state
.db
['maxmissedquestions'] = int(args
[0])
632 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
634 bot
.msg(user
, "Failed to set maxmissed.")
636 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
637 @lib.help("<seconds>", "sets the time between hints")
638 def hinttimer(bot
, user
, chan
, realtarget
, *args
):
640 state
.db
['hinttimer'] = float(args
[0])
641 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
643 bot
.msg(user
, "Failed to set hint timer.")
645 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
646 @lib.help("<number>", "sets the number of hints given")
647 def hintnum(bot
, user
, chan
, realtarget
, *args
):
649 state
.db
['hintnum'] = int(args
[0])
650 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
652 bot
.msg(user
, "Failed to set hintnum.")
654 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
655 @lib.help("<seconds>", "sets the pause between questions")
656 def questionpause(bot
, user
, chan
, realtarget
, *args
):
658 state
.db
['questionpause'] = float(args
[0])
659 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
661 bot
.msg(user
, "Failed to set questionpause.")
663 @lib.hook(glevel
=1, needchan
=False)
664 @lib.help("<full question>", "finds a qid given a complete question")
665 def findq(bot
, user
, chan
, realtarget
, *args
):
667 bot
.msg(user
, "You need to specify the question.")
670 searchkey
= ' '.join(args
).lower()
671 matches
= [str(i
) for i
in range(len(state
.db
['questions'])) if state
.db
['questions'][i
][0].lower() == searchkey
]
673 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
674 elif len(matches
) == 1:
675 bot
.msg(user
, "One match: %s" % (matches
[0]))
677 bot
.msg(user
, "No match.")
679 @lib.hook(glevel
=1, needchan
=False)
680 @lib.help("<regex>", "finds a qid given a regex or partial question")
681 def findqre(bot
, user
, chan
, realtarget
, *args
):
683 bot
.msg(user
, "You need to specify a search string.")
686 searcher
= re
.compile(' '.join(args
), re
.IGNORECASE
)
687 matches
= [str(i
) for i
in range(len(state
.db
['questions'])) if searcher
.search(state
.db
['questions'][i
][0]) is not None]
688 if len(matches
) > 25:
689 bot
.msg(user
, "Too many matches! (>25)")
690 elif len(matches
) > 1:
691 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
692 elif len(matches
) == 1:
693 bot
.msg(user
, "One match: %s" % (matches
[0]))
695 bot
.msg(user
, "No match.")
697 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
698 @lib.help("<qid>", "displays the q*a for a qid")
699 def showq(bot
, user
, chan
, realtarget
, *args
):
703 bot
.msg(user
, "Specify a numeric question ID.")
706 q
= state
.db
['questions'][qid
]
708 bot
.msg(user
, "ID not valid.")
710 bot
.msg(user
, "%s: %s*%s" % (qid
, q
[0], q
[1]))
712 @lib.hook(('delq', 'deleteq'), glevel
=lib
.STAFF
, needchan
=False)
713 @lib.help("<qid>", "removes a question from the database")
714 def delq(bot
, user
, chan
, realtarget
, *args
):
716 backup
= state
.db
['questions'][int(args
[0])]
717 del state
.db
['questions'][int(args
[0])]
718 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]))
720 bot
.msg(user
, "Couldn't delete that question. %r" % (e
))
722 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
723 @lib.help("<q>*<a>", "adds a question")
724 def addq(bot
, user
, chan
, realtarget
, *args
):
725 line
= ' '.join([str(arg
) for arg
in args
])
726 linepieces
= line
.split('*')
727 if len(linepieces
) < 2:
728 bot
.msg(user
, "Error: need <question>*<answer>")
730 question
= linepieces
[0].strip()
731 answer
= linepieces
[1].strip()
732 state
.db
['questions'].append([question
, answer
])
733 bot
.msg(user
, "Done. Question is #%s" % (len(state
.db
['questions'])-1))
736 @lib.hook(needchan
=False)
737 def triviahelp(bot
, user
, chan
, realtarget
, *args
):
738 bot
.slowmsg(user
, "START")
739 bot
.slowmsg(user
, "TOP10")
740 bot
.slowmsg(user
, "POINTS [<user>]")
741 bot
.slowmsg(user
, "RANK [<user>]")
742 bot
.slowmsg(user
, "BADQ <reason> (include info to identify question)")
744 bot
.slowmsg(user
, "SKIP (KNOWN)")
745 bot
.slowmsg(user
, "STOP (KNOWN)")
746 bot
.slowmsg(user
, "FINDQ <full question> (KNOWN)")
747 bot
.slowmsg(user
, "FINDQRE <regex> (KNOWN)")
748 bot
.slowmsg(user
, "SETNEXTID <qid> (KNOWN)")
749 if user
.glevel
>= lib
.STAFF
:
750 bot
.slowmsg(user
, "GIVE <user> [<points>] (STAFF)")
751 bot
.slowmsg(user
, "SETNEXT <q>*<a> (STAFF)")
752 bot
.slowmsg(user
, "ADDQ <q>*<a> (STAFF)")
753 bot
.slowmsg(user
, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
754 bot
.slowmsg(user
, "SHOWQ <qid> (STAFF)")
755 bot
.slowmsg(user
, "BADQS (STAFF)")
756 bot
.slowmsg(user
, "CLEARBADQS (STAFF)")
757 bot
.slowmsg(user
, "DELBADQ <reportid> (STAFF)")
758 if user
.glevel
>= lib
.ADMIN
:
759 bot
.slowmsg(user
, "SETTARGET <points> (ADMIN)")
760 bot
.slowmsg(user
, "MAXMISSED <questions> (ADMIN)")
761 bot
.slowmsg(user
, "HINTTIMER <float seconds> (ADMIN)")
762 bot
.slowmsg(user
, "HINTNUM <hints> (ADMIN)")
763 bot
.slowmsg(user
, "QUESTIONPAUSE <float seconds> (ADMIN)")
766 def num_417(bot
, textline
):
767 # bot.fastmsg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
768 state
.nextquestion(qskipped
=False, skipwait
=True)
771 def num_TOPIC(bot
, textline
):
772 pieces
= textline
.split(None, 4)
774 if chan
!= state
.db
['chan']:
776 gottopic
= pieces
[4][1:]
778 formatted
= state
.db
['topicformat'] % {
779 'chan': state
.db
['chan'],
780 'top1': "%s (%s)" % (person(0), pts(0)),
782 "%s (%s)" % (person(x
), pts(x
))
783 for x
in range(3) if x
< len(state
.db
['ranks'])
786 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
787 for x
in range(3) if x
< len(state
.db
['ranks'])
790 "%s (%s)" % (person(x
), pts(x
))
791 for x
in range(10) if x
< len(state
.db
['ranks'])
794 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
795 for x
in range(10) if x
< len(state
.db
['ranks'])
797 'lastwinner': state
.db
['lastwinner'],
798 'lastwon': time
.strftime("%b %d", time
.gmtime(state
.db
['lastwon'])),
799 'target': state
.db
['target'],
801 if gottopic
!= formatted
:
802 state
.getbot().conn
.send("TOPIC %s :%s" % (state
.db
['chan'], formatted
))
805 def specialQuestion(oldq
):
806 newq
= [oldq
[0], oldq
[1]]
807 qtype
= oldq
[0].upper()
809 if qtype
== "!MONTH":
810 newq
[0] = "What month is it currently (in UTC)?"
811 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
812 elif qtype
== "!MATH+":
813 randnum1
= random
.randrange(0, 11)
814 randnum2
= random
.randrange(0, 11)
815 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
816 newq
[1] = spellout(randnum1
+randnum2
)
821 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
822 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
823 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"