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