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