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