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