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