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