]>
Commit | Line | Data |
---|---|---|
80d02bd8 | 1 | # Erebus IRC bot - Author: Erebus Team |
c695f740 | 2 | # trivia module |
80d02bd8 | 3 | # This file is released into the public domain; see http://unlicense.org/ |
4 | ||
5 | # module info | |
6 | modinfo = { | |
7 | 'author': 'Erebus Team', | |
8 | 'license': 'public domain', | |
9 | 'compatible': [1], # compatible module API versions | |
fb20be7c | 10 | 'depends': ['userinfo'], # other modules required to work properly? |
80d02bd8 | 11 | } |
12 | ||
13 | # preamble | |
14 | import modlib | |
15 | lib = modlib.modlib(__name__) | |
16 | def modstart(parent, *args, **kwargs): | |
5871567f | 17 | state.gotParent(parent) |
18 | lib.hookchan(state.db['chan'])(trivia_checkanswer) # we need parent for this. so it goes here. | |
80d02bd8 | 19 | return lib.modstart(parent, *args, **kwargs) |
20 | def modstop(*args, **kwargs): | |
c0eee1b4 | 21 | global state |
8ef938d0 | 22 | try: |
23 | stop() | |
24 | state.closeshop() | |
25 | del state | |
26 | except Exception: pass | |
80d02bd8 | 27 | return lib.modstop(*args, **kwargs) |
28 | ||
29 | # module code | |
7bd5e7d5 | 30 | import json, random, threading, re, time, datetime |
b16b8c05 | 31 | |
c0eee1b4 | 32 | try: |
be8072b5 | 33 | import twitter |
c53f6514 | 34 | except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so... |
c0eee1b4 | 35 | |
b16b8c05 | 36 | def findnth(haystack, needle, n): #http://stackoverflow.com/a/1884151 |
37 | parts = haystack.split(needle, n+1) | |
38 | if len(parts)<=n+1: | |
39 | return -1 | |
40 | return len(haystack)-len(parts[-1])-len(needle) | |
80d02bd8 | 41 | |
00ccae72 | 42 | def person(num, throwindexerror=False): |
43 | try: | |
44 | return state.db['users'][state.db['ranks'][num]]['realnick'] | |
45 | except IndexError: | |
46 | if throwindexerror: | |
47 | raise | |
48 | else: | |
49 | return '' | |
50 | ||
3b89ebff | 51 | def pts(num): |
00ccae72 | 52 | try: |
53 | return str(state.db['users'][state.db['ranks'][num]]['points']) | |
54 | except IndexError: | |
55 | return 0 | |
2bb267e0 | 56 | |
00ccae72 | 57 | def country(num, default="??"): |
2bb267e0 | 58 | return lib.mod('userinfo')._get(person(num), 'country', default=default).upper() |
8ef938d0 | 59 | |
be8072b5 | 60 | class MyTimer(threading._Timer): |
61 | def __init__(self, *args, **kwargs): | |
62 | threading._Timer.__init__(self, *args, **kwargs) | |
63 | self.daemon = True | |
64 | ||
80d02bd8 | 65 | class TriviaState(object): |
5871567f | 66 | def __init__(self, parent=None, pointvote=False): |
67 | if parent is not None: | |
68 | self.gotParent(parent, pointvote) | |
69 | ||
70 | def gotParent(self, parent, pointvote=False): | |
bf8676ae | 71 | self.parent = parent |
72 | self.questionfile = self.parent.cfg.get('trivia', 'jsonpath', default="./modules/trivia.json") | |
73 | self.db = json.load(open(self.questionfile, "r")) | |
74 | self.chan = self.db['chan'] | |
75 | self.curq = None | |
76 | self.nextq = None | |
77 | self.nextquestiontimer = None | |
78 | self.steptimer = None | |
79 | self.hintstr = None | |
80 | self.hintanswer = None | |
81 | self.hintsgiven = 0 | |
b16b8c05 | 82 | self.revealpossibilities = None |
bf8676ae | 83 | self.gameover = False |
84 | self.missedquestions = 0 | |
85 | self.curqid = None | |
86 | self.lastqid = None | |
80d02bd8 | 87 | |
00ccae72 | 88 | if 'lastwon' not in self.db or self.db['lastwon'] is None: |
89 | self.db['lastwon'] = time.time() | |
7bd5e7d5 | 90 | |
c53f6514 | 91 | if pointvote: |
92 | self.getchan().msg("Vote for the next round target points! Options: %s. Vote using !vote <choice>" % (', '.join([str(x) for x in self.db['targetoptions']]))) | |
93 | self.getchan().msg("You have %s seconds." % (self.db['votetimer'])) | |
94 | self.voteamounts = dict([(x, 0) for x in self.db['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...} | |
be8072b5 | 95 | self.pointvote = MyTimer(self.db['votetimer'], self.endPointVote) |
c53f6514 | 96 | self.pointvote.start() |
97 | else: | |
98 | self.pointvote = None | |
99 | ||
80d02bd8 | 100 | def __del__(self): |
77c61775 | 101 | self.closeshop() |
102 | def closeshop(self): | |
442ed923 | 103 | if threading is not None and threading._Timer is not None: |
104 | if isinstance(self.steptimer, threading._Timer): | |
105 | self.steptimer.cancel() | |
106 | if isinstance(self.nextquestiontimer, threading._Timer): | |
107 | self.nextquestiontimer.cancel() | |
108 | self.nextquestiontimer = None | |
b9daa51a | 109 | self.savedb() |
110 | ||
111 | def savedb(self): | |
c695f740 | 112 | if json is not None and json.dump is not None: |
6374d61f | 113 | json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': ')) |
80d02bd8 | 114 | |
fadbf980 | 115 | def getchan(self): |
116 | return self.parent.channel(self.chan) | |
117 | def getbot(self): | |
118 | return self.getchan().bot | |
119 | ||
b16b8c05 | 120 | def nexthint(self, hintnum): |
b16b8c05 | 121 | answer = self.hintanswer |
122 | ||
b5c89dfb | 123 | if self.hintstr is None or self.revealpossibilities is None or self.reveal is None: |
93ce52fd | 124 | oldhintstr = "" |
b16b8c05 | 125 | self.hintstr = list(re.sub(r'[a-zA-Z0-9]', '*', answer)) |
126 | self.revealpossibilities = range(''.join(self.hintstr).count('*')) | |
93ce52fd | 127 | self.reveal = int(round(''.join(self.hintstr).count('*') * (7/24.0))) |
128 | else: | |
129 | oldhintstr = ''.join(self.hintstr) | |
b16b8c05 | 130 | |
b5c89dfb | 131 | for i in range(self.reveal): |
b16b8c05 | 132 | revealcount = random.choice(self.revealpossibilities) |
133 | revealloc = findnth(''.join(self.hintstr), '*', revealcount) | |
134 | self.revealpossibilities.remove(revealcount) | |
135 | self.hintstr[revealloc] = answer[revealloc] | |
2bb267e0 | 136 | if oldhintstr != ''.join(self.hintstr): self.getchan().fastmsg("\00304,01Here's a hint: %s" % (''.join(self.hintstr))) |
b16b8c05 | 137 | |
77c61775 | 138 | self.hintsgiven += 1 |
139 | ||
c4763e66 | 140 | if hintnum < self.db['hintnum']: |
be8072b5 | 141 | self.steptimer = MyTimer(self.db['hinttimer'], self.nexthint, args=[hintnum+1]) |
b16b8c05 | 142 | self.steptimer.start() |
143 | else: | |
be8072b5 | 144 | self.steptimer = MyTimer(self.db['hinttimer'], self.nextquestion, args=[True]) |
b16b8c05 | 145 | self.steptimer.start() |
146 | ||
77c61775 | 147 | def doGameOver(self): |
7bd5e7d5 | 148 | msg = self.getchan().msg |
c0eee1b4 | 149 | winner = person(0) |
77c61775 | 150 | try: |
151 | msg("\00312THE GAME IS OVER!!!") | |
00ccae72 | 152 | msg("THE WINNER IS: %s (%s)" % (person(0, True), pts(0))) |
153 | msg("2ND PLACE: %s (%s)" % (person(1, True), pts(1))) | |
154 | msg("3RD PLACE: %s (%s)" % (person(2, True), pts(2))) | |
155 | [msg("%dth place: %s (%s)" % (i+1, person(i, True), pts(i))) for i in range(3,10)] | |
77c61775 | 156 | except IndexError: pass |
09566235 | 157 | except Exception as e: |
158 | msg("DERP! %r" % (e)) | |
c0eee1b4 | 159 | |
5f42c250 | 160 | self.db['lastwinner'] = winner |
161 | self.db['lastwon'] = time.time() | |
162 | ||
7bd5e7d5 | 163 | if self.db['hofpath'] is not None and self.db['hofpath'] != '': |
164 | self.writeHof() | |
165 | ||
77c61775 | 166 | self.db['users'] = {} |
167 | self.db['ranks'] = [] | |
168 | stop() | |
169 | self.closeshop() | |
c0eee1b4 | 170 | |
c53f6514 | 171 | try: |
c0eee1b4 | 172 | t = twitter.Twitter(auth=twitter.OAuth(self.getbot().parent.cfg.get('trivia', 'token'), |
173 | self.getbot().parent.cfg.get('trivia', 'token_sec'), | |
174 | self.getbot().parent.cfg.get('trivia', 'con'), | |
175 | self.getbot().parent.cfg.get('trivia', 'con_sec'))) | |
176 | t.statuses.update(status="Round is over! The winner was %s" % (winner)) | |
c53f6514 | 177 | except: pass #don't care if errors happen updating twitter. |
178 | ||
5871567f | 179 | self.__init__(self.parent, True) |
c53f6514 | 180 | |
7bd5e7d5 | 181 | def writeHof(self): |
182 | def person(num): | |
183 | try: return self.db['users'][self.db['ranks'][num]]['realnick'] | |
184 | except: return "none" | |
185 | def pts(num): | |
186 | try: return str(self.db['users'][self.db['ranks'][num]]['points']) | |
187 | except: return 0 | |
188 | ||
189 | try: | |
190 | f = open(self.db['hofpath'], 'rb+') | |
191 | for i in range(self.db['hoflines']): #skip this many lines | |
192 | f.readline() | |
193 | insertpos = f.tell() | |
194 | fcontents = f.read() | |
195 | f.seek(insertpos) | |
196 | f.write((self.db['hofformat']+"\n") % { | |
197 | 'date': time.strftime("%F", time.gmtime()), | |
00ccae72 | 198 | 'duration': str(datetime.timedelta(seconds=time.time()-self.db['lastwon'])), |
7bd5e7d5 | 199 | 'targetscore': self.db['target'], |
200 | 'firstperson': person(0), | |
201 | 'firstscore': pts(0), | |
202 | 'secondperson': person(1), | |
203 | 'secondscore': pts(1), | |
204 | 'thirdperson': person(2), | |
205 | 'thirdscore': pts(2), | |
206 | }) | |
207 | f.write(fcontents) | |
208 | return True | |
209 | except Exception as e: | |
09566235 | 210 | raise e #FIXME wtf??? |
7bd5e7d5 | 211 | return False |
212 | finally: | |
213 | f.close() | |
214 | ||
c53f6514 | 215 | def endPointVote(self): |
216 | self.getchan().msg("Voting has ended!") | |
217 | votelist = sorted(self.voteamounts.items(), key=lambda item: item[1]) #sort into list of tuples: [(option, number_of_votes), ...] | |
218 | for i in range(len(votelist)-1): | |
219 | item = votelist[i] | |
220 | self.getchan().msg("%s place: %s (%s votes)" % (len(votelist)-i, item[0], item[1])) | |
221 | self.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist[-1][0], votelist[-1][1])) | |
c0eee1b4 | 222 | |
c53f6514 | 223 | self.db['target'] = votelist[-1][0] |
224 | self.pointvote = None | |
77c61775 | 225 | |
38b29993 | 226 | self.nextquestion() #start the game! |
227 | ||
442ed923 | 228 | def nextquestion(self, qskipped=False, iteration=0, skipwait=False): |
7b832b55 | 229 | self.lastqid = self.curqid |
6bdfec48 | 230 | self.curq = None |
7b832b55 | 231 | self.curqid = None |
77c61775 | 232 | if self.gameover == True: |
233 | return self.doGameOver() | |
fadbf980 | 234 | if qskipped: |
be8072b5 | 235 | self.getchan().fastmsg("\00304Fail! The correct answer was: %s" % (self.hintanswer)) |
c0eee1b4 | 236 | self.missedquestions += 1 |
237 | else: | |
238 | self.missedquestions = 0 | |
f8cc0124 | 239 | if 'topicformat' in self.db and self.db['topicformat'] is not None: |
240 | self.getbot().conn.send("TOPIC %s" % (self.db['chan'])) | |
fadbf980 | 241 | |
b16b8c05 | 242 | if isinstance(self.steptimer, threading._Timer): |
243 | self.steptimer.cancel() | |
442ed923 | 244 | if isinstance(self.nextquestiontimer, threading._Timer): |
245 | self.nextquestiontimer.cancel() | |
246 | self.nextquestiontimer = None | |
c0eee1b4 | 247 | |
b16b8c05 | 248 | self.hintstr = None |
77c61775 | 249 | self.hintsgiven = 0 |
b16b8c05 | 250 | self.revealpossibilities = None |
b5c89dfb | 251 | self.reveal = None |
b16b8c05 | 252 | |
c4763e66 | 253 | if self.missedquestions > self.db['maxmissedquestions']: |
c0eee1b4 | 254 | stop() |
ce03ceda | 255 | self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game." % (self.missedquestions)) |
256 | return | |
b16b8c05 | 257 | |
442ed923 | 258 | if skipwait: |
6bdfec48 | 259 | self._nextquestion(iteration) |
442ed923 | 260 | else: |
be8072b5 | 261 | self.nextquestiontimer = MyTimer(self.db['questionpause'], self._nextquestion, args=[iteration]) |
442ed923 | 262 | self.nextquestiontimer.start() |
263 | ||
6bdfec48 | 264 | def _nextquestion(self, iteration): |
e5a3970b | 265 | if self.nextq is not None: |
2520caee | 266 | nextqid = None |
e5a3970b | 267 | nextq = self.nextq |
268 | self.nextq = None | |
c695f740 | 269 | else: |
2520caee | 270 | nextqid = random.randrange(0, len(self.db['questions'])) |
271 | nextq = self.db['questions'][nextqid] | |
b5c89dfb | 272 | |
ebee6edb | 273 | if nextq[0][0] == "!": |
2520caee | 274 | nextqid = None |
b5c89dfb | 275 | nextq = specialQuestion(nextq) |
276 | ||
ebee6edb | 277 | if len(nextq) > 2 and nextq[2] - time.time() < 7*24*60*60 and iteration < 10: |
442ed923 | 278 | return self._nextquestion(iteration=iteration+1) #short-circuit to pick another question |
ebee6edb | 279 | if len(nextq) > 2: |
280 | nextq[2] = time.time() | |
281 | else: | |
282 | nextq.append(time.time()) | |
b5c89dfb | 283 | |
93ce52fd | 284 | if isinstance(nextq[1], basestring): |
285 | nextq[1] = nextq[1].lower() | |
286 | else: | |
287 | nextq[1] = [s.lower() for s in nextq[1]] | |
c695f740 | 288 | |
00ccae72 | 289 | qtext = "\00312,01Next up: " |
bf8676ae | 290 | qtext += "(%5d)" % (random.randint(0,99999)) |
ebee6edb | 291 | qary = nextq[0].split(None) |
71e0b5fb | 292 | qtext += " " |
c695f740 | 293 | for qword in qary: |
6374d61f | 294 | qtext += "\00304,01"+qword+"\00301,01"+chr(random.randrange(0x61,0x7A)) #a-z |
be8072b5 | 295 | self.getbot().fastmsg(self.chan, qtext) |
80d02bd8 | 296 | |
b5c89dfb | 297 | self.curq = nextq |
7b832b55 | 298 | self.curqid = nextqid |
b5c89dfb | 299 | |
ebee6edb | 300 | if isinstance(self.curq[1], basestring): self.hintanswer = self.curq[1] |
301 | else: self.hintanswer = random.choice(self.curq[1]) | |
c0eee1b4 | 302 | |
be8072b5 | 303 | self.steptimer = MyTimer(self.db['hinttimer'], self.nexthint, args=[1]) |
b16b8c05 | 304 | self.steptimer.start() |
305 | ||
80d02bd8 | 306 | def checkanswer(self, answer): |
9557ee54 | 307 | if self.curq is None: |
308 | return False | |
ebee6edb | 309 | elif isinstance(self.curq[1], basestring): |
310 | return answer.lower() == self.curq[1] | |
80d02bd8 | 311 | else: # assume it's a list or something. |
ebee6edb | 312 | return answer.lower() in self.curq[1] |
77c61775 | 313 | |
c53f6514 | 314 | def addpoint(self, user_obj, count=1): |
315 | user_nick = str(user_obj) | |
316 | user = user_nick.lower() # save this separately as we use both | |
80d02bd8 | 317 | if user in self.db['users']: |
318 | self.db['users'][user]['points'] += count | |
319 | else: | |
c53f6514 | 320 | self.db['users'][user] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])} |
9557ee54 | 321 | self.db['ranks'].append(user) |
80d02bd8 | 322 | |
e5a3970b | 323 | 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 | 324 | for i in range(0, len(self.db['ranks'])): |
325 | nick = self.db['ranks'][i] | |
326 | self.db['users'][nick]['rank'] = i | |
77c61775 | 327 | |
e5a3970b | 328 | if self.db['users'][user]['points'] >= self.db['target']: |
77c61775 | 329 | self.gameover = True |
330 | ||
80d02bd8 | 331 | return self.db['users'][user]['points'] |
332 | ||
333 | def points(self, user): | |
9557ee54 | 334 | user = str(user).lower() |
80d02bd8 | 335 | if user in self.db['users']: |
336 | return self.db['users'][user]['points'] | |
337 | else: | |
338 | return 0 | |
339 | ||
340 | def rank(self, user): | |
c695f740 | 341 | user = str(user).lower() |
fadbf980 | 342 | if user in self.db['users']: |
343 | return self.db['users'][user]['rank']+1 | |
344 | else: | |
345 | return len(self.db['users'])+1 | |
77c61775 | 346 | |
c695f740 | 347 | def targetuser(self, user): |
77c61775 | 348 | if len(self.db['ranks']) == 0: return "no one is ranked!" |
349 | ||
c695f740 | 350 | user = str(user).lower() |
fadbf980 | 351 | if user in self.db['users']: |
352 | rank = self.db['users'][user]['rank'] | |
353 | if rank == 0: | |
354 | return "you're in the lead!" | |
355 | else: | |
356 | return self.db['ranks'][rank-1] | |
c695f740 | 357 | else: |
fadbf980 | 358 | return self.db['ranks'][-1] |
c695f740 | 359 | def targetpoints(self, user): |
77c61775 | 360 | if len(self.db['ranks']) == 0: return 0 |
361 | ||
c695f740 | 362 | user = str(user).lower() |
fadbf980 | 363 | if user in self.db['users']: |
364 | rank = self.db['users'][user]['rank'] | |
365 | if rank == 0: | |
366 | return "N/A" | |
367 | else: | |
368 | return self.db['users'][self.db['ranks'][rank-1]]['points'] | |
c695f740 | 369 | else: |
fadbf980 | 370 | return self.db['users'][self.db['ranks'][-1]]['points'] |
80d02bd8 | 371 | |
5871567f | 372 | state = TriviaState() |
9557ee54 | 373 | |
5871567f | 374 | # we have to hook this in modstart, since we don't know the channel until then. |
80d02bd8 | 375 | def trivia_checkanswer(bot, user, chan, *args): |
80d02bd8 | 376 | line = ' '.join([str(arg) for arg in args]) |
377 | if state.checkanswer(line): | |
6bdfec48 | 378 | state.curq = None |
93ce52fd | 379 | if state.hintanswer.lower() == line.lower(): |
380 | bot.fastmsg(chan, "\00312%s\003 has it! The answer was \00312%s\003. New score: %d. Rank: %d. Target: %s (%s)." % (user, line, state.addpoint(user), state.rank(user), state.targetuser(user), state.targetpoints(user))) | |
381 | else: | |
382 | bot.fastmsg(chan, "\00312%s\003 has it! The answer was \00312%s\003 (hinted answer: %s). New score: %d. Rank: %d. Target: %s (%s)." % (user, line, state.hintanswer, state.addpoint(user), state.rank(user), state.targetuser(user), state.targetpoints(user))) | |
77c61775 | 383 | if state.hintsgiven == 0: |
6374d61f | 384 | bot.msg(chan, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user))) |
9557ee54 | 385 | state.nextquestion() |
80d02bd8 | 386 | |
fb20be7c | 387 | @lib.hook(needchan=False) |
388 | def points(bot, user, chan, realtarget, *args): | |
6bdfec48 | 389 | if chan is not None and realtarget == chan.name: replyto = chan |
80d02bd8 | 390 | else: replyto = user |
391 | ||
392 | if len(args) != 0: who = args[0] | |
393 | else: who = user | |
394 | ||
395 | bot.msg(replyto, "%s has %d points." % (who, state.points(who))) | |
396 | ||
fb20be7c | 397 | @lib.hook(glevel=lib.STAFF, needchan=False) |
80d02bd8 | 398 | @lib.argsGE(1) |
fb20be7c | 399 | def give(bot, user, chan, realtarget, *args): |
80d02bd8 | 400 | whoto = args[0] |
c695f740 | 401 | if len(args) > 1: |
402 | numpoints = int(args[1]) | |
403 | else: | |
404 | numpoints = 1 | |
405 | balance = state.addpoint(whoto, numpoints) | |
fadbf980 | 406 | |
c695f740 | 407 | bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance)) |
408 | ||
fb20be7c | 409 | @lib.hook(glevel=1, needchan=False) |
410 | def setnextid(bot, user, chan, realtarget, *args): | |
9306587e | 411 | try: |
412 | qid = int(args[0]) | |
413 | state.nextq = state.db['questions'][qid] | |
71e0b5fb | 414 | if user.glevel >= lib.STAFF: |
415 | respstr = "Done. Next question is: %s" % (state.nextq[0]) | |
416 | else: | |
417 | respstr = "Done." | |
418 | bot.msg(user, respstr) | |
9306587e | 419 | except Exception as e: |
420 | bot.msg(user, "Error: %s" % (e)) | |
421 | ||
fb20be7c | 422 | @lib.hook(glevel=lib.STAFF, needchan=False) |
c695f740 | 423 | @lib.argsGE(1) |
fb20be7c | 424 | def setnext(bot, user, chan, realtarget, *args): |
c695f740 | 425 | line = ' '.join([str(arg) for arg in args]) |
426 | linepieces = line.split('*') | |
b5c89dfb | 427 | if len(linepieces) < 2: |
428 | bot.msg(user, "Error: need <question>*<answer>") | |
429 | return | |
c695f740 | 430 | question = linepieces[0].strip() |
431 | answer = linepieces[1].strip() | |
ebee6edb | 432 | state.nextq = [question, answer] |
c695f740 | 433 | bot.msg(user, "Done.") |
434 | ||
fb20be7c | 435 | @lib.hook(glevel=1, needchan=False) |
436 | def skip(bot, user, chan, realtarget, *args): | |
442ed923 | 437 | state.nextquestion(qskipped=True, skipwait=True) |
c695f740 | 438 | |
fb20be7c | 439 | @lib.hook(needchan=False) |
440 | def start(bot, user, chan, realtarget, *args): | |
6bdfec48 | 441 | if chan is not None and realtarget == chan.name: replyto = chan |
c695f740 | 442 | else: replyto = user |
443 | ||
77a265cd | 444 | if chan is not None and chan.name != state.db['chan']: |
445 | bot.msg(replyto, "That command isn't valid here.") | |
446 | return | |
447 | ||
442ed923 | 448 | if state.curq is None and state.pointvote is None and state.nextquestiontimer is None: |
77a265cd | 449 | bot.msg(state.db['chan'], "%s has started the game!" % (user)) |
442ed923 | 450 | state.nextquestion(skipwait=True) |
c53f6514 | 451 | elif state.pointvote is not None: |
00ccae72 | 452 | bot.msg(user, "There's a vote in progress!") |
c695f740 | 453 | else: |
00ccae72 | 454 | bot.msg(user, "Game is already started!") |
c695f740 | 455 | |
9306587e | 456 | @lib.hook('stop', glevel=1, needchan=False) |
c695f740 | 457 | def cmd_stop(bot, user, chan, realtarget, *args): |
fadbf980 | 458 | if stop(): |
459 | bot.msg(state.chan, "Game stopped by %s" % (user)) | |
460 | else: | |
461 | bot.msg(user, "Game isn't running.") | |
c695f740 | 462 | |
b9daa51a | 463 | @lib.hook('exception', glevel=lib.OWNER) |
be8072b5 | 464 | def cmd_exception(*args, **kwargs): |
465 | raise Exception() | |
466 | ||
fadbf980 | 467 | def stop(): |
3b89ebff | 468 | state.curq = None |
469 | state.nextq = None | |
09566235 | 470 | try: |
471 | state.steptimer.cancel() | |
472 | except Exception as e: | |
473 | print "!!! steptimer.cancel(): %s %r" % (e,e) | |
3b89ebff | 474 | state.steptimer = None |
09566235 | 475 | try: |
476 | state.nextquestiontimer.cancel() | |
477 | except Exception as e: | |
478 | print "!!! nextquestiontimer.cancel(): %s %r" % (e,e) | |
3b89ebff | 479 | state.nextquestiontimer = None |
480 | return True | |
80d02bd8 | 481 | |
fb20be7c | 482 | @lib.hook(needchan=False) |
7b832b55 | 483 | @lib.argsGE(1) |
fb20be7c | 484 | def badq(bot, user, chan, realtarget, *args): |
7b832b55 | 485 | lastqid = state.lastqid |
486 | curqid = state.curqid | |
487 | ||
488 | reason = ' '.join(args) | |
489 | state.db['badqs'].append([lastqid, curqid, reason]) | |
490 | bot.msg(user, "Reported bad question.") | |
2520caee | 491 | |
fb20be7c | 492 | @lib.hook(glevel=lib.STAFF, needchan=False) |
493 | def badqs(bot, user, chan, realtarget, *args): | |
2520caee | 494 | if len(state.db['badqs']) == 0: |
495 | bot.msg(user, "No reports.") | |
496 | ||
497 | for i in range(len(state.db['badqs'])): | |
498 | try: | |
499 | report = state.db['badqs'][i] | |
7b832b55 | 500 | bot.msg(user, "Report #%d: LastQ=%r CurQ=%r: %s" % (i, report[0], report[1], report[2])) |
501 | try: lq = state.db['questions'][int(report[0])] | |
502 | except Exception as e: lq = (None,None) | |
503 | try: cq = state.db['questions'][int(report[1])] | |
504 | except Exception as e: cq = (None, None) | |
505 | bot.msg(user, "- Last: %s*%s" % (lq[0], lq[1])) | |
506 | bot.msg(user, "- Curr: %s*%s" % (cq[0], cq[1])) | |
2520caee | 507 | except Exception as e: |
508 | bot.msg(user, "- Exception: %r" % (e)) | |
509 | ||
fb20be7c | 510 | @lib.hook(glevel=lib.STAFF, needchan=False) |
511 | def clearbadqs(bot, user, chan, realtarget, *args): | |
2520caee | 512 | state.db['badqs'] = [] |
513 | bot.msg(user, "Cleared reports.") | |
514 | ||
fb20be7c | 515 | @lib.hook(glevel=lib.STAFF, needchan=False) |
2520caee | 516 | @lib.argsEQ(1) |
fb20be7c | 517 | def delbadq(bot, user, chan, realtarget, *args): |
2520caee | 518 | qid = int(args[0]) |
519 | del state.db['badqs'][qid] | |
520 | bot.msg(user, "Removed report #%d" % (qid)) | |
521 | ||
fb20be7c | 522 | @lib.hook(needchan=False) |
523 | def rank(bot, user, chan, realtarget, *args): | |
6bdfec48 | 524 | if chan is not None and realtarget == chan.name: replyto = chan |
80d02bd8 | 525 | else: replyto = user |
526 | ||
c695f740 | 527 | if len(args) != 0: who = args[0] |
528 | else: who = user | |
529 | ||
77c61775 | 530 | bot.msg(replyto, "%s is in %d place (%s points). Target is: %s (%s points)." % (who, state.rank(who), state.points(who), state.targetuser(who), state.targetpoints(who))) |
fadbf980 | 531 | |
fb20be7c | 532 | @lib.hook(needchan=False) |
533 | def top10(bot, user, chan, realtarget, *args): | |
77c61775 | 534 | if len(state.db['ranks']) == 0: |
535 | return bot.msg(state.db['chan'], "No one is ranked!") | |
fadbf980 | 536 | |
8ef938d0 | 537 | max = len(state.db['ranks']) |
538 | if max > 10: | |
539 | max = 10 | |
2bb267e0 | 540 | replylist = ', '.join(["%s (%s) %s" % (person(x), country(x), pts(x)) for x in range(max)]) |
00ccae72 | 541 | bot.msg(state.db['chan'], "Top 10: %s" % (replylist)) |
77c61775 | 542 | |
fb20be7c | 543 | @lib.hook(glevel=lib.ADMIN, needchan=False) |
544 | def settarget(bot, user, chan, realtarget, *args): | |
77c61775 | 545 | try: |
546 | state.db['target'] = int(args[0]) | |
547 | bot.msg(state.db['chan'], "Target has been changed to %s points!" % (state.db['target'])) | |
38b29993 | 548 | |
7bd5e7d5 | 549 | if state.pointvote is not None: |
550 | state.pointvote.cancel() | |
551 | state.pointvote = None | |
38b29993 | 552 | bot.msg(state.db['chan'], "Vote has been cancelled!") |
7bd5e7d5 | 553 | except Exception as e: |
554 | print e | |
77c61775 | 555 | bot.msg(user, "Failed to set target.") |
556 | ||
fb20be7c | 557 | @lib.hook(needchan=False) |
558 | def vote(bot, user, chan, realtarget, *args): | |
7bd5e7d5 | 559 | if state.pointvote is not None: |
38b29993 | 560 | if int(args[0]) in state.voteamounts: |
561 | state.voteamounts[int(args[0])] += 1 | |
562 | bot.msg(user, "Your vote has been recorded.") | |
563 | else: | |
564 | bot.msg(user, "Sorry - that's not an option!") | |
565 | else: | |
566 | bot.msg(user, "There's no vote in progress.") | |
567 | ||
fb20be7c | 568 | @lib.hook(glevel=lib.ADMIN, needchan=False) |
569 | def maxmissed(bot, user, chan, realtarget, *args): | |
c4763e66 | 570 | try: |
571 | state.db['maxmissedquestions'] = int(args[0]) | |
572 | bot.msg(state.db['chan'], "Max missed questions before round ends has been changed to %s." % (state.db['maxmissedquestions'])) | |
573 | except: | |
574 | bot.msg(user, "Failed to set maxmissed.") | |
575 | ||
fb20be7c | 576 | @lib.hook(glevel=lib.ADMIN, needchan=False) |
577 | def hinttimer(bot, user, chan, realtarget, *args): | |
c4763e66 | 578 | try: |
579 | state.db['hinttimer'] = float(args[0]) | |
580 | bot.msg(state.db['chan'], "Time between hints has been changed to %s." % (state.db['hinttimer'])) | |
581 | except: | |
582 | bot.msg(user, "Failed to set hint timer.") | |
583 | ||
fb20be7c | 584 | @lib.hook(glevel=lib.ADMIN, needchan=False) |
585 | def hintnum(bot, user, chan, realtarget, *args): | |
c4763e66 | 586 | try: |
587 | state.db['hintnum'] = int(args[0]) | |
588 | bot.msg(state.db['chan'], "Max number of hints has been changed to %s." % (state.db['hintnum'])) | |
589 | except: | |
590 | bot.msg(user, "Failed to set hintnum.") | |
591 | ||
fb20be7c | 592 | @lib.hook(glevel=lib.ADMIN, needchan=False) |
593 | def questionpause(bot, user, chan, realtarget, *args): | |
442ed923 | 594 | try: |
595 | state.db['questionpause'] = float(args[0]) | |
596 | bot.msg(state.db['chan'], "Pause between questions has been changed to %s." % (state.db['questionpause'])) | |
597 | except: | |
598 | bot.msg(user, "Failed to set questionpause.") | |
599 | ||
fb20be7c | 600 | @lib.hook(glevel=1, needchan=False) |
601 | def findq(bot, user, chan, realtarget, *args): | |
bf8676ae | 602 | if len(args) == 0: |
603 | bot.msg(user, "You need to specify a search string.") | |
604 | return | |
605 | ||
aaa67e6d | 606 | searcher = re.compile(' '.join(args)) |
607 | matches = [str(i) for i in range(len(state.db['questions'])) if searcher.search(state.db['questions'][i][0]) is not None] | |
bf8676ae | 608 | if len(matches) > 25: |
609 | bot.msg(user, "Too many matches! (>25)") | |
610 | elif len(matches) > 1: | |
c4763e66 | 611 | bot.msg(user, "Multiple matches: %s" % (', '.join(matches))) |
612 | elif len(matches) == 1: | |
613 | bot.msg(user, "One match: %s" % (matches[0])) | |
614 | else: | |
615 | bot.msg(user, "No match.") | |
616 | ||
b9daa51a | 617 | @lib.hook(glevel=lib.STAFF, needchan=False) |
618 | def showq(bot, user, chan, realtarget, *args): | |
619 | try: | |
620 | qid = int(args[0]) | |
621 | except: | |
622 | bot.msg(user, "Specify a numeric question ID.") | |
623 | return | |
624 | try: | |
625 | q = state.db['questions'][qid] | |
626 | except: | |
627 | bot.msg(user, "ID not valid.") | |
628 | return | |
629 | bot.msg(user, "%s: %s*%s" % (qid, q[0], q[1])) | |
630 | ||
fb20be7c | 631 | @lib.hook(('delq', 'deleteq'), glevel=lib.STAFF, needchan=False) |
632 | def delq(bot, user, chan, realtarget, *args): | |
c4763e66 | 633 | try: |
634 | backup = state.db['questions'][int(args[0])] | |
635 | del state.db['questions'][int(args[0])] | |
b9daa51a | 636 | state.savedb() |
ebee6edb | 637 | bot.msg(user, "Deleted %s*%s" % (backup[0], backup[1])) |
c4763e66 | 638 | except: |
b9daa51a | 639 | bot.msg(user, "Couldn't delete that question. %r" % (e)) |
c4763e66 | 640 | |
fb20be7c | 641 | @lib.hook(glevel=lib.STAFF, needchan=False) |
642 | def addq(bot, user, chan, realtarget, *args): | |
c4763e66 | 643 | line = ' '.join([str(arg) for arg in args]) |
644 | linepieces = line.split('*') | |
645 | if len(linepieces) < 2: | |
646 | bot.msg(user, "Error: need <question>*<answer>") | |
647 | return | |
648 | question = linepieces[0].strip() | |
649 | answer = linepieces[1].strip() | |
ebee6edb | 650 | state.db['questions'].append([question, answer]) |
b9daa51a | 651 | state.savedb() |
c4763e66 | 652 | bot.msg(user, "Done. Question is #%s" % (len(state.db['questions'])-1)) |
653 | ||
654 | ||
fb20be7c | 655 | @lib.hook(needchan=False) |
656 | def triviahelp(bot, user, chan, realtarget, *args): | |
2bb267e0 | 657 | bot.slowmsg(user, "START") |
658 | bot.slowmsg(user, "TOP10") | |
659 | bot.slowmsg(user, "POINTS [<user>]") | |
660 | bot.slowmsg(user, "RANK [<user>]") | |
661 | bot.slowmsg(user, "BADQ <reason> (include info to identify question)") | |
9306587e | 662 | if user.glevel >= 1: |
b9daa51a | 663 | bot.slowmsg(user, "SKIP (KNOWN)") |
664 | bot.slowmsg(user, "STOP (KNOWN)") | |
665 | bot.slowmsg(user, "FINDQ <question> (KNOWN)") | |
666 | bot.slowmsg(user, "SETNEXTID <qid> (KNOWN)") | |
9306587e | 667 | if user.glevel >= lib.STAFF: |
b9daa51a | 668 | bot.slowmsg(user, "GIVE <user> [<points>] (STAFF)") |
669 | bot.slowmsg(user, "SETNEXT <q>*<a> (STAFF)") | |
670 | bot.slowmsg(user, "ADDQ <q>*<a> (STAFF)") | |
671 | bot.slowmsg(user, "DELQ <q>*<a> (STAFF) [aka DELETEQ]") | |
672 | bot.slowmsg(user, "SHOWQ <qid> (STAFF)") | |
673 | bot.slowmsg(user, "BADQS (STAFF)") | |
674 | bot.slowmsg(user, "CLEARBADQS (STAFF)") | |
675 | bot.slowmsg(user, "DELBADQ <reportid> (STAFF)") | |
9306587e | 676 | if user.glevel >= lib.ADMIN: |
b9daa51a | 677 | bot.slowmsg(user, "SETTARGET <points> (ADMIN)") |
678 | bot.slowmsg(user, "MAXMISSED <questions> (ADMIN)") | |
679 | bot.slowmsg(user, "HINTTIMER <float seconds> (ADMIN)") | |
680 | bot.slowmsg(user, "HINTNUM <hints> (ADMIN)") | |
681 | bot.slowmsg(user, "QUESTIONPAUSE <float seconds> (ADMIN)") | |
b5c89dfb | 682 | |
6374d61f | 683 | @lib.hooknum(417) |
684 | def num_417(bot, textline): | |
93ce52fd | 685 | # bot.fastmsg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...") |
442ed923 | 686 | state.nextquestion(qskipped=False, skipwait=True) |
6374d61f | 687 | |
f8cc0124 | 688 | @lib.hooknum(332) |
689 | def num_TOPIC(bot, textline): | |
690 | pieces = textline.split(None, 4) | |
691 | chan = pieces[3] | |
692 | if chan != state.db['chan']: | |
693 | return | |
694 | gottopic = pieces[4][1:] | |
695 | ||
696 | formatted = state.db['topicformat'] % { | |
697 | 'chan': state.db['chan'], | |
8ef938d0 | 698 | 'top1': "%s (%s)" % (person(0), pts(0)), |
699 | 'top3': '/'.join([ | |
700 | "%s (%s)" % (person(x), pts(x)) | |
701 | for x in range(3) if x < len(state.db['ranks']) | |
702 | ]), | |
703 | 'top3c': ' '.join([ | |
704 | "%s (%s, %s)" % (person(x), pts(x), country(x)) | |
705 | for x in range(3) if x < len(state.db['ranks']) | |
706 | ]), | |
707 | 'top10': ' '.join([ | |
708 | "%s (%s)" % (person(x), pts(x)) | |
709 | for x in range(10) if x < len(state.db['ranks']) | |
710 | ]), | |
711 | 'top10c': ' '.join([ | |
712 | "%s (%s, %s)" % (person(x), pts(x), country(x)) | |
713 | for x in range(10) if x < len(state.db['ranks']) | |
714 | ]), | |
5f42c250 | 715 | 'lastwinner': state.db['lastwinner'], |
716 | 'lastwon': time.strftime("%b %d", time.gmtime(state.db['lastwon'])), | |
f8cc0124 | 717 | 'target': state.db['target'], |
718 | } | |
719 | if gottopic != formatted: | |
720 | state.getbot().conn.send("TOPIC %s :%s" % (state.db['chan'], formatted)) | |
721 | ||
b5c89dfb | 722 | |
723 | def specialQuestion(oldq): | |
ebee6edb | 724 | newq = [oldq[0], oldq[1]] |
725 | qtype = oldq[0].upper() | |
b5c89dfb | 726 | |
727 | if qtype == "!MONTH": | |
ebee6edb | 728 | newq[0] = "What month is it currently (in UTC)?" |
729 | newq[1] = time.strftime("%B", time.gmtime()).lower() | |
b5c89dfb | 730 | elif qtype == "!MATH+": |
731 | randnum1 = random.randrange(0, 11) | |
732 | randnum2 = random.randrange(0, 11) | |
ebee6edb | 733 | newq[0] = "What is %d + %d?" % (randnum1, randnum2) |
734 | newq[1] = spellout(randnum1+randnum2) | |
b5c89dfb | 735 | return newq |
736 | ||
737 | def spellout(num): | |
738 | return [ | |
00ccae72 | 739 | "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", |
b5c89dfb | 740 | "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", |
741 | "sixteen", "seventeen", "eighteen", "nineteen", "twenty" | |
742 | ][num] |