1 # Erebus IRC bot - Author: Erebus Team
3 # This file is released into the public domain; see http://unlicense.org/
7 'author': 'Erebus Team',
8 'license': 'public domain',
9 'compatible': [1], # compatible module API versions
10 'depends': [], # other modules required to work properly?
15 lib
= modlib
.modlib(__name__
)
16 def modstart(parent
, *args
, **kwargs
):
18 return lib
.modstart(parent
, *args
, **kwargs
)
19 def modstop(*args
, **kwargs
):
24 return lib
.modstop(*args
, **kwargs
)
27 import json
, random
, threading
, re
, time
, datetime
31 except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
33 def findnth(haystack
, needle
, n
): #http://stackoverflow.com/a/1884151
34 parts
= haystack
.split(needle
, n
+1)
37 return len(haystack
)-len(parts
[-1])-len(needle
)
39 class TriviaState(object):
40 def __init__(self
, questionfile
, parent
=None, pointvote
=False):
42 self
.questionfile
= self
.getbot().parent
.cfg
.get('trivia', 'jsonpath')
43 self
.db
= json
.load(open(questionfile
, "r"))
44 self
.chan
= self
.db
['chan']
49 self
.hintanswer
= None
51 self
.revealpossibilities
= None
53 self
.missedquestions
= 0
55 if 'starttime' not in self
.db
or self
.db
['starttime'] is None:
56 self
.db
['starttime'] = time
.time()
59 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']])))
60 self
.getchan().msg("You have %s seconds." % (self
.db
['votetimer']))
61 self
.voteamounts
= dict([(x
, 0) for x
in self
.db
['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
62 self
.pointvote
= threading
.Timer(self
.db
['votetimer'], self
.endPointVote
)
63 self
.pointvote
.start()
70 if threading
is not None and threading
._Timer
is not None and isinstance(self
.steptimer
, threading
._Timer
):
71 self
.steptimer
.cancel()
72 if json
is not None and json
.dump
is not None:
73 json
.dump(self
.db
, open(self
.questionfile
, "w"))#, indent=4, separators=(',', ': '))
76 return self
.parent
.channel(self
.chan
)
78 return self
.getchan().bot
80 def nexthint(self
, hintnum
):
81 answer
= self
.hintanswer
83 if self
.hintstr
is None or self
.revealpossibilities
is None or self
.reveal
is None:
84 self
.hintstr
= list(re
.sub(r
'[a-zA-Z0-9]', '*', answer
))
85 self
.revealpossibilities
= range(''.join(self
.hintstr
).count('*'))
86 self
.reveal
= int(''.join(self
.hintstr
).count('*') * (7/24.0))
88 for i
in range(self
.reveal
):
89 revealcount
= random
.choice(self
.revealpossibilities
)
90 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
91 self
.revealpossibilities
.remove(revealcount
)
92 self
.hintstr
[revealloc
] = answer
[revealloc
]
93 self
.parent
.channel(self
.chan
).bot
.msg(self
.chan
, "\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
97 if hintnum
< self
.db
['hintnum']:
98 self
.steptimer
= threading
.Timer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
99 self
.steptimer
.start()
101 self
.steptimer
= threading
.Timer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
102 self
.steptimer
.start()
104 def doGameOver(self
):
105 msg
= self
.getchan().msg
106 def person(num
): return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
107 def pts(num
): return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
110 msg("\00312THE GAME IS OVER!!!")
111 msg("THE WINNER IS: %s (%s)" % (person(0), pts(0)))
112 msg("2ND PLACE: %s (%s)" % (person(1), pts(1)))
113 msg("3RD PLACE: %s (%s)" % (person(2), pts(2)))
114 [msg("%dth place: %s (%s)" % (i
+1, person(i
), pts(i
))) for i
in range(3,10)]
115 except IndexError: pass
116 except Exception as e
: msg("DERP! %r" % (e
))
118 if self
.db
['hofpath'] is not None and self
.db
['hofpath'] != '':
121 self
.db
['users'] = {}
122 self
.db
['ranks'] = []
127 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
128 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
129 self
.getbot().parent
.cfg
.get('trivia', 'con'),
130 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
131 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
132 except: pass #don't care if errors happen updating twitter.
134 self
.__init
__(self
.questionfile
, self
.parent
, True)
138 try: return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
139 except: return "none"
141 try: return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
145 f
= open(self
.db
['hofpath'], 'rb+')
146 for i
in range(self
.db
['hoflines']): #skip this many lines
151 f
.write((self
.db
['hofformat']+"\n") % {
152 'date': time
.strftime("%F", time
.gmtime()),
153 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['starttime'])),
154 'targetscore': self
.db
['target'],
155 'firstperson': person(0),
156 'firstscore': pts(0),
157 'secondperson': person(1),
158 'secondscore': pts(1),
159 'thirdperson': person(2),
160 'thirdscore': pts(2),
164 except Exception as e
:
170 def endPointVote(self
):
171 self
.getchan().msg("Voting has ended!")
172 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
173 for i
in range(len(votelist
)-1):
175 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
176 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
178 self
.db
['target'] = votelist
[-1][0]
179 self
.pointvote
= None
181 self
.nextquestion() #start the game!
183 def nextquestion(self
, qskipped
=False, iteration
=0):
184 if self
.gameover
== True:
185 return self
.doGameOver()
187 self
.getchan().msg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
188 self
.missedquestions
+= 1
190 self
.missedquestions
= 0
192 if isinstance(self
.steptimer
, threading
._Timer
):
193 self
.steptimer
.cancel()
197 self
.revealpossibilities
= None
200 if self
.missedquestions
> self
.db
['maxmissedquestions']:
202 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game.")
204 if state
.nextq
is not None:
208 nextq
= random
.choice(self
.db
['questions'])
210 if nextq
['question'][0] == "!":
211 nextq
= specialQuestion(nextq
)
213 if iteration
< 10 and 'lastasked' in nextq
and nextq
['lastasked'] - time
.time() < 24*60*60:
214 return self
.nextquestion(iteration
=iteration
+1) #short-circuit to pick another question
215 nextq
['lastasked'] = time
.time()
217 nextq
['answer'] = nextq
['answer'].lower()
219 qtext
= "\00304,01Next up: "
220 qary
= nextq
['question'].split(None)
222 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(random
.randrange(0x61,0x7A)) #a-z
223 self
.getbot().msg(self
.chan
, qtext
)
227 if isinstance(self
.curq
['answer'], basestring
): self
.hintanswer
= self
.curq
['answer']
228 else: self
.hintanswer
= random
.choice(self
.curq
['answer'])
230 self
.steptimer
= threading
.Timer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
231 self
.steptimer
.start()
233 def checkanswer(self
, answer
):
234 if self
.curq
is None:
236 elif isinstance(self
.curq
['answer'], basestring
):
237 return answer
.lower() == self
.curq
['answer']
238 else: # assume it's a list or something.
239 return answer
.lower() in self
.curq
['answer']
241 def addpoint(self
, user_obj
, count
=1):
242 user_nick
= str(user_obj
)
243 user
= user_nick
.lower() # save this separately as we use both
244 if user
in self
.db
['users']:
245 self
.db
['users'][user
]['points'] += count
247 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
248 self
.db
['ranks'].append(user
)
250 self
.db
['ranks'].sort(key
=lambda nick
: state
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
251 for i
in range(0, len(self
.db
['ranks'])):
252 nick
= self
.db
['ranks'][i
]
253 self
.db
['users'][nick
]['rank'] = i
255 if self
.db
['users'][user
]['points'] >= state
.db
['target']:
258 return self
.db
['users'][user
]['points']
260 def points(self
, user
):
261 user
= str(user
).lower()
262 if user
in self
.db
['users']:
263 return self
.db
['users'][user
]['points']
267 def rank(self
, user
):
268 user
= str(user
).lower()
269 if user
in self
.db
['users']:
270 return self
.db
['users'][user
]['rank']+1
272 return len(self
.db
['users'])+1
274 def targetuser(self
, user
):
275 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
277 user
= str(user
).lower()
278 if user
in self
.db
['users']:
279 rank
= self
.db
['users'][user
]['rank']
281 return "you're in the lead!"
283 return self
.db
['ranks'][rank
-1]
285 return self
.db
['ranks'][-1]
286 def targetpoints(self
, user
):
287 if len(self
.db
['ranks']) == 0: return 0
289 user
= str(user
).lower()
290 if user
in self
.db
['users']:
291 rank
= self
.db
['users'][user
]['rank']
295 return self
.db
['users'][self
.db
['ranks'][rank
-1]]['points']
297 return self
.db
['users'][self
.db
['ranks'][-1]]['points']
299 state
= TriviaState("/home/jrunyon/erebus/modules/trivia.json") #TODO get path from config
301 @lib.hookchan(state
.db
['chan'])
302 def trivia_checkanswer(bot
, user
, chan
, *args
):
303 line
= ' '.join([str(arg
) for arg
in args
])
304 if state
.checkanswer(line
):
305 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
)))
306 if state
.hintsgiven
== 0:
307 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
310 @lib.hook('points', needchan
=False)
311 def cmd_points(bot
, user
, chan
, realtarget
, *args
):
312 if chan
== realtarget
: replyto
= chan
315 if len(args
) != 0: who
= args
[0]
318 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
320 @lib.hook('give', clevel
=lib
.OP
, needchan
=False)
322 def cmd_give(bot
, user
, chan
, realtarget
, *args
):
325 numpoints
= int(args
[1])
328 balance
= state
.addpoint(whoto
, numpoints
)
330 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
332 @lib.hook('setnext', clevel
=lib
.OP
, needchan
=False)
334 def cmd_setnext(bot
, user
, chan
, realtarget
, *args
):
335 line
= ' '.join([str(arg
) for arg
in args
])
336 linepieces
= line
.split('*')
337 if len(linepieces
) < 2:
338 bot
.msg(user
, "Error: need <question>*<answer>")
340 question
= linepieces
[0].strip()
341 answer
= linepieces
[1].strip()
342 state
.nextq
= {'question':question,'answer':answer}
343 bot
.msg(user
, "Done.")
345 @lib.hook('skip', clevel
=lib
.KNOWN
, needchan
=False)
346 def cmd_skip(bot
, user
, chan
, realtarget
, *args
):
347 state
.nextquestion(True)
349 @lib.hook('start', needchan
=False)
350 def cmd_start(bot
, user
, chan
, realtarget
, *args
):
351 if chan
== realtarget
: replyto
= chan
354 if state
.curq
is None and state
.pointvote
is None:
356 elif state
.pointvote
is not None:
357 bot
.msg(replyto
, "There's a vote in progress!")
359 bot
.msg(replyto
, "Game is already started!")
361 #FIXME @lib.hook('stop', clevel=lib.KNOWN, needchan=False)
362 @lib.hook('stop', needchan
=False) #FIXME
363 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
365 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
367 bot
.msg(user
, "Game isn't running.")
370 if state
.curq
is not None:
373 state
.steptimer
.cancel()
374 except Exception as e
:
375 print "!!! steptimer.cancel(): e"
380 @lib.hook('rank', needchan
=False)
381 def cmd_rank(bot
, user
, chan
, realtarget
, *args
):
382 if chan
== realtarget
: replyto
= chan
385 if len(args
) != 0: who
= args
[0]
388 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
)))
390 @lib.hook('top10', needchan
=False)
391 def cmd_top10(bot
, user
, chan
, realtarget
, *args
):
392 if len(state
.db
['ranks']) == 0:
393 return bot
.msg(state
.db
['chan'], "No one is ranked!")
396 for nick
in state
.db
['ranks'][0:10]:
397 user
= state
.db
['users'][nick
]
398 replylist
.append("%s (%s)" % (user
['realnick'], user
['points']))
399 bot
.msg(state
.db
['chan'], ', '.join(replylist
))
401 @lib.hook('settarget', clevel
=lib
.MASTER
, needchan
=False)
402 def cmd_settarget(bot
, user
, chan
, realtarget
, *args
):
404 state
.db
['target'] = int(args
[0])
405 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
407 if state
.pointvote
is not None:
408 state
.pointvote
.cancel()
409 state
.pointvote
= None
410 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
411 except Exception as e
:
413 bot
.msg(user
, "Failed to set target.")
415 @lib.hook('vote', needchan
=False)
416 def cmd_vote(bot
, user
, chan
, realtarget
, *args
):
417 if state
.pointvote
is not None:
418 if int(args
[0]) in state
.voteamounts
:
419 state
.voteamounts
[int(args
[0])] += 1
420 bot
.msg(user
, "Your vote has been recorded.")
422 bot
.msg(user
, "Sorry - that's not an option!")
424 bot
.msg(user
, "There's no vote in progress.")
426 @lib.hook('maxmissed', clevel
=lib
.MASTER
, needchan
=False)
427 def cmd_maxmissed(bot
, user
, chan
, realtarget
, *args
):
429 state
.db
['maxmissedquestions'] = int(args
[0])
430 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
432 bot
.msg(user
, "Failed to set maxmissed.")
434 @lib.hook('hinttimer', clevel
=lib
.MASTER
, needchan
=False)
435 def cmd_hinttimer(bot
, user
, chan
, realtarget
, *args
):
437 state
.db
['hinttimer'] = float(args
[0])
438 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
440 bot
.msg(user
, "Failed to set hint timer.")
442 @lib.hook('hintnum', clevel
=lib
.MASTER
, needchan
=False)
443 def cmd_hintnum(bot
, user
, chan
, realtarget
, *args
):
445 state
.db
['hintnum'] = int(args
[0])
446 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
448 bot
.msg(user
, "Failed to set hintnum.")
450 @lib.hook('findq', clevel
=lib
.KNOWN
, needchan
=False)
451 def cmd_findquestion(bot
, user
, chan
, realtarget
, *args
):
452 matches
= [str(i
) for i
in range(len(state
.db
['questions'])) if state
.db
['questions'][i
]['question'] == ' '.join(args
)] #FIXME: looser equality check
454 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
455 elif len(matches
) == 1:
456 bot
.msg(user
, "One match: %s" % (matches
[0]))
458 bot
.msg(user
, "No match.")
460 @lib.hook('delq', clevel
=lib
.OP
, needchan
=False)
461 @lib.hook('deleteq', clevel
=lib
.OP
, needchan
=False)
462 def cmd_deletequestion(bot
, user
, chan
, realtarget
, *args
):
464 backup
= state
.db
['questions'][int(args
[0])]
465 del state
.db
['questions'][int(args
[0])]
466 bot
.msg(user
, "Deleted %s*%s" % (backup
['question'], backup
['answer']))
468 bot
.msg(user
, "Couldn't delete that question.")
470 @lib.hook('addq', clevel
=lib
.OP
, needchan
=False)
471 def cmd_addquestion(bot
, user
, chan
, realtarget
, *args
):
472 line
= ' '.join([str(arg
) for arg
in args
])
473 linepieces
= line
.split('*')
474 if len(linepieces
) < 2:
475 bot
.msg(user
, "Error: need <question>*<answer>")
477 question
= linepieces
[0].strip()
478 answer
= linepieces
[1].strip()
479 state
.db
['questions'].append({'question':question,'answer':answer}
)
480 bot
.msg(user
, "Done. Question is #%s" % (len(state
.db
['questions'])-1))
483 @lib.hook('triviahelp', needchan
=False)
484 def cmd_triviahelp(bot
, user
, chan
, realtarget
, *args
):
485 bot
.msg(user
, "START")
486 bot
.msg(user
, "TOP10")
487 bot
.msg(user
, "POINTS [<user>]")
488 bot
.msg(user
, "RANK [<user>]")
489 if bot
.parent
.channel(state
.db
['chan']).levelof(user
.auth
) >= lib
.KNOWN
:
490 bot
.msg(user
, "SKIP (>=KNOWN )")
491 bot
.msg(user
, "STOP (>=KNOWN )")
492 bot
.msg(user
, "FINDQ <question> (>=KNOWN )")
493 if bot
.parent
.channel(state
.db
['chan']).levelof(user
.auth
) >= lib
.OP
:
494 bot
.msg(user
, "GIVE <user> [<points>] (>=OP )")
495 bot
.msg(user
, "SETNEXT <q>*<a> (>=OP )")
496 bot
.msg(user
, "ADDQ <q>*<a> (>=OP )")
497 bot
.msg(user
, "DELETEQ <q>*<a> (>=OP ) [aka DELQ]")
498 if bot
.parent
.channel(state
.db
['chan']).levelof(user
.auth
) >= lib
.MASTER
:
499 bot
.msg(user
, "SETTARGET <points> (>=MASTER)")
500 bot
.msg(user
, "MAXMISSED <questions> (>=MASTER)")
501 bot
.msg(user
, "HINTTIMER <float seconds> (>=MASTER)")
502 bot
.msg(user
, "HINTNUM <hints> (>=MASTER)")
505 def num_417(bot
, textline
):
506 bot
.msg(state
.db
['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
507 state
.nextquestion(False)
510 def specialQuestion(oldq
):
511 newq
= {'question': oldq['question'], 'answer': oldq['answer']}
512 qtype
= oldq
['question'].upper()
514 if qtype
== "!MONTH":
515 newq
['question'] = "What month is it currently (in UTC)?"
516 newq
['answer'] = time
.strftime("%B", time
.gmtime()).lower()
517 elif qtype
== "!MATH+":
518 randnum1
= random
.randrange(0, 11)
519 randnum2
= random
.randrange(0, 11)
520 newq
['question'] = "What is %d + %d?" % (randnum1
, randnum2
)
521 newq
['answer'] = spellout(randnum1
+randnum2
)
526 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
527 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
528 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"