]> jfr.im git - erebus.git/blame - modules/trivia.py
bot - update a few spots where it should use permnick
[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
5464fa7a 274 self.lastqtime = time.time()
77c61775 275 if self.gameover == True:
276 return self.doGameOver()
fadbf980 277 if qskipped:
010ab290 278 self.streak = 0
279 self.streak_holder = None
be8072b5 280 self.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self.hintanswer))
c0eee1b4 281 self.missedquestions += 1
282 else:
283 self.missedquestions = 0
f8cc0124 284 if 'topicformat' in self.db and self.db['topicformat'] is not None:
285 self.getbot().conn.send("TOPIC %s" % (self.db['chan']))
fadbf980 286
9138aa03 287 if isinstance(self.steptimer, MyTimer):
b16b8c05 288 self.steptimer.cancel()
9138aa03 289 if isinstance(self.nextquestiontimer, MyTimer):
442ed923 290 self.nextquestiontimer.cancel()
291 self.nextquestiontimer = None
c0eee1b4 292
b16b8c05 293 self.hintstr = None
77c61775 294 self.hintsgiven = 0
b16b8c05 295 self.revealpossibilities = None
b5c89dfb 296 self.reveal = None
b16b8c05 297
af349654 298 self.savedb()
299
c4763e66 300 if self.missedquestions > self.db['maxmissedquestions']:
c0eee1b4 301 stop()
ce03ceda 302 self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game." % (self.missedquestions))
303 return
b16b8c05 304
442ed923 305 if skipwait:
6bdfec48 306 self._nextquestion(iteration)
442ed923 307 else:
be8072b5 308 self.nextquestiontimer = MyTimer(self.db['questionpause'], self._nextquestion, args=[iteration])
442ed923 309 self.nextquestiontimer.start()
310
6bdfec48 311 def _nextquestion(self, iteration):
e5a3970b 312 if self.nextq is not None:
2520caee 313 nextqid = None
e5a3970b 314 nextq = self.nextq
315 self.nextq = None
656dc5a4 316 elif self.nextqid is not None:
317 nextqid = self.nextqid
318 nextq = self.questions[nextqid]
319 self.nextqid = None
c695f740 320 else:
8ad3a154 321 nextqid = random.randrange(0, len(self.questions))
322 nextq = self.questions[nextqid]
b5c89dfb 323
fd07173d 324 if nextq[0].startswith("!"):
2520caee 325 nextqid = None
b5c89dfb 326 nextq = specialQuestion(nextq)
327
aa0e4be4 328 if len(nextq) > 2 and time.time() - nextq[2] < 7*24*60*60 and iteration < 10:
442ed923 329 return self._nextquestion(iteration=iteration+1) #short-circuit to pick another question
ebee6edb 330 if len(nextq) > 2:
331 nextq[2] = time.time()
332 else:
333 nextq.append(time.time())
b5c89dfb 334
93ce52fd 335 if isinstance(nextq[1], basestring):
336 nextq[1] = nextq[1].lower()
337 else:
338 nextq[1] = [s.lower() for s in nextq[1]]
c695f740 339
00ccae72 340 qtext = "\00312,01Next up: "
bf8676ae 341 qtext += "(%5d)" % (random.randint(0,99999))
ebee6edb 342 qary = nextq[0].split(None)
71e0b5fb 343 qtext += " "
c695f740 344 for qword in qary:
af349654 345 spacer = random.choice(
346 range(0x61,0x7A) + ([0x20]*4)
347 )
348 qtext += "\00304,01"+qword+"\00301,01"+chr(spacer) #a-z
656dc5a4 349 if not self.getbot().fastmsg(self.chan, qtext): #if message is too long:
bcb6dc21 350 if not self.getbot().fastmsg(self.chan, "\00312,01Next up: " + ("(%5d)" % (random.randint(0,99999))) + "\00304,01" + nextq[0]):
351 if nextqid is None: nextqid = "manual"
352 self.getbot().slowmsg(self.chan, "(Unable to ask question #%s: line too long)" % (nextqid))
353 return self._nextquestion(iteration) #retry; don't increment the iteration
80d02bd8 354
b5c89dfb 355 self.curq = nextq
7b832b55 356 self.curqid = nextqid
b5c89dfb 357
ebee6edb 358 if isinstance(self.curq[1], basestring): self.hintanswer = self.curq[1]
359 else: self.hintanswer = random.choice(self.curq[1])
c0eee1b4 360
be8072b5 361 self.steptimer = MyTimer(self.db['hinttimer'], self.nexthint, args=[1])
b16b8c05 362 self.steptimer.start()
363
80d02bd8 364 def checkanswer(self, answer):
9557ee54 365 if self.curq is None:
366 return False
ebee6edb 367 elif isinstance(self.curq[1], basestring):
368 return answer.lower() == self.curq[1]
80d02bd8 369 else: # assume it's a list or something.
ebee6edb 370 return answer.lower() in self.curq[1]
77c61775 371
c53f6514 372 def addpoint(self, user_obj, count=1):
373 user_nick = str(user_obj)
374 user = user_nick.lower() # save this separately as we use both
80d02bd8 375 if user in self.db['users']:
376 self.db['users'][user]['points'] += count
377 else:
c53f6514 378 self.db['users'][user] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
9557ee54 379 self.db['ranks'].append(user)
80d02bd8 380
e5a3970b 381 self.db['ranks'].sort(key=lambda nick: self.db['users'][nick]['points'], reverse=True) #re-sort ranks, rather than dealing with anything more efficient
6374d61f 382 for i in range(0, len(self.db['ranks'])):
383 nick = self.db['ranks'][i]
384 self.db['users'][nick]['rank'] = i
77c61775 385
e5a3970b 386 if self.db['users'][user]['points'] >= self.db['target']:
77c61775 387 self.gameover = True
388
80d02bd8 389 return self.db['users'][user]['points']
390
391 def points(self, user):
9557ee54 392 user = str(user).lower()
80d02bd8 393 if user in self.db['users']:
394 return self.db['users'][user]['points']
395 else:
396 return 0
397
398 def rank(self, user):
c695f740 399 user = str(user).lower()
fadbf980 400 if user in self.db['users']:
401 return self.db['users'][user]['rank']+1
402 else:
403 return len(self.db['users'])+1
77c61775 404
c695f740 405 def targetuser(self, user):
77c61775 406 if len(self.db['ranks']) == 0: return "no one is ranked!"
407
c695f740 408 user = str(user).lower()
fadbf980 409 if user in self.db['users']:
410 rank = self.db['users'][user]['rank']
411 if rank == 0:
412 return "you're in the lead!"
413 else:
414 return self.db['ranks'][rank-1]
c695f740 415 else:
fadbf980 416 return self.db['ranks'][-1]
c695f740 417 def targetpoints(self, user):
77c61775 418 if len(self.db['ranks']) == 0: return 0
419
c695f740 420 user = str(user).lower()
fadbf980 421 if user in self.db['users']:
422 rank = self.db['users'][user]['rank']
423 if rank == 0:
af349654 424 return ""
fadbf980 425 else:
af349654 426 return "("+str(self.db['users'][self.db['ranks'][rank-1]]['points'])+")"
c695f740 427 else:
af349654 428 return "("+str(self.db['users'][self.db['ranks'][-1]]['points'])+")"
80d02bd8 429
5871567f 430state = TriviaState()
9557ee54 431
5871567f 432# we have to hook this in modstart, since we don't know the channel until then.
80d02bd8 433def trivia_checkanswer(bot, user, chan, *args):
80d02bd8 434 line = ' '.join([str(arg) for arg in args])
435 if state.checkanswer(line):
6bdfec48 436 state.curq = None
68419d56 437
438 if state.streak_holder == user:
439 state.streak += 1
93ce52fd 440 else:
010ab290 441 if state.streak >= 3:
442 bot.fastmsg(chan, "\00312%s\003 broke \00304%s\003's streak of \00307%d\003!" % (user, state.streak_holder, state.streak))
68419d56 443 state.streak_holder = user
444 state.streak = 1
445
5464fa7a 446 response = "\00312%s\003 got it in %d seconds! The answer was \00312%s\003" % (user, time.time()-state.lastqtime, line)
68419d56 447 if state.hintanswer.lower() != line.lower():
448 response += " (hinted answer: %s)" % (state.hintanswer)
449 response += ". New score: %d. Rank: %d. Target: %s %s" % (state.addpoint(user), state.rank(user), state.targetuser(user), state.targetpoints(user))
450 bot.fastmsg(chan, response)
451
452 if state.streak >= 3:
453 bot.msg(chan, "\00312%s\003 is on a streak! \00307%d\003 answers correct in a row!" % (user, state.streak))
454
77c61775 455 if state.hintsgiven == 0:
6374d61f 456 bot.msg(chan, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user)))
68419d56 457
9557ee54 458 state.nextquestion()
80d02bd8 459
f5aec865 460@lib.hook(glevel=1, needchan=False, wantchan=True)
67faf5d7 461@lib.help(None, "saves the trivia database")
462def save(bot, user, chan, realtarget, *args):
f5aec865 463 if chan is not None: replyto = chan
67faf5d7 464 else: replyto = user
465
466 if state.savedb():
467 bot.msg(replyto, "Save successful.")
468 else:
469 bot.msg(replyto, "Save failed!")
470
f5aec865 471@lib.hook(needchan=False, wantchan=True)
5f03d045 472@lib.help("[<user>]", "shows how many points you or someone has")
fb20be7c 473def points(bot, user, chan, realtarget, *args):
f5aec865 474 if chan is not None: eplyto = chan
80d02bd8 475 else: replyto = user
476
477 if len(args) != 0: who = args[0]
478 else: who = user
479
480 bot.msg(replyto, "%s has %d points." % (who, state.points(who)))
481
fb20be7c 482@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 483@lib.help("<user> [<amount>]", "gives someone points", "defaults to 1 point")
80d02bd8 484@lib.argsGE(1)
fb20be7c 485def give(bot, user, chan, realtarget, *args):
80d02bd8 486 whoto = args[0]
c695f740 487 if len(args) > 1:
488 numpoints = int(args[1])
489 else:
490 numpoints = 1
491 balance = state.addpoint(whoto, numpoints)
fadbf980 492
c695f740 493 bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance))
494
fb20be7c 495@lib.hook(glevel=1, needchan=False)
5f03d045 496@lib.help("<qid>", "sets next question to one in the database")
497@lib.argsEQ(1)
fb20be7c 498def setnextid(bot, user, chan, realtarget, *args):
9306587e 499 try:
500 qid = int(args[0])
656dc5a4 501 except ValueError:
502 bot.msg(user, "Error: QID must be a number.")
503 return
504 if qid >= len(state.questions):
505 bot.msg(user, "Error: no such QID.")
506 return
507 state.nextqid = qid
4d925ae3 508 bot.msg(user, "Done. Next question is %d: %s" % (qid, state.questions[qid][0]), truncate=True)
9306587e 509
fb20be7c 510@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 511@lib.help("<q>*<a>", "sets next question to one not in database")
c695f740 512@lib.argsGE(1)
fb20be7c 513def setnext(bot, user, chan, realtarget, *args):
c695f740 514 line = ' '.join([str(arg) for arg in args])
aa0e4be4 515 linepieces = line.split('*', 1)
b5c89dfb 516 if len(linepieces) < 2:
517 bot.msg(user, "Error: need <question>*<answer>")
518 return
c695f740 519 question = linepieces[0].strip()
520 answer = linepieces[1].strip()
ebee6edb 521 state.nextq = [question, answer]
c695f740 522 bot.msg(user, "Done.")
523
fb20be7c 524@lib.hook(glevel=1, needchan=False)
5f03d045 525@lib.help(None, "skips to next question")
fb20be7c 526def skip(bot, user, chan, realtarget, *args):
442ed923 527 state.nextquestion(qskipped=True, skipwait=True)
c695f740 528
492f66ea 529@lib.hook(('start','trivia'), needchan=False, wantchan=True)
5f03d045 530@lib.help(None, "starts the trivia game")
fb20be7c 531def start(bot, user, chan, realtarget, *args):
f5aec865 532 if chan is not None: replyto = chan
c695f740 533 else: replyto = user
534
77a265cd 535 if chan is not None and chan.name != state.db['chan']:
536 bot.msg(replyto, "That command isn't valid here.")
537 return
538
442ed923 539 if state.curq is None and state.pointvote is None and state.nextquestiontimer is None:
77a265cd 540 bot.msg(state.db['chan'], "%s has started the game!" % (user))
442ed923 541 state.nextquestion(skipwait=True)
c53f6514 542 elif state.pointvote is not None:
00ccae72 543 bot.msg(user, "There's a vote in progress!")
c695f740 544 else:
00ccae72 545 bot.msg(user, "Game is already started!")
c695f740 546
9306587e 547@lib.hook('stop', glevel=1, needchan=False)
5f03d045 548@lib.help(None, "stops the trivia game")
c695f740 549def cmd_stop(bot, user, chan, realtarget, *args):
fadbf980 550 if stop():
551 bot.msg(state.chan, "Game stopped by %s" % (user))
552 else:
553 bot.msg(user, "Game isn't running.")
c695f740 554
fadbf980 555def stop():
3b89ebff 556 state.curq = None
557 state.nextq = None
09566235 558 try:
559 state.steptimer.cancel()
560 except Exception as e:
a28e2ae9 561 print("!!! steptimer.cancel(): %s %r" % (e,e))
3b89ebff 562 state.steptimer = None
09566235 563 try:
564 state.nextquestiontimer.cancel()
565 except Exception as e:
a28e2ae9 566 print("!!! nextquestiontimer.cancel(): %s %r" % (e,e))
3b89ebff 567 state.nextquestiontimer = None
568 return True
80d02bd8 569
fb20be7c 570@lib.hook(needchan=False)
5f03d045 571@lib.help("<reason>", "reports a bad question to the admins")
7b832b55 572@lib.argsGE(1)
fb20be7c 573def badq(bot, user, chan, realtarget, *args):
7b832b55 574 lastqid = state.lastqid
575 curqid = state.curqid
576
577 reason = ' '.join(args)
8ad3a154 578 state.db['badqs'].append([state.db['category'], lastqid, curqid, reason])
7b832b55 579 bot.msg(user, "Reported bad question.")
2520caee 580
fb20be7c 581@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 582@lib.help(None, "shows a list of BADQ reports")
fb20be7c 583def badqs(bot, user, chan, realtarget, *args):
2520caee 584 if len(state.db['badqs']) == 0:
585 bot.msg(user, "No reports.")
586
587 for i in range(len(state.db['badqs'])):
588 try:
589 report = state.db['badqs'][i]
8ad3a154 590 bot.msg(user, "Report #%d: Cat=%s LastQ=%r CurQ=%r: %s" % (i, report[0], report[1], report[2], report[3]))
591 try: lq = state.db['questions'][report[0]][int(report[1])]
7b832b55 592 except Exception as e: lq = (None,None)
8ad3a154 593 try: cq = state.db['questions'][report[0]][int(report[2])]
7b832b55 594 except Exception as e: cq = (None, None)
595 bot.msg(user, "- Last: %s*%s" % (lq[0], lq[1]))
596 bot.msg(user, "- Curr: %s*%s" % (cq[0], cq[1]))
2520caee 597 except Exception as e:
598 bot.msg(user, "- Exception: %r" % (e))
599
fb20be7c 600@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 601@lib.hook(None, "clears list of BADQ reports")
fb20be7c 602def clearbadqs(bot, user, chan, realtarget, *args):
2520caee 603 state.db['badqs'] = []
604 bot.msg(user, "Cleared reports.")
605
fb20be7c 606@lib.hook(glevel=lib.STAFF, needchan=False)
5f03d045 607@lib.hook("<badqid>", "removes a BADQ report")
2520caee 608@lib.argsEQ(1)
fb20be7c 609def delbadq(bot, user, chan, realtarget, *args):
4d98501a 610 try:
611 qid = int(args[0])
612 del state.db['badqs'][qid]
4d98501a 613 bot.msg(user, "Removed report #%d" % (qid))
614 except:
615 bot.msg(user, "Failed!")
2520caee 616
f5aec865 617@lib.hook(needchan=False, wantchan=True)
5f03d045 618@lib.help("[<user>]", "shows you or someone else's rank")
fb20be7c 619def rank(bot, user, chan, realtarget, *args):
f5aec865 620 if chan is not None: replyto = chan
80d02bd8 621 else: replyto = user
622
c695f740 623 if len(args) != 0: who = args[0]
624 else: who = user
625
af349654 626 bot.msg(replyto, "%s is in %d place (%s points). Target is: %s %s" % (who, state.rank(who), state.points(who), state.targetuser(who), state.targetpoints(who)))
fadbf980 627
fb20be7c 628@lib.hook(needchan=False)
5f03d045 629@lib.help(None, "shows top10 list")
fb20be7c 630def top10(bot, user, chan, realtarget, *args):
77c61775 631 if len(state.db['ranks']) == 0:
632 return bot.msg(state.db['chan'], "No one is ranked!")
fadbf980 633
8ef938d0 634 max = len(state.db['ranks'])
635 if max > 10:
636 max = 10
2bb267e0 637 replylist = ', '.join(["%s (%s) %s" % (person(x), country(x), pts(x)) for x in range(max)])
bcb6dc21 638 bot.msg(state.db['chan'], "Game is to %s! Top 10: %s" % (state.db['target'], replylist))
77c61775 639
fb20be7c 640@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 641@lib.help("<target score>", "changes the target score for this round")
fb20be7c 642def settarget(bot, user, chan, realtarget, *args):
77c61775 643 try:
644 state.db['target'] = int(args[0])
645 bot.msg(state.db['chan'], "Target has been changed to %s points!" % (state.db['target']))
38b29993 646
7bd5e7d5 647 if state.pointvote is not None:
648 state.pointvote.cancel()
649 state.pointvote = None
38b29993 650 bot.msg(state.db['chan'], "Vote has been cancelled!")
7bd5e7d5 651 except Exception as e:
a28e2ae9 652 print(e)
77c61775 653 bot.msg(user, "Failed to set target.")
654
fb20be7c 655@lib.hook(needchan=False)
5f03d045 656@lib.help("<option>", "votes for a trarget score for next round")
fb20be7c 657def vote(bot, user, chan, realtarget, *args):
7bd5e7d5 658 if state.pointvote is not None:
38b29993 659 if int(args[0]) in state.voteamounts:
660 state.voteamounts[int(args[0])] += 1
661 bot.msg(user, "Your vote has been recorded.")
662 else:
663 bot.msg(user, "Sorry - that's not an option!")
664 else:
665 bot.msg(user, "There's no vote in progress.")
666
fb20be7c 667@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 668@lib.help("<number>", "sets the max missed question before game stops")
fb20be7c 669def maxmissed(bot, user, chan, realtarget, *args):
c4763e66 670 try:
671 state.db['maxmissedquestions'] = int(args[0])
672 bot.msg(state.db['chan'], "Max missed questions before round ends has been changed to %s." % (state.db['maxmissedquestions']))
673 except:
674 bot.msg(user, "Failed to set maxmissed.")
675
fb20be7c 676@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 677@lib.help("<seconds>", "sets the time between hints")
fb20be7c 678def hinttimer(bot, user, chan, realtarget, *args):
c4763e66 679 try:
680 state.db['hinttimer'] = float(args[0])
681 bot.msg(state.db['chan'], "Time between hints has been changed to %s." % (state.db['hinttimer']))
682 except:
683 bot.msg(user, "Failed to set hint timer.")
684
fb20be7c 685@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 686@lib.help("<number>", "sets the number of hints given")
fb20be7c 687def hintnum(bot, user, chan, realtarget, *args):
c4763e66 688 try:
689 state.db['hintnum'] = int(args[0])
690 bot.msg(state.db['chan'], "Max number of hints has been changed to %s." % (state.db['hintnum']))
691 except:
692 bot.msg(user, "Failed to set hintnum.")
693
fb20be7c 694@lib.hook(glevel=lib.ADMIN, needchan=False)
5f03d045 695@lib.help("<seconds>", "sets the pause between questions")
fb20be7c 696def questionpause(bot, user, chan, realtarget, *args):
442ed923 697 try:
698 state.db['questionpause'] = float(args[0])
699 bot.msg(state.db['chan'], "Pause between questions has been changed to %s." % (state.db['questionpause']))
700 except:
701 bot.msg(user, "Failed to set questionpause.")
702
fb20be7c 703@lib.hook(glevel=1, needchan=False)
8e76c9bb 704@lib.help("[@category] <full question>", "finds a qid given a complete question")
705@lib.argsGE(1)
fb20be7c 706def findq(bot, user, chan, realtarget, *args):
8ad3a154 707 args = list(args)
fd07173d 708 if args[0].startswith("@"):
8ad3a154 709 cat = args.pop(0)[1:].lower()
710 questions = state.db['questions'][cat]
711 else:
712 questions = state.questions
713
4d98501a 714 if len(args) == 0:
715 bot.msg(user, "You need to specify the question.")
716 return
717
718 searchkey = ' '.join(args).lower()
8ad3a154 719 matches = [str(i) for i in range(len(questions)) if questions[i][0].lower() == searchkey]
4d98501a 720 if len(matches) > 1:
721 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
722 elif len(matches) == 1:
723 bot.msg(user, "One match: %s" % (matches[0]))
724 else:
725 bot.msg(user, "No match.")
726
727@lib.hook(glevel=1, needchan=False)
8ad3a154 728@lib.help("[@<category>] <regex>", "finds a qid given a regex or partial question")
8e76c9bb 729@lib.argsGE(1)
4d98501a 730def findqre(bot, user, chan, realtarget, *args):
8ad3a154 731 args = list(args)
fd07173d 732 if args[0].startswith("@"):
8ad3a154 733 cat = args.pop(0)[1:].lower()
734 questions = state.db['questions'][cat]
735 else:
736 questions = state.questions
737
bf8676ae 738 if len(args) == 0:
739 bot.msg(user, "You need to specify a search string.")
740 return
741
4d98501a 742 searcher = re.compile(' '.join(args), re.IGNORECASE)
8ad3a154 743 matches = [str(i) for i in range(len(questions)) if searcher.search(questions[i][0]) is not None]
bf8676ae 744 if len(matches) > 25:
745 bot.msg(user, "Too many matches! (>25)")
746 elif len(matches) > 1:
c4763e66 747 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
748 elif len(matches) == 1:
749 bot.msg(user, "One match: %s" % (matches[0]))
750 else:
751 bot.msg(user, "No match.")
752
b9daa51a 753@lib.hook(glevel=lib.STAFF, needchan=False)
8ad3a154 754@lib.help("[@<category>] <qid>", "displays the q*a for a qid", "category defaults to current")
b9daa51a 755def showq(bot, user, chan, realtarget, *args):
8ad3a154 756 args = list(args)
fd07173d 757 if args[0].startswith("@"):
8ad3a154 758 cat = args.pop(0)[1:].lower()
759 questions = state.db['questions'][cat]
760 else:
761 questions = state.questions
762
b9daa51a 763 try:
764 qid = int(args[0])
765 except:
766 bot.msg(user, "Specify a numeric question ID.")
767 return
768 try:
8ad3a154 769 q = questions[qid]
b9daa51a 770 except:
771 bot.msg(user, "ID not valid.")
772 return
43649433 773 bot.msg(user, "%s: %s*%s" % (qid, q[0], q[1]), True)
b9daa51a 774
fb20be7c 775@lib.hook(('delq', 'deleteq'), glevel=lib.STAFF, needchan=False)
8ad3a154 776@lib.help("[@<category>] <qid>", "removes a question from the database")
fb20be7c 777def delq(bot, user, chan, realtarget, *args):
8ad3a154 778 args = list(args)
fd07173d 779 if args[0].startswith("@"):
8ad3a154 780 cat = args.pop(0)[1:].lower()
781 questions = state.db['questions'][cat]
782 else:
783 questions = state.questions
784
c4763e66 785 try:
8ad3a154 786 backup = questions[int(args[0])]
787 del questions[int(args[0])]
d2de4fce 788 bot.msg(user, "Deleted %s*%s" % (backup[0], backup[1]), True)
789 except Exception as e:
b9daa51a 790 bot.msg(user, "Couldn't delete that question. %r" % (e))
c4763e66 791
fb20be7c 792@lib.hook(glevel=lib.STAFF, needchan=False)
8ad3a154 793@lib.help("[@<category>] <q>*<a>", "adds a question")
fb20be7c 794def addq(bot, user, chan, realtarget, *args):
8ad3a154 795 args = list(args)
fd07173d 796 if args[0].startswith("@"):
8ad3a154 797 cat = args.pop(0)[1:].lower()
798 questions = state.db['questions'][cat]
799 else:
800 questions = state.questions
801
c4763e66 802 line = ' '.join([str(arg) for arg in args])
aa0e4be4 803 linepieces = line.split('*', 1)
c4763e66 804 if len(linepieces) < 2:
805 bot.msg(user, "Error: need <question>*<answer>")
806 return
807 question = linepieces[0].strip()
808 answer = linepieces[1].strip()
8ad3a154 809 questions.append([question, answer])
810 bot.msg(user, "Done. Question is #%s" % (len(questions)-1))
c4763e66 811
8770f6ef 812@lib.hook(needchan=False)
813@lib.help(None, "show current category")
814def showcat(bot, user, chan, realtarget, *args):
815 bot.msg(user, "Current category: %s" % (state.db['category']))
816
8ad3a154 817@lib.hook(glevel=1, needchan=False)
818@lib.help("<category>", "change category")
819def setcat(bot, user, chan, realtarget, *args):
820 category = args[0].lower()
821 if category in state.db['questions']:
822 state.db['category'] = category
823 state.questions = state.db['questions'][category]
824 bot.msg(user, "Changed category to %s" % (category))
825 else:
826 bot.msg(user, "That category doesn't exist.")
827
828@lib.hook(needchan=False)
8770f6ef 829@lib.help(None, "list categories", "the current category will be marked with a *")
8ad3a154 830def listcats(bot, user, chan, realtarget, *args):
8770f6ef 831 cats = ["%s%s (%d)" % ("*" if c == state.db['category'] else "", c, len(state.db['questions'][c])) for c in state.db['questions'].keys()]
8ad3a154 832 bot.msg(user, "Categories: %s" % (', '.join(cats)))
833
834@lib.hook(glevel=lib.STAFF, needchan=False)
835@lib.help("<category>", "adds an empty category")
836def addcat(bot, user, chan, realtarget, *args):
837 category = args[0].lower()
838 if category not in state.db['questions']:
839 state.db['questions'][category] = []
840 bot.msg(user, "Added category %s" % (category))
841 else:
842 bot.msg(user, "Category already exists.")
843
844@lib.hook(glevel=lib.MANAGER, needchan=False)
845@lib.help("<category>", "deletes an entire category")
846def delcat(bot, user, chan, realtarget, *args):
847 category = args[0].lower()
848 if category == state.db['category']:
849 bot.msg(user, "Category currently in use!")
850 elif category in state.db['questions']:
851 length = len(state.db['questions'][category])
852 del state.db['questions'][category]
853 bot.msg(user, "Deleted category %s (%d questions)" % (category, length))
854 else:
855 bot.msg(user, "Category does not exist.")
c4763e66 856
fb20be7c 857@lib.hook(needchan=False)
858def triviahelp(bot, user, chan, realtarget, *args):
2bb267e0 859 bot.slowmsg(user, "START")
860 bot.slowmsg(user, "TOP10")
861 bot.slowmsg(user, "POINTS [<user>]")
862 bot.slowmsg(user, "RANK [<user>]")
863 bot.slowmsg(user, "BADQ <reason> (include info to identify question)")
9306587e 864 if user.glevel >= 1:
b9daa51a 865 bot.slowmsg(user, "SKIP (KNOWN)")
866 bot.slowmsg(user, "STOP (KNOWN)")
4d98501a 867 bot.slowmsg(user, "FINDQ <full question> (KNOWN)")
868 bot.slowmsg(user, "FINDQRE <regex> (KNOWN)")
b9daa51a 869 bot.slowmsg(user, "SETNEXTID <qid> (KNOWN)")
9306587e 870 if user.glevel >= lib.STAFF:
b9daa51a 871 bot.slowmsg(user, "GIVE <user> [<points>] (STAFF)")
872 bot.slowmsg(user, "SETNEXT <q>*<a> (STAFF)")
873 bot.slowmsg(user, "ADDQ <q>*<a> (STAFF)")
874 bot.slowmsg(user, "DELQ <q>*<a> (STAFF) [aka DELETEQ]")
875 bot.slowmsg(user, "SHOWQ <qid> (STAFF)")
876 bot.slowmsg(user, "BADQS (STAFF)")
877 bot.slowmsg(user, "CLEARBADQS (STAFF)")
878 bot.slowmsg(user, "DELBADQ <reportid> (STAFF)")
9306587e 879 if user.glevel >= lib.ADMIN:
b9daa51a 880 bot.slowmsg(user, "SETTARGET <points> (ADMIN)")
881 bot.slowmsg(user, "MAXMISSED <questions> (ADMIN)")
882 bot.slowmsg(user, "HINTTIMER <float seconds> (ADMIN)")
883 bot.slowmsg(user, "HINTNUM <hints> (ADMIN)")
884 bot.slowmsg(user, "QUESTIONPAUSE <float seconds> (ADMIN)")
b5c89dfb 885
a46e5e4d 886@lib.hooknum(332) # topic is...
887@lib.hooknum(331) # no topic set
f8cc0124 888def num_TOPIC(bot, textline):
889 pieces = textline.split(None, 4)
890 chan = pieces[3]
891 if chan != state.db['chan']:
892 return
893 gottopic = pieces[4][1:]
894
895 formatted = state.db['topicformat'] % {
896 'chan': state.db['chan'],
8ef938d0 897 'top1': "%s (%s)" % (person(0), pts(0)),
898 'top3': '/'.join([
899 "%s (%s)" % (person(x), pts(x))
900 for x in range(3) if x < len(state.db['ranks'])
901 ]),
e227969c 902 'top3c': ', '.join([
903 "%s (%s) %s" % (person(x), country(x), pts(x))
8ef938d0 904 for x in range(3) if x < len(state.db['ranks'])
905 ]),
906 'top10': ' '.join([
907 "%s (%s)" % (person(x), pts(x))
908 for x in range(10) if x < len(state.db['ranks'])
909 ]),
910 'top10c': ' '.join([
911 "%s (%s, %s)" % (person(x), pts(x), country(x))
912 for x in range(10) if x < len(state.db['ranks'])
913 ]),
5f42c250 914 'lastwinner': state.db['lastwinner'],
915 'lastwon': time.strftime("%b %d", time.gmtime(state.db['lastwon'])),
f8cc0124 916 'target': state.db['target'],
8770f6ef 917 'category': state.db['category'],
f8cc0124 918 }
919 if gottopic != formatted:
a46e5e4d 920 state.getbot().conn.send(bot.parent.cfg.get('trivia', 'topiccommand', default="TOPIC %(chan)s :%(topic)s") % {'chan': state.db['chan'], 'topic': formatted})
f8cc0124 921
b5c89dfb 922
923def specialQuestion(oldq):
ebee6edb 924 newq = [oldq[0], oldq[1]]
925 qtype = oldq[0].upper()
b5c89dfb 926
927 if qtype == "!MONTH":
ebee6edb 928 newq[0] = "What month is it currently (in UTC)?"
929 newq[1] = time.strftime("%B", time.gmtime()).lower()
b5c89dfb 930 elif qtype == "!MATH+":
5ed70e94 931 try:
932 maxnum = int(oldq[1])
933 except ValueError:
934 maxnum = 10
935 randnum1 = random.randrange(0, maxnum+1)
936 randnum2 = random.randrange(0, maxnum+1)
ebee6edb 937 newq[0] = "What is %d + %d?" % (randnum1, randnum2)
938 newq[1] = spellout(randnum1+randnum2)
5ed70e94 939 elif qtype == "!ALGEBRA+":
940 try:
941 num1, num2 = [int(i) for i in oldq[1].split('!')]
942 except ValueError:
943 num1, num2 = 10, 10
944 randnum1 = random.randrange(0, num1+1)
945 randnum2 = random.randrange(randnum1, num2+1)
946 newq[0] = "What is x? %d = %d + x" % (randnum2, randnum1)
947 newq[1] = spellout(randnum2-randnum1)
e227969c 948 else: pass #default to not modifying
b5c89dfb 949 return newq
950
951def spellout(num):
5ed70e94 952 ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
953 teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
954 tens = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
955
956 if num == 0:
957 return 'zero'
958
959 ihundreds = num / 100
960 itens = num % 100 / 10
961 iones = num % 10
962 buf = []
963
964 if ihundreds > 0:
965 buf.append("%s hundred" % (ones[ihundreds]))
966 if itens > 1:
967 buf.append(tens[itens])
968 if itens == 1:
969 buf.append(teens[iones])
970 elif iones > 0:
971 buf.append(ones[iones])
972 return ' '.join(buf)
973# return [
974# "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
975# "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
976# "sixteen", "seventeen", "eighteen", "nineteen", "twenty"
977# ][num]