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