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