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