]> jfr.im git - erebus.git/blame - modules/trivia.py
rename run.sh to run
[erebus.git] / modules / trivia.py
CommitLineData
80d02bd8 1# Erebus IRC bot - Author: Erebus Team
c695f740 2# trivia module
80d02bd8 3# This file is released into the public domain; see http://unlicense.org/
4
a28e2ae9 5from __future__ import print_function
6
80d02bd8 7# module info
8modinfo = {
9 'author': 'Erebus Team',
10 'license': 'public domain',
fa93b933 11 'compatible': [0],
a62d0d18 12 'depends': ['userinfo'],
13 'softdeps': ['help'],
80d02bd8 14}
15
16# preamble
17import modlib
18lib = modlib.modlib(__name__)
19def modstart(parent, *args, **kwargs):
5871567f 20 state.gotParent(parent)
21 lib.hookchan(state.db['chan'])(trivia_checkanswer) # we need parent for this. so it goes here.
80d02bd8 22 return lib.modstart(parent, *args, **kwargs)
23def modstop(*args, **kwargs):
c0eee1b4 24 global state
8ef938d0 25 try:
26 stop()
27 state.closeshop()
28 del state
29 except Exception: pass
80d02bd8 30 return lib.modstop(*args, **kwargs)
31
32# module code
a28e2ae9 33import json, random, threading, re, time, datetime, os, sys
34
35if sys.version_info.major < 3:
36 timerbase = threading._Timer
37else:
38 timerbase = threading.Timer
39
b16b8c05 40
c0eee1b4 41try:
be8072b5 42 import twitter
c53f6514 43except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
c0eee1b4 44
b16b8c05 45def findnth(haystack, needle, n): #http://stackoverflow.com/a/1884151
46 parts = haystack.split(needle, n+1)
47 if len(parts)<=n+1:
48 return -1
49 return len(haystack)-len(parts[-1])-len(needle)
80d02bd8 50
00ccae72 51def person(num, throwindexerror=False):
52 try:
53 return state.db['users'][state.db['ranks'][num]]['realnick']
54 except IndexError:
55 if throwindexerror:
56 raise
57 else:
58 return ''
59
3b89ebff 60def pts(num):
00ccae72 61 try:
62 return str(state.db['users'][state.db['ranks'][num]]['points'])
63 except IndexError:
64 return 0
2bb267e0 65
00ccae72 66def country(num, default="??"):
2bb267e0 67 return lib.mod('userinfo')._get(person(num), 'country', default=default).upper()
8ef938d0 68
a28e2ae9 69class MyTimer(timerbase):
be8072b5 70 def __init__(self, *args, **kwargs):
a28e2ae9 71 timerbase.__init__(self, *args, **kwargs)
be8072b5 72 self.daemon = True
73
80d02bd8 74class TriviaState(object):
5871567f 75 def __init__(self, parent=None, pointvote=False):
76 if parent is not None:
77 self.gotParent(parent, pointvote)
78
79 def gotParent(self, parent, pointvote=False):
bf8676ae 80 self.parent = parent
81 self.questionfile = self.parent.cfg.get('trivia', 'jsonpath', default="./modules/trivia.json")
82 self.db = json.load(open(self.questionfile, "r"))
8ad3a154 83 self.questions = self.db['questions'][self.db['category']]
bf8676ae 84 self.chan = self.db['chan']
85 self.curq = None
86 self.nextq = None
656dc5a4 87 self.nextqid = None
bf8676ae 88 self.nextquestiontimer = None
89 self.steptimer = None
90 self.hintstr = None
91 self.hintanswer = None
92 self.hintsgiven = 0
b16b8c05 93 self.revealpossibilities = None
bf8676ae 94 self.gameover = False
95 self.missedquestions = 0
96 self.curqid = None
97 self.lastqid = None
80d02bd8 98
00ccae72 99 if 'lastwon' not in self.db or self.db['lastwon'] is None:
100 self.db['lastwon'] = time.time()
7bd5e7d5 101
c53f6514 102 if pointvote:
103 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']])))
104 self.getchan().msg("You have %s seconds." % (self.db['votetimer']))
105 self.voteamounts = dict([(x, 0) for x in self.db['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
be8072b5 106 self.pointvote = MyTimer(self.db['votetimer'], self.endPointVote)
c53f6514 107 self.pointvote.start()
108 else:
109 self.pointvote = None
110
8770f6ef 111# def __del__(self):
112# self.closeshop()
77c61775 113 def closeshop(self):
2bb487be 114 try:
115 self.steptimer.cancel()
116 self.steptimer = None
117 except: pass
118 try:
119 self.nextquestiontimer.cancel()
120 self.nextquestiontimer = None
121 except: pass
b9daa51a 122
67faf5d7 123 def savedb(self): #returns whether or not it was able to save
c695f740 124 if json is not None and json.dump is not None:
67faf5d7 125# json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
126 dbjson = json.dumps(self.db)
127 if len(dbjson) > 0:
3f04e466 128 os.rename(self.questionfile, self.questionfile+".auto.bak")
67faf5d7 129 tmpfn = os.tempnam('.', 'trivia')
130 try:
131 f = open(tmpfn, "w")
132 f.write(dbjson)
133 f.close()
134 os.rename(tmpfn, self.questionfile)
135 return True
136 except: #if something happens, restore the backup
3f04e466 137 os.rename(self.questionfile+".auto.bak", self.questionfile)
67faf5d7 138 try:
139 os.unlink(tmpfn)
140 except OSError: # temp file is already gone
141 pass
f5f2b592 142 raise # we may be better off just swallowing exceptions?
67faf5d7 143 return False
80d02bd8 144
fadbf980 145 def getchan(self):
146 return self.parent.channel(self.chan)
147 def getbot(self):
148 return self.getchan().bot
149
b16b8c05 150 def nexthint(self, hintnum):
b16b8c05 151 answer = self.hintanswer
152
b5c89dfb 153 if self.hintstr is None or self.revealpossibilities is None or self.reveal is None:
93ce52fd 154 oldhintstr = ""
b16b8c05 155 self.hintstr = list(re.sub(r'[a-zA-Z0-9]', '*', answer))
156 self.revealpossibilities = range(''.join(self.hintstr).count('*'))
93ce52fd 157 self.reveal = int(round(''.join(self.hintstr).count('*') * (7/24.0)))
158 else:
159 oldhintstr = ''.join(self.hintstr)
b16b8c05 160
b5c89dfb 161 for i in range(self.reveal):
b16b8c05 162 revealcount = random.choice(self.revealpossibilities)
163 revealloc = findnth(''.join(self.hintstr), '*', revealcount)
164 self.revealpossibilities.remove(revealcount)
165 self.hintstr[revealloc] = answer[revealloc]
2bb267e0 166 if oldhintstr != ''.join(self.hintstr): self.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self.hintstr)))
b16b8c05 167
77c61775 168 self.hintsgiven += 1
169
c4763e66 170 if hintnum < self.db['hintnum']:
be8072b5 171 self.steptimer = MyTimer(self.db['hinttimer'], self.nexthint, args=[hintnum+1])
b16b8c05 172 self.steptimer.start()
173 else:
be8072b5 174 self.steptimer = MyTimer(self.db['hinttimer'], self.nextquestion, args=[True])
b16b8c05 175 self.steptimer.start()
176
77c61775 177 def doGameOver(self):
7bd5e7d5 178 msg = self.getchan().msg
c0eee1b4 179 winner = person(0)
77c61775 180 try:
181 msg("\00312THE GAME IS OVER!!!")
00ccae72 182 msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0)))
183 msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1)))
184 msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2)))
185 [msg("%dth place: %s (%s)" % (i+1, person(i, True), pts(i))) for i in range(3,10)]
77c61775 186 except IndexError: pass
09566235 187 except Exception as e:
188 msg("DERP! %r" % (e))
c0eee1b4 189
5f42c250 190 self.db['lastwinner'] = winner
191 self.db['lastwon'] = time.time()
192
7bd5e7d5 193 if self.db['hofpath'] is not None and self.db['hofpath'] != '':
194 self.writeHof()
195
77c61775 196 self.db['users'] = {}
197 self.db['ranks'] = []
198 stop()
199 self.closeshop()
c0eee1b4 200
c53f6514 201 try:
c0eee1b4 202 t = twitter.Twitter(auth=twitter.OAuth(self.getbot().parent.cfg.get('trivia', 'token'),
203 self.getbot().parent.cfg.get('trivia', 'token_sec'),
204 self.getbot().parent.cfg.get('trivia', 'con'),
205 self.getbot().parent.cfg.get('trivia', 'con_sec')))
206 t.statuses.update(status="Round is over! The winner was %s" % (winner))
c53f6514 207 except: pass #don't care if errors happen updating twitter.
208
5871567f 209 self.__init__(self.parent, True)
c53f6514 210
7bd5e7d5 211 def writeHof(self):
212 def person(num):
213 try: return self.db['users'][self.db['ranks'][num]]['realnick']
214 except: return "none"
215 def pts(num):
216 try: return str(self.db['users'][self.db['ranks'][num]]['points'])
217 except: return 0
218
aaf381b8 219 status = False
7bd5e7d5 220 try:
221 f = open(self.db['hofpath'], 'rb+')
222 for i in range(self.db['hoflines']): #skip this many lines
223 f.readline()
224 insertpos = f.tell()
225 fcontents = f.read()
226 f.seek(insertpos)
227 f.write((self.db['hofformat']+"\n") % {
228 'date': time.strftime("%F", time.gmtime()),
00ccae72 229 'duration': str(datetime.timedelta(seconds=time.time()-self.db['lastwon'])),
7bd5e7d5 230 'targetscore': self.db['target'],
231 'firstperson': person(0),
232 'firstscore': pts(0),
233 'secondperson': person(1),
234 'secondscore': pts(1),
235 'thirdperson': person(2),
236 'thirdscore': pts(2),
237 })
238 f.write(fcontents)
aaf381b8 239 status = True
7bd5e7d5 240 except Exception as e:
aaf381b8 241 status = False
7bd5e7d5 242 finally:
243 f.close()
aaf381b8 244 return status
7bd5e7d5 245
c53f6514 246 def endPointVote(self):
247 self.getchan().msg("Voting has ended!")
248 votelist = sorted(self.voteamounts.items(), key=lambda item: item[1]) #sort into list of tuples: [(option, number_of_votes), ...]
249 for i in range(len(votelist)-1):
250 item = votelist[i]
251 self.getchan().msg("%s place: %s (%s votes)" % (len(votelist)-i, item[0], item[1]))
252 self.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist[-1][0], votelist[-1][1]))
c0eee1b4 253
c53f6514 254 self.db['target'] = votelist[-1][0]
255 self.pointvote = None
77c61775 256
38b29993 257 self.nextquestion() #start the game!
258
442ed923 259 def nextquestion(self, qskipped=False, iteration=0, skipwait=False):
7b832b55 260 self.lastqid = self.curqid
6bdfec48 261 self.curq = None
7b832b55 262 self.curqid = None
77c61775 263 if self.gameover == True:
264 return self.doGameOver()
fadbf980 265 if qskipped:
be8072b5 266 self.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self.hintanswer))
c0eee1b4 267 self.missedquestions += 1
268 else:
269 self.missedquestions = 0
f8cc0124 270 if 'topicformat' in self.db and self.db['topicformat'] is not None:
271 self.getbot().conn.send("TOPIC %s" % (self.db['chan']))
fadbf980 272
9138aa03 273 if isinstance(self.steptimer, MyTimer):
b16b8c05 274 self.steptimer.cancel()
9138aa03 275 if isinstance(self.nextquestiontimer, MyTimer):
442ed923 276 self.nextquestiontimer.cancel()
277 self.nextquestiontimer = None
c0eee1b4 278
b16b8c05 279 self.hintstr = None
77c61775 280 self.hintsgiven = 0
b16b8c05 281 self.revealpossibilities = None
b5c89dfb 282 self.reveal = None
b16b8c05 283
af349654 284 self.savedb()
285
c4763e66 286 if self.missedquestions > self.db['maxmissedquestions']:
c0eee1b4 287 stop()
ce03ceda 288 self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game." % (self.missedquestions))
289 return
b16b8c05 290
442ed923 291 if skipwait:
6bdfec48 292 self._nextquestion(iteration)
442ed923 293 else:
be8072b5 294 self.nextquestiontimer = MyTimer(self.db['questionpause'], self._nextquestion, args=[iteration])
442ed923 295 self.nextquestiontimer.start()
296
6bdfec48 297 def _nextquestion(self, iteration):
e5a3970b 298 if self.nextq is not None:
2520caee 299 nextqid = None
e5a3970b 300 nextq = self.nextq
301 self.nextq = None
656dc5a4 302 elif self.nextqid is not None:
303 nextqid = self.nextqid
304 nextq = self.questions[nextqid]
305 self.nextqid = None
c695f740 306 else:
8ad3a154 307 nextqid = random.randrange(0, len(self.questions))
308 nextq = self.questions[nextqid]
b5c89dfb 309
fd07173d 310 if nextq[0].startswith("!"):
2520caee 311 nextqid = None
b5c89dfb 312 nextq = specialQuestion(nextq)
313
aa0e4be4 314 if len(nextq) > 2 and time.time() - nextq[2] < 7*24*60*60 and iteration < 10:
442ed923 315 return self._nextquestion(iteration=iteration+1) #short-circuit to pick another question
ebee6edb 316 if len(nextq) > 2:
317 nextq[2] = time.time()
318 else:
319 nextq.append(time.time())
b5c89dfb 320
93ce52fd 321 if isinstance(nextq[1], basestring):
322 nextq[1] = nextq[1].lower()
323 else:
324 nextq[1] = [s.lower() for s in nextq[1]]
c695f740 325
00ccae72 326 qtext = "\00312,01Next up: "
bf8676ae 327 qtext += "(%5d)" % (random.randint(0,99999))
ebee6edb 328 qary = nextq[0].split(None)
71e0b5fb 329 qtext += " "
c695f740 330 for qword in qary:
af349654 331 spacer = random.choice(
332 range(0x61,0x7A) + ([0x20]*4)
333 )
334 qtext += "\00304,01"+qword+"\00301,01"+chr(spacer) #a-z
656dc5a4 335 if not self.getbot().fastmsg(self.chan, qtext): #if message is too long:
336 if nextqid is None: nextqid = "manual"
337 self.getbot().slowmsg(self.chan, "(Unable to ask question #%s: line too long)" % (nextqid))
338 return self._nextquestion(iteration) #retry; don't increment the iteration
80d02bd8 339
b5c89dfb 340 self.curq = nextq
7b832b55 341 self.curqid = nextqid
b5c89dfb 342
ebee6edb 343 if isinstance(self.curq[1], basestring): self.hintanswer = self.curq[1]
344 else: self.hintanswer = random.choice(self.curq[1])
c0eee1b4 345
be8072b5 346 self.steptimer = MyTimer(self.db['hinttimer'], self.nexthint, args=[1])
b16b8c05 347 self.steptimer.start()
348
80d02bd8 349 def checkanswer(self, answer):
9557ee54 350 if self.curq is None:
351 return False
ebee6edb 352 elif isinstance(self.curq[1], basestring):
353 return answer.lower() == self.curq[1]
80d02bd8 354 else: # assume it's a list or something.
ebee6edb 355 return answer.lower() in self.curq[1]
77c61775 356
c53f6514 357 def addpoint(self, user_obj, count=1):
358 user_nick = str(user_obj)
359 user = user_nick.lower() # save this separately as we use both
80d02bd8 360 if user in self.db['users']:
361 self.db['users'][user]['points'] += count
362 else:
c53f6514 363 self.db['users'][user] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
9557ee54 364 self.db['ranks'].append(user)
80d02bd8 365
e5a3970b 366 self.db['ranks'].sort(key=lambda nick: self.db['users'][nick]['points'], reverse=True) #re-sort ranks, rather than dealing with anything more efficient
6374d61f 367 for i in range(0, len(self.db['ranks'])):
368 nick = self.db['ranks'][i]
369 self.db['users'][nick]['rank'] = i
77c61775 370
e5a3970b 371 if self.db['users'][user]['points'] >= self.db['target']:
77c61775 372 self.gameover = True
373
80d02bd8 374 return self.db['users'][user]['points']
375
376 def points(self, user):
9557ee54 377 user = str(user).lower()
80d02bd8 378 if user in self.db['users']:
379 return self.db['users'][user]['points']
380 else:
381 return 0
382
383 def rank(self, user):
c695f740 384 user = str(user).lower()
fadbf980 385 if user in self.db['users']:
386 return self.db['users'][user]['rank']+1
387 else:
388 return len(self.db['users'])+1
77c61775 389
c695f740 390 def targetuser(self, user):
77c61775 391 if len(self.db['ranks']) == 0: return "no one is ranked!"
392
c695f740 393 user = str(user).lower()
fadbf980 394 if user in self.db['users']:
395 rank = self.db['users'][user]['rank']
396 if rank == 0:
397 return "you're in the lead!"
398 else:
399 return self.db['ranks'][rank-1]
c695f740 400 else:
fadbf980 401 return self.db['ranks'][-1]
c695f740 402 def targetpoints(self, user):
77c61775 403 if len(self.db['ranks']) == 0: return 0
404
c695f740 405 user = str(user).lower()
fadbf980 406 if user in self.db['users']:
407 rank = self.db['users'][user]['rank']
408 if rank == 0:
af349654 409 return ""
fadbf980 410 else:
af349654 411 return "("+str(self.db['users'][self.db['ranks'][rank-1]]['points'])+")"
c695f740 412 else:
af349654 413 return "("+str(self.db['users'][self.db['ranks'][-1]]['points'])+")"
80d02bd8 414
5871567f 415state = TriviaState()
9557ee54 416
5871567f 417# we have to hook this in modstart, since we don't know the channel until then.
80d02bd8 418def trivia_checkanswer(bot, user, chan, *args):
80d02bd8 419 line = ' '.join([str(arg) for arg in args])
420 if state.checkanswer(line):
6bdfec48 421 state.curq = None
93ce52fd 422 if state.hintanswer.lower() == line.lower():
af349654 423 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)))
93ce52fd 424 else:
af349654 425 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)))
77c61775 426 if state.hintsgiven == 0:
6374d61f 427 bot.msg(chan, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user)))
9557ee54 428 state.nextquestion()
80d02bd8 429
f5aec865 430@lib.hook(glevel=1, needchan=False, wantchan=True)
67faf5d7 431@lib.help(None, "saves the trivia database")
432def save(bot, user, chan, realtarget, *args):
f5aec865 433 if chan is not None: replyto = chan
67faf5d7 434 else: replyto = user
435
436 if state.savedb():
437 bot.msg(replyto, "Save successful.")
438 else:
439 bot.msg(replyto, "Save failed!")
440
f5aec865 441@lib.hook(needchan=False, wantchan=True)
5f03d045 442@lib.help("[<user>]", "shows how many points you or someone has")
fb20be7c 443def points(bot, user, chan, realtarget, *args):
f5aec865 444 if chan is not None: eplyto = chan
80d02bd8 445 else: replyto = user
446
447 if len(args) != 0: who = args[0]
448 else: who = user
449
450 bot.msg(replyto, "%s has %d points." % (who, state.points(who)))
451
fb20be7c 452@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 453@lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
80d02bd8 454@lib.argsGE(1)
fb20be7c 455def give(bot, user, chan, realtarget, *args):
80d02bd8 456 whoto = args[0]
c695f740 457 if len(args) > 1:
458 numpoints = int(args[1])
459 else:
460 numpoints = 1
461 balance = state.addpoint(whoto, numpoints)
fadbf980 462
c695f740 463 bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance))
464
fb20be7c 465@lib.hook(glevel=1, needchan=False)
5f03d045 466@lib.help("<qid>", "sets next question to one in the database")
467@lib.argsEQ(1)
fb20be7c 468def setnextid(bot, user, chan, realtarget, *args):
9306587e 469 try:
470 qid = int(args[0])
656dc5a4 471 except ValueError:
472 bot.msg(user, "Error: QID must be a number.")
473 return
474 if qid >= len(state.questions):
475 bot.msg(user, "Error: no such QID.")
476 return
477 state.nextqid = qid
478 bot.msg(user, "Done. Next question is %d: %s" % (qid, state.questions[qid][0]))
9306587e 479
fb20be7c 480@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 481@lib.help("<q>*<a>", "sets next question to one not in database")
c695f740 482@lib.argsGE(1)
fb20be7c 483def setnext(bot, user, chan, realtarget, *args):
c695f740 484 line = ' '.join([str(arg) for arg in args])
aa0e4be4 485 linepieces = line.split('*', 1)
b5c89dfb 486 if len(linepieces) < 2:
487 bot.msg(user, "Error: need <question>*<answer>")
488 return
c695f740 489 question = linepieces[0].strip()
490 answer = linepieces[1].strip()
ebee6edb 491 state.nextq = [question, answer]
c695f740 492 bot.msg(user, "Done.")
493
fb20be7c 494@lib.hook(glevel=1, needchan=False)
5f03d045 495@lib.help(None, "skips to next question")
fb20be7c 496def skip(bot, user, chan, realtarget, *args):
442ed923 497 state.nextquestion(qskipped=True, skipwait=True)
c695f740 498
f5aec865 499@lib.hook(needchan=False, wantchan=True)
5f03d045 500@lib.help(None, "starts the trivia game")
fb20be7c 501def start(bot, user, chan, realtarget, *args):
f5aec865 502 if chan is not None: replyto = chan
c695f740 503 else: replyto = user
504
77a265cd 505 if chan is not None and chan.name != state.db['chan']:
506 bot.msg(replyto, "That command isn't valid here.")
507 return
508
442ed923 509 if state.curq is None and state.pointvote is None and state.nextquestiontimer is None:
77a265cd 510 bot.msg(state.db['chan'], "%s has started the game!" % (user))
442ed923 511 state.nextquestion(skipwait=True)
c53f6514 512 elif state.pointvote is not None:
00ccae72 513 bot.msg(user, "There's a vote in progress!")
c695f740 514 else:
00ccae72 515 bot.msg(user, "Game is already started!")
c695f740 516
9306587e 517@lib.hook('stop', glevel=1, needchan=False)
5f03d045 518@lib.help(None, "stops the trivia game")
c695f740 519def cmd_stop(bot, user, chan, realtarget, *args):
fadbf980 520 if stop():
521 bot.msg(state.chan, "Game stopped by %s" % (user))
522 else:
523 bot.msg(user, "Game isn't running.")
c695f740 524
fadbf980 525def stop():
3b89ebff 526 state.curq = None
527 state.nextq = None
09566235 528 try:
529 state.steptimer.cancel()
530 except Exception as e:
a28e2ae9 531 print("!!! steptimer.cancel(): %s %r" % (e,e))
3b89ebff 532 state.steptimer = None
09566235 533 try:
534 state.nextquestiontimer.cancel()
535 except Exception as e:
a28e2ae9 536 print("!!! nextquestiontimer.cancel(): %s %r" % (e,e))
3b89ebff 537 state.nextquestiontimer = None
538 return True
80d02bd8 539
fb20be7c 540@lib.hook(needchan=False)
5f03d045 541@lib.help("<reason>", "reports a bad question to the admins")
7b832b55 542@lib.argsGE(1)
fb20be7c 543def badq(bot, user, chan, realtarget, *args):
7b832b55 544 lastqid = state.lastqid
545 curqid = state.curqid
546
547 reason = ' '.join(args)
8ad3a154 548 state.db['badqs'].append([state.db['category'], lastqid, curqid, reason])
7b832b55 549 bot.msg(user, "Reported bad question.")
2520caee 550
fb20be7c 551@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 552@lib.help(None, "shows a list of BADQ reports")
fb20be7c 553def badqs(bot, user, chan, realtarget, *args):
2520caee 554 if len(state.db['badqs']) == 0:
555 bot.msg(user, "No reports.")
556
557 for i in range(len(state.db['badqs'])):
558 try:
559 report = state.db['badqs'][i]
8ad3a154 560 bot.msg(user, "Report #%d: Cat=%s LastQ=%r CurQ=%r: %s" % (i, report[0], report[1], report[2], report[3]))
561 try: lq = state.db['questions'][report[0]][int(report[1])]
7b832b55 562 except Exception as e: lq = (None,None)
8ad3a154 563 try: cq = state.db['questions'][report[0]][int(report[2])]
7b832b55 564 except Exception as e: cq = (None, None)
565 bot.msg(user, "- Last: %s*%s" % (lq[0], lq[1]))
566 bot.msg(user, "- Curr: %s*%s" % (cq[0], cq[1]))
2520caee 567 except Exception as e:
568 bot.msg(user, "- Exception: %r" % (e))
569
fb20be7c 570@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 571@lib.hook(None, "clears list of BADQ reports")
fb20be7c 572def clearbadqs(bot, user, chan, realtarget, *args):
2520caee 573 state.db['badqs'] = []
574 bot.msg(user, "Cleared reports.")
575
fb20be7c 576@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 577@lib.hook("<badqid>", "removes a BADQ report")
2520caee 578@lib.argsEQ(1)
fb20be7c 579def delbadq(bot, user, chan, realtarget, *args):
4d98501a 580 try:
581 qid = int(args[0])
582 del state.db['badqs'][qid]
4d98501a 583 bot.msg(user, "Removed report #%d" % (qid))
584 except:
585 bot.msg(user, "Failed!")
2520caee 586
f5aec865 587@lib.hook(needchan=False, wantchan=True)
5f03d045 588@lib.help("[<user>]", "shows you or someone else's rank")
fb20be7c 589def rank(bot, user, chan, realtarget, *args):
f5aec865 590 if chan is not None: replyto = chan
80d02bd8 591 else: replyto = user
592
c695f740 593 if len(args) != 0: who = args[0]
594 else: who = user
595
af349654 596 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)))
fadbf980 597
fb20be7c 598@lib.hook(needchan=False)
5f03d045 599@lib.help(None, "shows top10 list")
fb20be7c 600def top10(bot, user, chan, realtarget, *args):
77c61775 601 if len(state.db['ranks']) == 0:
602 return bot.msg(state.db['chan'], "No one is ranked!")
fadbf980 603
8ef938d0 604 max = len(state.db['ranks'])
605 if max > 10:
606 max = 10
2bb267e0 607 replylist = ', '.join(["%s (%s) %s" % (person(x), country(x), pts(x)) for x in range(max)])
00ccae72 608 bot.msg(state.db['chan'], "Top 10: %s" % (replylist))
77c61775 609
fb20be7c 610@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 611@lib.help("<target score>", "changes the target score for this round")
fb20be7c 612def settarget(bot, user, chan, realtarget, *args):
77c61775 613 try:
614 state.db['target'] = int(args[0])
615 bot.msg(state.db['chan'], "Target has been changed to %s points!" % (state.db['target']))
38b29993 616
7bd5e7d5 617 if state.pointvote is not None:
618 state.pointvote.cancel()
619 state.pointvote = None
38b29993 620 bot.msg(state.db['chan'], "Vote has been cancelled!")
7bd5e7d5 621 except Exception as e:
a28e2ae9 622 print(e)
77c61775 623 bot.msg(user, "Failed to set target.")
624
fb20be7c 625@lib.hook(needchan=False)
5f03d045 626@lib.help("<option>", "votes for a trarget score for next round")
fb20be7c 627def vote(bot, user, chan, realtarget, *args):
7bd5e7d5 628 if state.pointvote is not None:
38b29993 629 if int(args[0]) in state.voteamounts:
630 state.voteamounts[int(args[0])] += 1
631 bot.msg(user, "Your vote has been recorded.")
632 else:
633 bot.msg(user, "Sorry - that's not an option!")
634 else:
635 bot.msg(user, "There's no vote in progress.")
636
fb20be7c 637@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 638@lib.help("<number>", "sets the max missed question before game stops")
fb20be7c 639def maxmissed(bot, user, chan, realtarget, *args):
c4763e66 640 try:
641 state.db['maxmissedquestions'] = int(args[0])
642 bot.msg(state.db['chan'], "Max missed questions before round ends has been changed to %s." % (state.db['maxmissedquestions']))
643 except:
644 bot.msg(user, "Failed to set maxmissed.")
645
fb20be7c 646@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 647@lib.help("<seconds>", "sets the time between hints")
fb20be7c 648def hinttimer(bot, user, chan, realtarget, *args):
c4763e66 649 try:
650 state.db['hinttimer'] = float(args[0])
651 bot.msg(state.db['chan'], "Time between hints has been changed to %s." % (state.db['hinttimer']))
652 except:
653 bot.msg(user, "Failed to set hint timer.")
654
fb20be7c 655@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 656@lib.help("<number>", "sets the number of hints given")
fb20be7c 657def hintnum(bot, user, chan, realtarget, *args):
c4763e66 658 try:
659 state.db['hintnum'] = int(args[0])
660 bot.msg(state.db['chan'], "Max number of hints has been changed to %s." % (state.db['hintnum']))
661 except:
662 bot.msg(user, "Failed to set hintnum.")
663
fb20be7c 664@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 665@lib.help("<seconds>", "sets the pause between questions")
fb20be7c 666def questionpause(bot, user, chan, realtarget, *args):
442ed923 667 try:
668 state.db['questionpause'] = float(args[0])
669 bot.msg(state.db['chan'], "Pause between questions has been changed to %s." % (state.db['questionpause']))
670 except:
671 bot.msg(user, "Failed to set questionpause.")
672
fb20be7c 673@lib.hook(glevel=1, needchan=False)
5f03d045 674@lib.help("<full question>", "finds a qid given a complete question")
fb20be7c 675def findq(bot, user, chan, realtarget, *args):
8ad3a154 676 args = list(args)
fd07173d 677 if args[0].startswith("@"):
8ad3a154 678 cat = args.pop(0)[1:].lower()
679 questions = state.db['questions'][cat]
680 else:
681 questions = state.questions
682
4d98501a 683 if len(args) == 0:
684 bot.msg(user, "You need to specify the question.")
685 return
686
687 searchkey = ' '.join(args).lower()
8ad3a154 688 matches = [str(i) for i in range(len(questions)) if questions[i][0].lower() == searchkey]
4d98501a 689 if len(matches) > 1:
690 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
691 elif len(matches) == 1:
692 bot.msg(user, "One match: %s" % (matches[0]))
693 else:
694 bot.msg(user, "No match.")
695
696@lib.hook(glevel=1, needchan=False)
8ad3a154 697@lib.help("[@<category>] <regex>", "finds a qid given a regex or partial question")
4d98501a 698def findqre(bot, user, chan, realtarget, *args):
8ad3a154 699 args = list(args)
fd07173d 700 if args[0].startswith("@"):
8ad3a154 701 cat = args.pop(0)[1:].lower()
702 questions = state.db['questions'][cat]
703 else:
704 questions = state.questions
705
bf8676ae 706 if len(args) == 0:
707 bot.msg(user, "You need to specify a search string.")
708 return
709
4d98501a 710 searcher = re.compile(' '.join(args), re.IGNORECASE)
8ad3a154 711 matches = [str(i) for i in range(len(questions)) if searcher.search(questions[i][0]) is not None]
bf8676ae 712 if len(matches) > 25:
713 bot.msg(user, "Too many matches! (>25)")
714 elif len(matches) > 1:
c4763e66 715 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
716 elif len(matches) == 1:
717 bot.msg(user, "One match: %s" % (matches[0]))
718 else:
719 bot.msg(user, "No match.")
720
b9daa51a 721@lib.hook(glevel=lib.STAFF, needchan=False)
8ad3a154 722@lib.help("[@<category>] <qid>", "displays the q*a for a qid", "category defaults to current")
b9daa51a 723def showq(bot, user, chan, realtarget, *args):
8ad3a154 724 args = list(args)
fd07173d 725 if args[0].startswith("@"):
8ad3a154 726 cat = args.pop(0)[1:].lower()
727 questions = state.db['questions'][cat]
728 else:
729 questions = state.questions
730
b9daa51a 731 try:
732 qid = int(args[0])
733 except:
734 bot.msg(user, "Specify a numeric question ID.")
735 return
736 try:
8ad3a154 737 q = questions[qid]
b9daa51a 738 except:
739 bot.msg(user, "ID not valid.")
740 return
741 bot.msg(user, "%s: %s*%s" % (qid, q[0], q[1]))
742
fb20be7c 743@lib.hook(('delq', 'deleteq'), glevel=lib.STAFF, needchan=False)
8ad3a154 744@lib.help("[@<category>] <qid>", "removes a question from the database")
fb20be7c 745def delq(bot, user, chan, realtarget, *args):
8ad3a154 746 args = list(args)
fd07173d 747 if args[0].startswith("@"):
8ad3a154 748 cat = args.pop(0)[1:].lower()
749 questions = state.db['questions'][cat]
750 else:
751 questions = state.questions
752
c4763e66 753 try:
8ad3a154 754 backup = questions[int(args[0])]
755 del questions[int(args[0])]
ebee6edb 756 bot.msg(user, "Deleted %s*%s" % (backup[0], backup[1]))
c4763e66 757 except:
b9daa51a 758 bot.msg(user, "Couldn't delete that question. %r" % (e))
c4763e66 759
fb20be7c 760@lib.hook(glevel=lib.STAFF, needchan=False)
8ad3a154 761@lib.help("[@<category>] <q>*<a>", "adds a question")
fb20be7c 762def addq(bot, user, chan, realtarget, *args):
8ad3a154 763 args = list(args)
fd07173d 764 if args[0].startswith("@"):
8ad3a154 765 cat = args.pop(0)[1:].lower()
766 questions = state.db['questions'][cat]
767 else:
768 questions = state.questions
769
c4763e66 770 line = ' '.join([str(arg) for arg in args])
aa0e4be4 771 linepieces = line.split('*', 1)
c4763e66 772 if len(linepieces) < 2:
773 bot.msg(user, "Error: need <question>*<answer>")
774 return
775 question = linepieces[0].strip()
776 answer = linepieces[1].strip()
8ad3a154 777 questions.append([question, answer])
778 bot.msg(user, "Done. Question is #%s" % (len(questions)-1))
c4763e66 779
8770f6ef 780@lib.hook(needchan=False)
781@lib.help(None, "show current category")
782def showcat(bot, user, chan, realtarget, *args):
783 bot.msg(user, "Current category: %s" % (state.db['category']))
784
8ad3a154 785@lib.hook(glevel=1, needchan=False)
786@lib.help("<category>", "change category")
787def setcat(bot, user, chan, realtarget, *args):
788 category = args[0].lower()
789 if category in state.db['questions']:
790 state.db['category'] = category
791 state.questions = state.db['questions'][category]
792 bot.msg(user, "Changed category to %s" % (category))
793 else:
794 bot.msg(user, "That category doesn't exist.")
795
796@lib.hook(needchan=False)
8770f6ef 797@lib.help(None, "list categories", "the current category will be marked with a *")
8ad3a154 798def listcats(bot, user, chan, realtarget, *args):
8770f6ef 799 cats = ["%s%s (%d)" % ("*" if c == state.db['category'] else "", c, len(state.db['questions'][c])) for c in state.db['questions'].keys()]
8ad3a154 800 bot.msg(user, "Categories: %s" % (', '.join(cats)))
801
802@lib.hook(glevel=lib.STAFF, needchan=False)
803@lib.help("<category>", "adds an empty category")
804def addcat(bot, user, chan, realtarget, *args):
805 category = args[0].lower()
806 if category not in state.db['questions']:
807 state.db['questions'][category] = []
808 bot.msg(user, "Added category %s" % (category))
809 else:
810 bot.msg(user, "Category already exists.")
811
812@lib.hook(glevel=lib.MANAGER, needchan=False)
813@lib.help("<category>", "deletes an entire category")
814def delcat(bot, user, chan, realtarget, *args):
815 category = args[0].lower()
816 if category == state.db['category']:
817 bot.msg(user, "Category currently in use!")
818 elif category in state.db['questions']:
819 length = len(state.db['questions'][category])
820 del state.db['questions'][category]
821 bot.msg(user, "Deleted category %s (%d questions)" % (category, length))
822 else:
823 bot.msg(user, "Category does not exist.")
c4763e66 824
fb20be7c 825@lib.hook(needchan=False)
826def triviahelp(bot, user, chan, realtarget, *args):
2bb267e0 827 bot.slowmsg(user, "START")
828 bot.slowmsg(user, "TOP10")
829 bot.slowmsg(user, "POINTS [<user>]")
830 bot.slowmsg(user, "RANK [<user>]")
831 bot.slowmsg(user, "BADQ <reason> (include info to identify question)")
9306587e 832 if user.glevel >= 1:
b9daa51a 833 bot.slowmsg(user, "SKIP (KNOWN)")
834 bot.slowmsg(user, "STOP (KNOWN)")
4d98501a 835 bot.slowmsg(user, "FINDQ <full question> (KNOWN)")
836 bot.slowmsg(user, "FINDQRE <regex> (KNOWN)")
b9daa51a 837 bot.slowmsg(user, "SETNEXTID <qid> (KNOWN)")
9306587e 838 if user.glevel >= lib.STAFF:
b9daa51a 839 bot.slowmsg(user, "GIVE <user> [<points>] (STAFF)")
840 bot.slowmsg(user, "SETNEXT <q>*<a> (STAFF)")
841 bot.slowmsg(user, "ADDQ <q>*<a> (STAFF)")
842 bot.slowmsg(user, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
843 bot.slowmsg(user, "SHOWQ <qid> (STAFF)")
844 bot.slowmsg(user, "BADQS (STAFF)")
845 bot.slowmsg(user, "CLEARBADQS (STAFF)")
846 bot.slowmsg(user, "DELBADQ <reportid> (STAFF)")
9306587e 847 if user.glevel >= lib.ADMIN:
b9daa51a 848 bot.slowmsg(user, "SETTARGET <points> (ADMIN)")
849 bot.slowmsg(user, "MAXMISSED <questions> (ADMIN)")
850 bot.slowmsg(user, "HINTTIMER <float seconds> (ADMIN)")
851 bot.slowmsg(user, "HINTNUM <hints> (ADMIN)")
852 bot.slowmsg(user, "QUESTIONPAUSE <float seconds> (ADMIN)")
b5c89dfb 853
f8cc0124 854@lib.hooknum(332)
855def num_TOPIC(bot, textline):
856 pieces = textline.split(None, 4)
857 chan = pieces[3]
858 if chan != state.db['chan']:
859 return
860 gottopic = pieces[4][1:]
861
862 formatted = state.db['topicformat'] % {
863 'chan': state.db['chan'],
8ef938d0 864 'top1': "%s (%s)" % (person(0), pts(0)),
865 'top3': '/'.join([
866 "%s (%s)" % (person(x), pts(x))
867 for x in range(3) if x < len(state.db['ranks'])
868 ]),
e227969c 869 'top3c': ', '.join([
870 "%s (%s) %s" % (person(x), country(x), pts(x))
8ef938d0 871 for x in range(3) if x < len(state.db['ranks'])
872 ]),
873 'top10': ' '.join([
874 "%s (%s)" % (person(x), pts(x))
875 for x in range(10) if x < len(state.db['ranks'])
876 ]),
877 'top10c': ' '.join([
878 "%s (%s, %s)" % (person(x), pts(x), country(x))
879 for x in range(10) if x < len(state.db['ranks'])
880 ]),
5f42c250 881 'lastwinner': state.db['lastwinner'],
882 'lastwon': time.strftime("%b %d", time.gmtime(state.db['lastwon'])),
f8cc0124 883 'target': state.db['target'],
8770f6ef 884 'category': state.db['category'],
f8cc0124 885 }
886 if gottopic != formatted:
887 state.getbot().conn.send("TOPIC %s :%s" % (state.db['chan'], formatted))
888
b5c89dfb 889
890def specialQuestion(oldq):
ebee6edb 891 newq = [oldq[0], oldq[1]]
892 qtype = oldq[0].upper()
b5c89dfb 893
894 if qtype == "!MONTH":
ebee6edb 895 newq[0] = "What month is it currently (in UTC)?"
896 newq[1] = time.strftime("%B", time.gmtime()).lower()
b5c89dfb 897 elif qtype == "!MATH+":
5ed70e94 898 try:
899 maxnum = int(oldq[1])
900 except ValueError:
901 maxnum = 10
902 randnum1 = random.randrange(0, maxnum+1)
903 randnum2 = random.randrange(0, maxnum+1)
ebee6edb 904 newq[0] = "What is %d + %d?" % (randnum1, randnum2)
905 newq[1] = spellout(randnum1+randnum2)
5ed70e94 906 elif qtype == "!ALGEBRA+":
907 try:
908 num1, num2 = [int(i) for i in oldq[1].split('!')]
909 except ValueError:
910 num1, num2 = 10, 10
911 randnum1 = random.randrange(0, num1+1)
912 randnum2 = random.randrange(randnum1, num2+1)
913 newq[0] = "What is x? %d = %d + x" % (randnum2, randnum1)
914 newq[1] = spellout(randnum2-randnum1)
e227969c 915 else: pass #default to not modifying
b5c89dfb 916 return newq
917
918def spellout(num):
5ed70e94 919 ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
920 teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
921 tens = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
922
923 if num == 0:
924 return 'zero'
925
926 ihundreds = num / 100
927 itens = num % 100 / 10
928 iones = num % 10
929 buf = []
930
931 if ihundreds > 0:
932 buf.append("%s hundred" % (ones[ihundreds]))
933 if itens > 1:
934 buf.append(tens[itens])
935 if itens == 1:
936 buf.append(teens[iones])
937 elif iones > 0:
938 buf.append(ones[iones])
939 return ' '.join(buf)
940# return [
941# "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
942# "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
943# "sixteen", "seventeen", "eighteen", "nineteen", "twenty"
944# ][num]