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'])
190 f
= open(self
.db
['hofpath'], 'rb+')
191 for i
in range(self
.db
['hoflines']): #skip this many lines
196 f
.write((self
.db
['hofformat']+"\n") % {
197 'date': time
.strftime("%F", time
.gmtime()),
198 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['lastwon'])),
199 'targetscore': self
.db
['target'],
200 'firstperson': person(0),
201 'firstscore': pts(0),
202 'secondperson': person(1),
203 'secondscore': pts(1),
204 'thirdperson': person(2),
205 'thirdscore': pts(2),
209 except Exception as e
:
210 raise e
#FIXME wtf???
215 def endPointVote(self
):
216 self
.getchan().msg("Voting has ended!")
217 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
218 for i
in range(len(votelist
)-1):
220 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
221 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
223 self
.db
['target'] = votelist
[-1][0]
224 self
.pointvote
= None
226 self
.nextquestion() #start the game!
228 def nextquestion(self
, qskipped
=False, iteration
=0, skipwait
=False):
229 self
.lastqid
= self
.curqid
232 if self
.gameover
== True:
233 return self
.doGameOver()
235 self
.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
236 self
.missedquestions
+= 1
238 self
.missedquestions
= 0
239 if 'topicformat' in self
.db
and self
.db
['topicformat'] is not None:
240 self
.getbot().conn
.send("TOPIC %s" % (self
.db
['chan']))
242 if isinstance(self
.steptimer
, threading
._Timer
):
243 self
.steptimer
.cancel()
244 if isinstance(self
.nextquestiontimer
, threading
._Timer
):
245 self
.nextquestiontimer
.cancel()
246 self
.nextquestiontimer
= None
250 self
.revealpossibilities
= None
253 if self
.missedquestions
> self
.db
['maxmissedquestions']:
255 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game." % (self
.missedquestions
))
259 self
._nextquestion
(iteration
)
261 self
.nextquestiontimer
= MyTimer(self
.db
['questionpause'], self
._nextquestion
, args
=[iteration
])
262 self
.nextquestiontimer
.start()
264 def _nextquestion(self
, iteration
):
265 if self
.nextq
is not None:
270 nextqid
= random
.randrange(0, len(self
.db
['questions']))
271 nextq
= self
.db
['questions'][nextqid
]
273 if nextq
[0][0] == "!":
275 nextq
= specialQuestion(nextq
)
277 if len(nextq
) > 2 and nextq
[2] - time
.time() < 7*24*60*60 and iteration
< 10:
278 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
280 nextq
[2] = time
.time()
282 nextq
.append(time
.time())
284 if isinstance(nextq
[1], basestring
):
285 nextq
[1] = nextq
[1].lower()
287 nextq
[1] = [s
.lower() for s
in nextq
[1]]
289 qtext
= "\00312,01Next up: "
290 qtext
+= "(%5d)" % (random
.randint(0,99999))
291 qary
= nextq
[0].split(None)
294 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(random
.randrange(0x61,0x7A)) #a-z
295 self
.getbot().fastmsg(self
.chan
, qtext
)
298 self
.curqid
= nextqid
300 if isinstance(self
.curq
[1], basestring
): self
.hintanswer
= self
.curq
[1]
301 else: self
.hintanswer
= random
.choice(self
.curq
[1])
303 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
304 self
.steptimer
.start()
306 def checkanswer(self
, answer
):
307 if self
.curq
is None:
309 elif isinstance(self
.curq
[1], basestring
):
310 return answer
.lower() == self
.curq
[1]
311 else: # assume it's a list or something.
312 return answer
.lower() in self
.curq
[1]
314 def addpoint(self
, user_obj
, count
=1):
315 user_nick
= str(user_obj
)
316 user
= user_nick
.lower() # save this separately as we use both
317 if user
in self
.db
['users']:
318 self
.db
['users'][user
]['points'] += count
320 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
321 self
.db
['ranks'].append(user
)
323 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
324 for i
in range(0, len(self
.db
['ranks'])):
325 nick
= self
.db
['ranks'][i
]
326 self
.db
['users'][nick
]['rank'] = i
328 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
331 return self
.db
['users'][user
]['points']
333 def points(self
, user
):
334 user
= str(user
).lower()
335 if user
in self
.db
['users']:
336 return self
.db
['users'][user
]['points']
340 def rank(self
, user
):
341 user
= str(user
).lower()
342 if user
in self
.db
['users']:
343 return self
.db
['users'][user
]['rank']+1
345 return len(self
.db
['users'])+1
347 def targetuser(self
, user
):
348 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
350 user
= str(user
).lower()
351 if user
in self
.db
['users']:
352 rank
= self
.db
['users'][user
]['rank']
354 return "you're in the lead!"
356 return self
.db
['ranks'][rank
-1]
358 return self
.db
['ranks'][-1]
359 def targetpoints(self
, user
):
360 if len(self
.db
['ranks']) == 0: return 0
362 user
= str(user
).lower()
363 if user
in self
.db
['users']:
364 rank
= self
.db
['users'][user
]['rank']
368 return self
.db
['users'][self
.db
['ranks'][rank
-1]]['points']
370 return self
.db
['users'][self
.db
['ranks'][-1]]['points']
372 state
= TriviaState()
374 # we have to hook this in modstart, since we don't know the channel until then.
375 def trivia_checkanswer(bot
, user
, chan
, *args
):
376 line
= ' '.join([str(arg
) for arg
in args
])
377 if state
.checkanswer(line
):
379 if state
.hintanswer
.lower() == line
.lower():
380 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
)))
382 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
)))
383 if state
.hintsgiven
== 0:
384 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
387 @lib.hook(needchan
=False)
388 def points(bot
, user
, chan
, realtarget
, *args
):
389 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
392 if len(args
) != 0: who
= args
[0]
395 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
397 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
399 def give(bot
, user
, chan
, realtarget
, *args
):
402 numpoints
= int(args
[1])
405 balance
= state
.addpoint(whoto
, numpoints
)
407 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
409 @lib.hook(glevel
=1, needchan
=False)
410 def setnextid(bot
, user
, chan
, realtarget
, *args
):
413 state
.nextq
= state
.db
['questions'][qid
]
414 if user
.glevel
>= lib
.STAFF
:
415 respstr
= "Done. Next question is: %s" % (state
.nextq
[0])
418 bot
.msg(user
, respstr
)
419 except Exception as e
:
420 bot
.msg(user
, "Error: %s" % (e
))
422 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
424 def setnext(bot
, user
, chan
, realtarget
, *args
):
425 line
= ' '.join([str(arg
) for arg
in args
])
426 linepieces
= line
.split('*')
427 if len(linepieces
) < 2:
428 bot
.msg(user
, "Error: need <question>*<answer>")
430 question
= linepieces
[0].strip()
431 answer
= linepieces
[1].strip()
432 state
.nextq
= [question
, answer
]
433 bot
.msg(user
, "Done.")
435 @lib.hook(glevel
=1, needchan
=False)
436 def skip(bot
, user
, chan
, realtarget
, *args
):
437 state
.nextquestion(qskipped
=True, skipwait
=True)
439 @lib.hook(needchan
=False)
440 def start(bot
, user
, chan
, realtarget
, *args
):
441 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
444 if chan
is not None and chan
.name
!= state
.db
['chan']:
445 bot
.msg(replyto
, "That command isn't valid here.")
448 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
449 bot
.msg(state
.db
['chan'], "%s has started the game!" % (user
))
450 state
.nextquestion(skipwait
=True)
451 elif state
.pointvote
is not None:
452 bot
.msg(user
, "There's a vote in progress!")
454 bot
.msg(user
, "Game is already started!")
456 @lib.hook('stop', glevel
=1, needchan
=False)
457 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
459 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
461 bot
.msg(user
, "Game isn't running.")
467 state
.steptimer
.cancel()
468 except Exception as e
:
469 print "!!! steptimer.cancel(): %s %r" % (e
,e
)
470 state
.steptimer
= None
472 state
.nextquestiontimer
.cancel()
473 except Exception as e
:
474 print "!!! nextquestiontimer.cancel(): %s %r" % (e
,e
)
475 state
.nextquestiontimer
= None
478 @lib.hook(needchan
=False)
480 def badq(bot
, user
, chan
, realtarget
, *args
):
481 lastqid
= state
.lastqid
482 curqid
= state
.curqid
484 reason
= ' '.join(args
)
485 state
.db
['badqs'].append([lastqid
, curqid
, reason
])
487 bot
.msg(user
, "Reported bad question.")
489 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
490 def badqs(bot
, user
, chan
, realtarget
, *args
):
491 if len(state
.db
['badqs']) == 0:
492 bot
.msg(user
, "No reports.")
494 for i
in range(len(state
.db
['badqs'])):
496 report
= state
.db
['badqs'][i
]
497 bot
.msg(user
, "Report #%d: LastQ=%r CurQ=%r: %s" % (i
, report
[0], report
[1], report
[2]))
498 try: lq
= state
.db
['questions'][int(report
[0])]
499 except Exception as e
: lq
= (None,None)
500 try: cq
= state
.db
['questions'][int(report
[1])]
501 except Exception as e
: cq
= (None, None)
502 bot
.msg(user
, "- Last: %s*%s" % (lq
[0], lq
[1]))
503 bot
.msg(user
, "- Curr: %s*%s" % (cq
[0], cq
[1]))
504 except Exception as e
:
505 bot
.msg(user
, "- Exception: %r" % (e
))
507 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
508 def clearbadqs(bot
, user
, chan
, realtarget
, *args
):
509 state
.db
['badqs'] = []
511 bot
.msg(user
, "Cleared reports.")
513 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
515 def delbadq(bot
, user
, chan
, realtarget
, *args
):
518 del state
.db
['badqs'][qid
]
520 bot
.msg(user
, "Removed report #%d" % (qid
))
522 bot
.msg(user
, "Failed!")
524 @lib.hook(needchan
=False)
525 def rank(bot
, user
, chan
, realtarget
, *args
):
526 if chan
is not None and realtarget
== chan
.name
: replyto
= chan
529 if len(args
) != 0: who
= args
[0]
532 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
)))
534 @lib.hook(needchan
=False)
535 def top10(bot
, user
, chan
, realtarget
, *args
):
536 if len(state
.db
['ranks']) == 0:
537 return bot
.msg(state
.db
['chan'], "No one is ranked!")
539 max = len(state
.db
['ranks'])
542 replylist
= ', '.join(["%s (%s) %s" % (person(x
), country(x
), pts(x
)) for x
in range(max)])
543 bot
.msg(state
.db
['chan'], "Top 10: %s" % (replylist
))
545 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
546 def settarget(bot
, user
, chan
, realtarget
, *args
):
548 state
.db
['target'] = int(args
[0])
549 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
551 if state
.pointvote
is not None:
552 state
.pointvote
.cancel()
553 state
.pointvote
= None
554 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
555 except Exception as e
:
557 bot
.msg(user
, "Failed to set target.")
559 @lib.hook(needchan
=False)
560 def vote(bot
, user
, chan
, realtarget
, *args
):
561 if state
.pointvote
is not None:
562 if int(args
[0]) in state
.voteamounts
:
563 state
.voteamounts
[int(args
[0])] += 1
564 bot
.msg(user
, "Your vote has been recorded.")
566 bot
.msg(user
, "Sorry - that's not an option!")
568 bot
.msg(user
, "There's no vote in progress.")
570 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
571 def maxmissed(bot
, user
, chan
, realtarget
, *args
):
573 state
.db
['maxmissedquestions'] = int(args
[0])
574 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
576 bot
.msg(user
, "Failed to set maxmissed.")
578 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
579 def hinttimer(bot
, user
, chan
, realtarget
, *args
):
581 state
.db
['hinttimer'] = float(args
[0])
582 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
584 bot
.msg(user
, "Failed to set hint timer.")
586 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
587 def hintnum(bot
, user
, chan
, realtarget
, *args
):
589 state
.db
['hintnum'] = int(args
[0])
590 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
592 bot
.msg(user
, "Failed to set hintnum.")
594 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
595 def questionpause(bot
, user
, chan
, realtarget
, *args
):
597 state
.db
['questionpause'] = float(args
[0])
598 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
600 bot
.msg(user
, "Failed to set questionpause.")
602 @lib.hook(glevel
=1, needchan
=False)
603 def findq(bot
, user
, chan
, realtarget
, *args
):
605 bot
.msg(user
, "You need to specify the question.")
608 searchkey
= ' '.join(args
).lower()
609 matches
= [str(i
) for i
in range(len(state
.db
['questions'])) if state
.db
['questions'][i
][0].lower() == searchkey
]
611 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
612 elif len(matches
) == 1:
613 bot
.msg(user
, "One match: %s" % (matches
[0]))
615 bot
.msg(user
, "No match.")
617 @lib.hook(glevel
=1, needchan
=False)
618 def findqre(bot
, user
, chan
, realtarget
, *args
):
620 bot
.msg(user
, "You need to specify a search string.")
623 searcher
= re
.compile(' '.join(args
), re
.IGNORECASE
)
624 matches
= [str(i
) for i
in range(len(state
.db
['questions'])) if searcher
.search(state
.db
['questions'][i
][0]) is not None]
625 if len(matches
) > 25:
626 bot
.msg(user
, "Too many matches! (>25)")
627 elif len(matches
) > 1:
628 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
629 elif len(matches
) == 1:
630 bot
.msg(user
, "One match: %s" % (matches
[0]))
632 bot
.msg(user
, "No match.")
634 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
635 def showq(bot
, user
, chan
, realtarget
, *args
):
639 bot
.msg(user
, "Specify a numeric question ID.")
642 q
= state
.db
['questions'][qid
]
644 bot
.msg(user
, "ID not valid.")
646 bot
.msg(user
, "%s: %s*%s" % (qid
, q
[0], q
[1]))
648 @lib.hook(('delq', 'deleteq'), glevel
=lib
.STAFF
, needchan
=False)
649 def delq(bot
, user
, chan
, realtarget
, *args
):
651 backup
= state
.db
['questions'][int(args
[0])]
652 del state
.db
['questions'][int(args
[0])]
654 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]))
656 bot
.msg(user
, "Couldn't delete that question. %r" % (e
))
658 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
659 def addq(bot
, user
, chan
, realtarget
, *args
):
660 line
= ' '.join([str(arg
) for arg
in args
])
661 linepieces
= line
.split('*')
662 if len(linepieces
) < 2:
663 bot
.msg(user
, "Error: need <question>*<answer>")
665 question
= linepieces
[0].strip()
666 answer
= linepieces
[1].strip()
667 state
.db
['questions'].append([question
, answer
])
669 bot
.msg(user
, "Done. Question is #%s" % (len(state
.db
['questions'])-1))
672 @lib.hook(needchan
=False)
673 def triviahelp(bot
, user
, chan
, realtarget
, *args
):
674 bot
.slowmsg(user
, "START")
675 bot
.slowmsg(user
, "TOP10")
676 bot
.slowmsg(user
, "POINTS [<user>]")
677 bot
.slowmsg(user
, "RANK [<user>]")
678 bot
.slowmsg(user
, "BADQ <reason> (include info to identify question)")
680 bot
.slowmsg(user
, "SKIP (KNOWN)")
681 bot
.slowmsg(user
, "STOP (KNOWN)")
682 bot
.slowmsg(user
, "FINDQ <full question> (KNOWN)")
683 bot
.slowmsg(user
, "FINDQRE <regex> (KNOWN)")
684 bot
.slowmsg(user
, "SETNEXTID <qid> (KNOWN)")
685 if user
.glevel
>= lib
.STAFF
:
686 bot
.slowmsg(user
, "GIVE <user> [<points>] (STAFF)")
687 bot
.slowmsg(user
, "SETNEXT <q>*<a> (STAFF)")
688 bot
.slowmsg(user
, "ADDQ <q>*<a> (STAFF)")
689 bot
.slowmsg(user
, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
690 bot
.slowmsg(user
, "SHOWQ <qid> (STAFF)")
691 bot
.slowmsg(user
, "BADQS (STAFF)")
692 bot
.slowmsg(user
, "CLEARBADQS (STAFF)")
693 bot
.slowmsg(user
, "DELBADQ <reportid> (STAFF)")
694 if user
.glevel
>= lib
.ADMIN
:
695 bot
.slowmsg(user
, "SETTARGET <points> (ADMIN)")
696 bot
.slowmsg(user
, "MAXMISSED <questions> (ADMIN)")
697 bot
.slowmsg(user
, "HINTTIMER <float seconds> (ADMIN)")
698 bot
.slowmsg(user
, "HINTNUM <hints> (ADMIN)")
699 bot
.slowmsg(user
, "QUESTIONPAUSE <float seconds> (ADMIN)")
702 def num_417(bot
, textline
):
703 # bot.fastmsg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
704 state
.nextquestion(qskipped
=False, skipwait
=True)
707 def num_TOPIC(bot
, textline
):
708 pieces
= textline
.split(None, 4)
710 if chan
!= state
.db
['chan']:
712 gottopic
= pieces
[4][1:]
714 formatted
= state
.db
['topicformat'] % {
715 'chan': state
.db
['chan'],
716 'top1': "%s (%s)" % (person(0), pts(0)),
718 "%s (%s)" % (person(x
), pts(x
))
719 for x
in range(3) if x
< len(state
.db
['ranks'])
722 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
723 for x
in range(3) if x
< len(state
.db
['ranks'])
726 "%s (%s)" % (person(x
), pts(x
))
727 for x
in range(10) if x
< len(state
.db
['ranks'])
730 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
731 for x
in range(10) if x
< len(state
.db
['ranks'])
733 'lastwinner': state
.db
['lastwinner'],
734 'lastwon': time
.strftime("%b %d", time
.gmtime(state
.db
['lastwon'])),
735 'target': state
.db
['target'],
737 if gottopic
!= formatted
:
738 state
.getbot().conn
.send("TOPIC %s :%s" % (state
.db
['chan'], formatted
))
741 def specialQuestion(oldq
):
742 newq
= [oldq
[0], oldq
[1]]
743 qtype
= oldq
[0].upper()
745 if qtype
== "!MONTH":
746 newq
[0] = "What month is it currently (in UTC)?"
747 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
748 elif qtype
== "!MATH+":
749 randnum1
= random
.randrange(0, 11)
750 randnum2
= random
.randrange(0, 11)
751 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
752 newq
[1] = spellout(randnum1
+randnum2
)
757 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
758 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
759 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"