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