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