1 # Erebus IRC bot - Author: Erebus Team
2 # vim: fileencoding=utf-8
4 # This file is released into the public domain; see http://unlicense.org/
6 from __future__
import print_function
10 'author': 'Erebus Team',
11 'license': 'public domain',
14 'softdeps': ['help','userinfo'],
19 lib
= modlib
.modlib(__name__
)
20 def modstart(parent
, *args
, **kwargs
):
21 state
.gotParent(parent
)
22 lib
.hookchan(state
.db
['chan'])(trivia_checkanswer
) # we need parent for this. so it goes here.
23 return lib
.modstart(parent
, *args
, **kwargs
)
24 def modstop(*args
, **kwargs
):
30 except Exception: pass
31 return lib
.modstop(*args
, **kwargs
)
34 import json
, random
, threading
, re
, time
, datetime
, os
, sys
36 if sys
.version_info
.major
< 3:
37 timerbase
= threading
._Timer
39 timerbase
= threading
.Timer
44 except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
46 def findnth(haystack
, needle
, n
): #http://stackoverflow.com/a/1884151
47 parts
= haystack
.split(needle
, n
+1)
50 return len(haystack
)-len(parts
[-1])-len(needle
)
52 def person(num
, throwindexerror
=False):
54 return state
.db
['users'][state
.db
['ranks'][num
]]['realnick']
63 return str(state
.db
['users'][state
.db
['ranks'][num
]]['points'])
67 def country(num
, default
="??"):
69 return lib
.mod('userinfo').get(person(num
), 'country', default
=default
).upper()
71 return default
.upper()
73 class MyTimer(timerbase
):
74 def __init__(self
, *args
, **kwargs
):
75 timerbase
.__init
__(self
, *args
, **kwargs
)
78 class TriviaState(object):
79 def __init__(self
, parent
=None, pointvote
=False):
81 self
.streak_holder
= None
82 if parent
is not None:
83 self
.gotParent(parent
, pointvote
)
85 def gotParent(self
, parent
, pointvote
=False):
87 self
.questionfile
= self
.parent
.cfg
.get('trivia', 'jsonpath', default
="./modules/trivia.json")
88 self
.db
= json
.load(open(self
.questionfile
, "r"))
89 self
.questions
= self
.db
['questions'][self
.db
['category']]
90 self
.chan
= self
.db
['chan']
94 self
.nextquestiontimer
= None
97 self
.hintanswer
= None
99 self
.revealpossibilities
= None
100 self
.gameover
= False
101 self
.missedquestions
= 0
105 if 'lastwon' not in self
.db
or self
.db
['lastwon'] is None:
106 self
.db
['lastwon'] = time
.time()
109 self
.getchan().fastmsg("Vote for the next round target points! Options: %s. Vote using !vote <choice>" % (', '.join([str(x
) for x
in self
.db
['targetoptions']])))
110 self
.getchan().fastmsg("You have %s seconds." % (self
.db
['votetimer']))
111 self
.voteamounts
= dict([(x
, 0) for x
in self
.db
['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
112 self
.pointvote
= MyTimer(self
.db
['votetimer'], self
.endPointVote
)
113 self
.pointvote
.start()
115 self
.pointvote
= None
121 self
.steptimer
.cancel()
122 self
.steptimer
= None
125 self
.nextquestiontimer
.cancel()
126 self
.nextquestiontimer
= None
129 def savedb(self
): #returns whether or not it was able to save
130 if json
is not None and json
.dump
is not None:
131 # json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
132 dbjson
= json
.dumps(self
.db
)
134 os
.rename(self
.questionfile
, self
.questionfile
+".auto.bak")
135 tmpfn
= os
.tempnam('.', 'trivia')
140 os
.rename(tmpfn
, self
.questionfile
)
142 except: #if something happens, restore the backup
143 os
.rename(self
.questionfile
+".auto.bak", self
.questionfile
)
146 except OSError: # temp file is already gone
148 raise # we may be better off just swallowing exceptions?
152 return self
.parent
.channel(self
.chan
)
154 return self
.getchan().bot
156 def nexthint(self
, hintnum
):
157 answer
= self
.hintanswer
159 if self
.hintstr
is None or self
.revealpossibilities
is None or self
.reveal
is None:
161 self
.hintstr
= list(re
.sub(r
'[a-zA-Z0-9]', '*', answer
))
162 self
.revealpossibilities
= range(''.join(self
.hintstr
).count('*'))
163 self
.reveal
= int(round(''.join(self
.hintstr
).count('*') * (7/24.0)))
165 oldhintstr
= ''.join(self
.hintstr
)
168 for i
in range(self
.reveal
):
169 revealcount
= random
.choice(self
.revealpossibilities
)
170 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
171 self
.revealpossibilities
.remove(revealcount
)
172 self
.hintstr
[revealloc
] = answer
[revealloc
]
173 except IndexError: pass # if everything is revealed, random.choice will IndexError
174 if oldhintstr
!= ''.join(self
.hintstr
): self
.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
178 if hintnum
< self
.db
['hintnum']:
179 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
180 self
.steptimer
.start()
182 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
183 self
.steptimer
.start()
185 def doGameOver(self
):
186 msg
= self
.getchan().msg
189 msg("\00312THE GAME IS OVER!!!")
190 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
191 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
192 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
193 [msg("%dth place: %s (%s)" % (i
+1, person(i
, True), pts(i
))) for i
in range(3,10)]
194 except IndexError: pass
195 except Exception as e
:
196 msg("DERP! %r" % (e
))
198 if self
.db
['hofpath'] is not None and self
.db
['hofpath'] != '':
201 self
.db
['lastwinner'] = winner
202 self
.db
['lastwon'] = time
.time()
204 self
.db
['users'] = {}
205 self
.db
['ranks'] = []
211 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
212 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
213 self
.getbot().parent
.cfg
.get('trivia', 'con'),
214 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
215 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
216 except: pass #don't care if errors happen updating twitter.
218 self
.__init
__(self
.parent
, True)
222 try: return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
223 except: return "none"
225 try: return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
231 f
= open(self
.db
['hofpath'], 'rb+')
232 for i
in range(self
.db
['hoflines']): #skip this many lines
237 f
.write((self
.db
['hofformat']+"\n") % {
238 'date': time
.strftime("%F", time
.gmtime()),
239 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['lastwon'])),
240 'targetscore': self
.db
['target'],
241 'firstperson': person(0),
242 'firstscore': pts(0),
243 'secondperson': person(1),
244 'secondscore': pts(1),
245 'thirdperson': person(2),
246 'thirdscore': pts(2),
250 except Exception as e
:
257 def endPointVote(self
):
258 self
.getchan().msg("Voting has ended!")
259 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
260 for i
in range(len(votelist
)-1):
262 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
263 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
265 self
.db
['target'] = votelist
[-1][0]
266 self
.pointvote
= None
268 self
.nextquestion() #start the game!
270 def nextquestion(self
, qskipped
=False, iteration
=0, skipwait
=False):
271 self
.lastqid
= self
.curqid
274 self
.lastqtime
= time
.time()
275 if self
.gameover
== True:
276 return self
.doGameOver()
279 self
.streak_holder
= None
280 self
.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
281 self
.missedquestions
+= 1
283 self
.missedquestions
= 0
284 if 'topicformat' in self
.db
and self
.db
['topicformat'] is not None:
285 self
.getbot().conn
.send("TOPIC %s" % (self
.db
['chan']))
287 if isinstance(self
.steptimer
, MyTimer
):
288 self
.steptimer
.cancel()
289 if isinstance(self
.nextquestiontimer
, MyTimer
):
290 self
.nextquestiontimer
.cancel()
291 self
.nextquestiontimer
= None
295 self
.revealpossibilities
= None
300 if self
.missedquestions
> self
.db
['maxmissedquestions']:
302 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game." % (self
.missedquestions
))
306 self
._nextquestion
(iteration
)
308 self
.nextquestiontimer
= MyTimer(self
.db
['questionpause'], self
._nextquestion
, args
=[iteration
])
309 self
.nextquestiontimer
.start()
311 def _nextquestion(self
, iteration
):
312 if self
.nextq
is not None:
316 elif self
.nextqid
is not None:
317 nextqid
= self
.nextqid
318 nextq
= self
.questions
[nextqid
]
321 nextqid
= random
.randrange(0, len(self
.questions
))
322 nextq
= self
.questions
[nextqid
]
324 if nextq
[0].startswith("!"):
326 nextq
= specialQuestion(nextq
)
328 if len(nextq
) > 2 and time
.time() - nextq
[2] < 7*24*60*60 and iteration
< 10:
329 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
331 nextq
[2] = time
.time()
333 nextq
.append(time
.time())
335 if isinstance(nextq
[1], basestring
):
336 nextq
[1] = nextq
[1].lower()
338 nextq
[1] = [s
.lower() for s
in nextq
[1]]
340 qtext
= "\00312,01Next up: "
341 qtext
+= "(%5d)" % (random
.randint(0,99999))
342 qary
= nextq
[0].split(None)
345 spacer
= random
.choice(
346 range(0x61,0x7A) + ([0x20]*4)
348 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(spacer
) #a-z
349 if not self
.getbot().fastmsg(self
.chan
, qtext
): #if message is too long:
350 if not self
.getbot().fastmsg(self
.chan
, "\00312,01Next up: " + ("(%5d)" % (random
.randint(0,99999))) + "\00304,01" + nextq
[0]):
351 if nextqid
is None: nextqid
= "manual"
352 self
.getbot().slowmsg(self
.chan
, "(Unable to ask question #%s: line too long)" % (nextqid
))
353 return self
._nextquestion
(iteration
) #retry; don't increment the iteration
356 self
.curqid
= nextqid
358 if isinstance(self
.curq
[1], basestring
): self
.hintanswer
= self
.curq
[1]
359 else: self
.hintanswer
= random
.choice(self
.curq
[1])
361 self
.steptimer
= MyTimer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
362 self
.steptimer
.start()
364 def checkanswer(self
, answer
):
365 if self
.curq
is None:
367 elif isinstance(self
.curq
[1], basestring
):
368 return answer
.lower() == self
.curq
[1]
369 else: # assume it's a list or something.
370 return answer
.lower() in self
.curq
[1]
372 def addpoint(self
, user_obj
, count
=1):
373 user_nick
= str(user_obj
)
374 user
= user_nick
.lower() # save this separately as we use both
375 if user
in self
.db
['users']:
376 self
.db
['users'][user
]['points'] += count
378 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
379 self
.db
['ranks'].append(user
)
381 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
382 for i
in range(0, len(self
.db
['ranks'])):
383 nick
= self
.db
['ranks'][i
]
384 self
.db
['users'][nick
]['rank'] = i
386 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
389 return self
.db
['users'][user
]['points']
391 def points(self
, user
):
392 user
= str(user
).lower()
393 if user
in self
.db
['users']:
394 return self
.db
['users'][user
]['points']
398 def rank(self
, user
):
399 user
= str(user
).lower()
400 if user
in self
.db
['users']:
401 return self
.db
['users'][user
]['rank']+1
403 return len(self
.db
['users'])+1
405 def targetuser(self
, user
):
406 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
408 user
= str(user
).lower()
409 if user
in self
.db
['users']:
410 rank
= self
.db
['users'][user
]['rank']
412 return "you're in the lead!"
414 return self
.db
['ranks'][rank
-1]
416 return self
.db
['ranks'][-1]
417 def targetpoints(self
, user
):
418 if len(self
.db
['ranks']) == 0: return 0
420 user
= str(user
).lower()
421 if user
in self
.db
['users']:
422 rank
= self
.db
['users'][user
]['rank']
426 return "("+str(self
.db
['users'][self
.db
['ranks'][rank
-1]]['points'])+")"
428 return "("+str(self
.db
['users'][self
.db
['ranks'][-1]]['points'])+")"
430 state
= TriviaState()
432 # we have to hook this in modstart, since we don't know the channel until then.
433 def trivia_checkanswer(bot
, user
, chan
, *args
):
434 line
= ' '.join([str(arg
) for arg
in args
])
435 if state
.checkanswer(line
):
438 if state
.streak_holder
== user
:
441 if state
.streak
>= 3:
442 bot
.fastmsg(chan
, "\00312%s\003 broke \00304%s\003's streak of \00307%d\003!" % (user
, state
.streak_holder
, state
.streak
))
443 state
.streak_holder
= user
446 response
= "\00312%s\003 got it in %d seconds! The answer was \00312%s\003" % (user
, time
.time()-state
.lastqtime
, line
)
447 if state
.hintanswer
.lower() != line
.lower():
448 response
+= " (hinted answer: %s)" % (state
.hintanswer
)
449 response
+= ". New score: %d. Rank: %d. Target: %s %s" % (state
.addpoint(user
), state
.rank(user
), state
.targetuser(user
), state
.targetpoints(user
))
450 bot
.fastmsg(chan
, response
)
452 if state
.streak
>= 3:
453 bot
.msg(chan
, "\00312%s\003 is on a streak! \00307%d\003 answers correct in a row!" % (user
, state
.streak
))
455 if state
.hintsgiven
== 0:
456 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
460 @lib.hook(glevel
=1, needchan
=False, wantchan
=True)
461 @lib.help(None, "saves the trivia database")
462 def save(bot
, user
, chan
, realtarget
, *args
):
463 if chan
is not None: replyto
= chan
467 bot
.msg(replyto
, "Save successful.")
469 bot
.msg(replyto
, "Save failed!")
471 @lib.hook(needchan
=False, wantchan
=True)
472 @lib.help("[<user>]", "shows how many points you or someone has")
473 def points(bot
, user
, chan
, realtarget
, *args
):
474 if chan
is not None: eplyto
= chan
477 if len(args
) != 0: who
= args
[0]
480 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
482 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
483 @lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
485 def give(bot
, user
, chan
, realtarget
, *args
):
488 numpoints
= int(args
[1])
491 balance
= state
.addpoint(whoto
, numpoints
)
493 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
495 @lib.hook(glevel
=1, needchan
=False)
496 @lib.help("<qid>", "sets next question to one in the database")
498 def setnextid(bot
, user
, chan
, realtarget
, *args
):
502 bot
.msg(user
, "Error: QID must be a number.")
504 if qid
>= len(state
.questions
):
505 bot
.msg(user
, "Error: no such QID.")
508 bot
.msg(user
, "Done. Next question is %d: %s" % (qid
, state
.questions
[qid
][0]), truncate
=True)
510 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
511 @lib.help("<q>*<a>", "sets next question to one not in database")
513 def setnext(bot
, user
, chan
, realtarget
, *args
):
514 line
= ' '.join([str(arg
) for arg
in args
])
515 linepieces
= line
.split('*', 1)
516 if len(linepieces
) < 2:
517 bot
.msg(user
, "Error: need <question>*<answer>")
519 question
= linepieces
[0].strip()
520 answer
= linepieces
[1].strip()
521 state
.nextq
= [question
, answer
]
522 bot
.msg(user
, "Done.")
524 @lib.hook(glevel
=1, needchan
=False)
525 @lib.help(None, "skips to next question")
526 def skip(bot
, user
, chan
, realtarget
, *args
):
527 state
.nextquestion(qskipped
=True, skipwait
=True)
529 @lib.hook(('start','trivia'), needchan
=False, wantchan
=True)
530 @lib.help(None, "starts the trivia game")
531 def start(bot
, user
, chan
, realtarget
, *args
):
532 if chan
is not None: replyto
= chan
535 if chan
is not None and chan
.name
!= state
.db
['chan']:
536 bot
.msg(replyto
, "That command isn't valid here.")
539 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
540 bot
.msg(state
.db
['chan'], "%s has started the game!" % (user
))
541 state
.nextquestion(skipwait
=True)
542 elif state
.pointvote
is not None:
543 bot
.msg(user
, "There's a vote in progress!")
545 bot
.msg(user
, "Game is already started!")
547 @lib.hook('stop', glevel
=1, needchan
=False)
548 @lib.help(None, "stops the trivia game")
549 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
551 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
553 bot
.msg(user
, "Game isn't running.")
559 state
.steptimer
.cancel()
560 except Exception as e
:
561 print("!!! steptimer.cancel(): %s %r" % (e
,e
))
562 state
.steptimer
= None
564 state
.nextquestiontimer
.cancel()
565 except Exception as e
:
566 print("!!! nextquestiontimer.cancel(): %s %r" % (e
,e
))
567 state
.nextquestiontimer
= None
570 @lib.hook(needchan
=False)
571 @lib.help("<reason>", "reports a bad question to the admins")
573 def badq(bot
, user
, chan
, realtarget
, *args
):
574 lastqid
= state
.lastqid
575 curqid
= state
.curqid
577 reason
= ' '.join(args
)
578 state
.db
['badqs'].append([state
.db
['category'], lastqid
, curqid
, reason
])
579 bot
.msg(user
, "Reported bad question.")
581 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
582 @lib.help(None, "shows a list of BADQ reports")
583 def badqs(bot
, user
, chan
, realtarget
, *args
):
584 if len(state
.db
['badqs']) == 0:
585 bot
.msg(user
, "No reports.")
587 for i
in range(len(state
.db
['badqs'])):
589 report
= state
.db
['badqs'][i
]
590 bot
.msg(user
, "Report #%d: Cat=%s LastQ=%r CurQ=%r: %s" % (i
, report
[0], report
[1], report
[2], report
[3]))
591 try: lq
= state
.db
['questions'][report
[0]][int(report
[1])]
592 except Exception as e
: lq
= (None,None)
593 try: cq
= state
.db
['questions'][report
[0]][int(report
[2])]
594 except Exception as e
: cq
= (None, None)
595 bot
.msg(user
, "- Last: %s*%s" % (lq
[0], lq
[1]))
596 bot
.msg(user
, "- Curr: %s*%s" % (cq
[0], cq
[1]))
597 except Exception as e
:
598 bot
.msg(user
, "- Exception: %r" % (e
))
600 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
601 @lib.hook(None, "clears list of BADQ reports")
602 def clearbadqs(bot
, user
, chan
, realtarget
, *args
):
603 state
.db
['badqs'] = []
604 bot
.msg(user
, "Cleared reports.")
606 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
607 @lib.hook("<badqid>", "removes a BADQ report")
609 def delbadq(bot
, user
, chan
, realtarget
, *args
):
612 del state
.db
['badqs'][qid
]
613 bot
.msg(user
, "Removed report #%d" % (qid
))
615 bot
.msg(user
, "Failed!")
617 @lib.hook(needchan
=False, wantchan
=True)
618 @lib.help("[<user>]", "shows you or someone else's rank")
619 def rank(bot
, user
, chan
, realtarget
, *args
):
620 if chan
is not None: replyto
= chan
623 if len(args
) != 0: who
= args
[0]
626 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
)))
628 @lib.hook(needchan
=False)
629 @lib.help(None, "shows top10 list")
630 def top10(bot
, user
, chan
, realtarget
, *args
):
631 if len(state
.db
['ranks']) == 0:
632 return bot
.msg(state
.db
['chan'], "No one is ranked!")
634 max = len(state
.db
['ranks'])
637 replylist
= ', '.join(["%s (%s) %s" % (person(x
), country(x
), pts(x
)) for x
in range(max)])
638 bot
.msg(state
.db
['chan'], "Game is to %s! Top 10: %s" % (state
.db
['target'], replylist
))
640 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
641 @lib.help("<target score>", "changes the target score for this round")
642 def settarget(bot
, user
, chan
, realtarget
, *args
):
644 state
.db
['target'] = int(args
[0])
645 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
647 if state
.pointvote
is not None:
648 state
.pointvote
.cancel()
649 state
.pointvote
= None
650 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
651 except Exception as e
:
653 bot
.msg(user
, "Failed to set target.")
655 @lib.hook(needchan
=False)
656 @lib.help("<option>", "votes for a trarget score for next round")
657 def vote(bot
, user
, chan
, realtarget
, *args
):
658 if state
.pointvote
is not None:
659 if int(args
[0]) in state
.voteamounts
:
660 state
.voteamounts
[int(args
[0])] += 1
661 bot
.msg(user
, "Your vote has been recorded.")
663 bot
.msg(user
, "Sorry - that's not an option!")
665 bot
.msg(user
, "There's no vote in progress.")
667 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
668 @lib.help("<number>", "sets the max missed question before game stops")
669 def maxmissed(bot
, user
, chan
, realtarget
, *args
):
671 state
.db
['maxmissedquestions'] = int(args
[0])
672 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
674 bot
.msg(user
, "Failed to set maxmissed.")
676 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
677 @lib.help("<seconds>", "sets the time between hints")
678 def hinttimer(bot
, user
, chan
, realtarget
, *args
):
680 state
.db
['hinttimer'] = float(args
[0])
681 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
683 bot
.msg(user
, "Failed to set hint timer.")
685 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
686 @lib.help("<number>", "sets the number of hints given")
687 def hintnum(bot
, user
, chan
, realtarget
, *args
):
689 state
.db
['hintnum'] = int(args
[0])
690 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
692 bot
.msg(user
, "Failed to set hintnum.")
694 @lib.hook(glevel
=lib
.ADMIN
, needchan
=False)
695 @lib.help("<seconds>", "sets the pause between questions")
696 def questionpause(bot
, user
, chan
, realtarget
, *args
):
698 state
.db
['questionpause'] = float(args
[0])
699 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
701 bot
.msg(user
, "Failed to set questionpause.")
703 @lib.hook(glevel
=1, needchan
=False)
704 @lib.help("[@category] <full question>", "finds a qid given a complete question")
706 def findq(bot
, user
, chan
, realtarget
, *args
):
708 if args
[0].startswith("@"):
709 cat
= args
.pop(0)[1:].lower()
710 questions
= state
.db
['questions'][cat
]
712 questions
= state
.questions
715 bot
.msg(user
, "You need to specify the question.")
718 searchkey
= ' '.join(args
).lower()
719 matches
= [str(i
) for i
in range(len(questions
)) if questions
[i
][0].lower() == searchkey
]
721 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
722 elif len(matches
) == 1:
723 bot
.msg(user
, "One match: %s" % (matches
[0]))
725 bot
.msg(user
, "No match.")
727 @lib.hook(glevel
=1, needchan
=False)
728 @lib.help("[@<category>] <regex>", "finds a qid given a regex or partial question")
730 def findqre(bot
, user
, chan
, realtarget
, *args
):
732 if args
[0].startswith("@"):
733 cat
= args
.pop(0)[1:].lower()
734 questions
= state
.db
['questions'][cat
]
736 questions
= state
.questions
739 bot
.msg(user
, "You need to specify a search string.")
742 searcher
= re
.compile(' '.join(args
), re
.IGNORECASE
)
743 matches
= [str(i
) for i
in range(len(questions
)) if searcher
.search(questions
[i
][0]) is not None]
744 if len(matches
) > 25:
745 bot
.msg(user
, "Too many matches! (>25)")
746 elif len(matches
) > 1:
747 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
748 elif len(matches
) == 1:
749 bot
.msg(user
, "One match: %s" % (matches
[0]))
751 bot
.msg(user
, "No match.")
753 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
754 @lib.help("[@<category>] <qid>", "displays the q*a for a qid", "category defaults to current")
755 def showq(bot
, user
, chan
, realtarget
, *args
):
757 if args
[0].startswith("@"):
758 cat
= args
.pop(0)[1:].lower()
759 questions
= state
.db
['questions'][cat
]
761 questions
= state
.questions
766 bot
.msg(user
, "Specify a numeric question ID.")
771 bot
.msg(user
, "ID not valid.")
773 bot
.msg(user
, "%s: %s*%s" % (qid
, q
[0], q
[1]), True)
775 @lib.hook(('delq', 'deleteq'), glevel
=lib
.STAFF
, needchan
=False)
776 @lib.help("[@<category>] <qid>", "removes a question from the database")
777 def delq(bot
, user
, chan
, realtarget
, *args
):
779 if args
[0].startswith("@"):
780 cat
= args
.pop(0)[1:].lower()
781 questions
= state
.db
['questions'][cat
]
783 questions
= state
.questions
786 backup
= questions
[int(args
[0])]
787 del questions
[int(args
[0])]
788 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]), True)
789 except Exception as e
:
790 bot
.msg(user
, "Couldn't delete that question. %r" % (e
))
792 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
793 @lib.help("[@<category>] <q>*<a>", "adds a question")
794 def addq(bot
, user
, chan
, realtarget
, *args
):
796 if args
[0].startswith("@"):
797 cat
= args
.pop(0)[1:].lower()
798 questions
= state
.db
['questions'][cat
]
800 questions
= state
.questions
802 line
= ' '.join([str(arg
) for arg
in args
])
803 linepieces
= line
.split('*', 1)
804 if len(linepieces
) < 2:
805 bot
.msg(user
, "Error: need <question>*<answer>")
807 question
= linepieces
[0].strip()
808 answer
= linepieces
[1].strip()
809 questions
.append([question
, answer
])
810 bot
.msg(user
, "Done. Question is #%s" % (len(questions
)-1))
812 @lib.hook(needchan
=False)
813 @lib.help(None, "show current category")
814 def showcat(bot
, user
, chan
, realtarget
, *args
):
815 bot
.msg(user
, "Current category: %s" % (state
.db
['category']))
817 @lib.hook(glevel
=1, needchan
=False)
818 @lib.help("<category>", "change category")
819 def setcat(bot
, user
, chan
, realtarget
, *args
):
820 category
= args
[0].lower()
821 if category
in state
.db
['questions']:
822 state
.db
['category'] = category
823 state
.questions
= state
.db
['questions'][category
]
824 bot
.msg(user
, "Changed category to %s" % (category
))
826 bot
.msg(user
, "That category doesn't exist.")
828 @lib.hook(needchan
=False)
829 @lib.help(None, "list categories", "the current category will be marked with a *")
830 def listcats(bot
, user
, chan
, realtarget
, *args
):
831 cats
= ["%s%s (%d)" % ("*" if c
== state
.db
['category'] else "", c
, len(state
.db
['questions'][c
])) for c
in state
.db
['questions'].keys()]
832 bot
.msg(user
, "Categories: %s" % (', '.join(cats
)))
834 @lib.hook(glevel
=lib
.STAFF
, needchan
=False)
835 @lib.help("<category>", "adds an empty category")
836 def addcat(bot
, user
, chan
, realtarget
, *args
):
837 category
= args
[0].lower()
838 if category
not in state
.db
['questions']:
839 state
.db
['questions'][category
] = []
840 bot
.msg(user
, "Added category %s" % (category
))
842 bot
.msg(user
, "Category already exists.")
844 @lib.hook(glevel
=lib
.MANAGER
, needchan
=False)
845 @lib.help("<category>", "deletes an entire category")
846 def delcat(bot
, user
, chan
, realtarget
, *args
):
847 category
= args
[0].lower()
848 if category
== state
.db
['category']:
849 bot
.msg(user
, "Category currently in use!")
850 elif category
in state
.db
['questions']:
851 length
= len(state
.db
['questions'][category
])
852 del state
.db
['questions'][category
]
853 bot
.msg(user
, "Deleted category %s (%d questions)" % (category
, length
))
855 bot
.msg(user
, "Category does not exist.")
857 @lib.hook(needchan
=False)
858 def triviahelp(bot
, user
, chan
, realtarget
, *args
):
859 bot
.slowmsg(user
, "START")
860 bot
.slowmsg(user
, "TOP10")
861 bot
.slowmsg(user
, "POINTS [<user>]")
862 bot
.slowmsg(user
, "RANK [<user>]")
863 bot
.slowmsg(user
, "BADQ <reason> (include info to identify question)")
865 bot
.slowmsg(user
, "SKIP (KNOWN)")
866 bot
.slowmsg(user
, "STOP (KNOWN)")
867 bot
.slowmsg(user
, "FINDQ <full question> (KNOWN)")
868 bot
.slowmsg(user
, "FINDQRE <regex> (KNOWN)")
869 bot
.slowmsg(user
, "SETNEXTID <qid> (KNOWN)")
870 if user
.glevel
>= lib
.STAFF
:
871 bot
.slowmsg(user
, "GIVE <user> [<points>] (STAFF)")
872 bot
.slowmsg(user
, "SETNEXT <q>*<a> (STAFF)")
873 bot
.slowmsg(user
, "ADDQ <q>*<a> (STAFF)")
874 bot
.slowmsg(user
, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
875 bot
.slowmsg(user
, "SHOWQ <qid> (STAFF)")
876 bot
.slowmsg(user
, "BADQS (STAFF)")
877 bot
.slowmsg(user
, "CLEARBADQS (STAFF)")
878 bot
.slowmsg(user
, "DELBADQ <reportid> (STAFF)")
879 if user
.glevel
>= lib
.ADMIN
:
880 bot
.slowmsg(user
, "SETTARGET <points> (ADMIN)")
881 bot
.slowmsg(user
, "MAXMISSED <questions> (ADMIN)")
882 bot
.slowmsg(user
, "HINTTIMER <float seconds> (ADMIN)")
883 bot
.slowmsg(user
, "HINTNUM <hints> (ADMIN)")
884 bot
.slowmsg(user
, "QUESTIONPAUSE <float seconds> (ADMIN)")
886 @lib.hooknum(332) # topic is...
887 @lib.hooknum(331) # no topic set
888 def num_TOPIC(bot
, textline
):
889 pieces
= textline
.split(None, 4)
891 if chan
!= state
.db
['chan']:
893 gottopic
= pieces
[4][1:]
895 formatted
= state
.db
['topicformat'] % {
896 'chan': state
.db
['chan'],
897 'top1': "%s (%s)" % (person(0), pts(0)),
899 "%s (%s)" % (person(x
), pts(x
))
900 for x
in range(3) if x
< len(state
.db
['ranks'])
903 "%s (%s) %s" % (person(x
), country(x
), pts(x
))
904 for x
in range(3) if x
< len(state
.db
['ranks'])
907 "%s (%s)" % (person(x
), pts(x
))
908 for x
in range(10) if x
< len(state
.db
['ranks'])
911 "%s (%s, %s)" % (person(x
), pts(x
), country(x
))
912 for x
in range(10) if x
< len(state
.db
['ranks'])
914 'lastwinner': state
.db
['lastwinner'],
915 'lastwon': time
.strftime("%b %d", time
.gmtime(state
.db
['lastwon'])),
916 'target': state
.db
['target'],
917 'category': state
.db
['category'],
919 if gottopic
!= formatted
:
920 state
.getbot().conn
.send(bot
.parent
.cfg
.get('trivia', 'topiccommand', default
="TOPIC %(chan)s :%(topic)s") % {'chan': state.db['chan'], 'topic': formatted}
)
923 def specialQuestion(oldq
):
924 newq
= [oldq
[0], oldq
[1]]
925 qtype
= oldq
[0].upper()
927 if qtype
== "!MONTH":
928 newq
[0] = "What month is it currently (in UTC)?"
929 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
930 elif qtype
== "!MATH+":
932 maxnum
= int(oldq
[1])
935 randnum1
= random
.randrange(0, maxnum
+1)
936 randnum2
= random
.randrange(0, maxnum
+1)
937 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
938 newq
[1] = spellout(randnum1
+randnum2
)
939 elif qtype
== "!ALGEBRA+":
941 num1
, num2
= [int(i
) for i
in oldq
[1].split('!')]
944 randnum1
= random
.randrange(0, num1
+1)
945 randnum2
= random
.randrange(randnum1
, num2
+1)
946 newq
[0] = "What is x? %d = %d + x" % (randnum2
, randnum1
)
947 newq
[1] = spellout(randnum2
-randnum1
)
948 else: pass #default to not modifying
952 ones
= ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
953 teens
= ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
954 tens
= ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
959 ihundreds
= num
/ 100
960 itens
= num
% 100 / 10
965 buf
.append("%s hundred" % (ones
[ihundreds
]))
967 buf
.append(tens
[itens
])
969 buf
.append(teens
[iones
])
971 buf
.append(ones
[iones
])
974 # "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
975 # "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
976 # "sixteen", "seventeen", "eighteen", "nineteen", "twenty"