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