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