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
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
= questionfile
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
56 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']])))
57 self
.getchan().msg("You have %s seconds." % (self
.db
['votetimer']))
58 self
.voteamounts
= dict([(x
, 0) for x
in self
.db
['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
59 self
.pointvote
= threading
.Timer(self
.db
['votetimer'], self
.endPointVote
)
60 self
.pointvote
.start()
67 if threading
is not None and threading
._Timer
is not None and isinstance(self
.steptimer
, threading
._Timer
):
68 self
.steptimer
.cancel()
69 if json
is not None and json
.dump
is not None:
70 json
.dump(self
.db
, open(self
.questionfile
, "w"))#, indent=4, separators=(',', ': '))
73 return self
.parent
.channel(self
.chan
)
75 return self
.getchan().bot
77 def nexthint(self
, hintnum
):
78 answer
= self
.hintanswer
80 if self
.hintstr
is None or self
.revealpossibilities
is None or self
.reveal
is None:
81 self
.hintstr
= list(re
.sub(r
'[a-zA-Z0-9]', '*', answer
))
82 self
.revealpossibilities
= range(''.join(self
.hintstr
).count('*'))
83 self
.reveal
= int(''.join(self
.hintstr
).count('*') * (7/24.0))
85 for i
in range(self
.reveal
):
86 revealcount
= random
.choice(self
.revealpossibilities
)
87 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
88 self
.revealpossibilities
.remove(revealcount
)
89 self
.hintstr
[revealloc
] = answer
[revealloc
]
90 self
.parent
.channel(self
.chan
).bot
.msg(self
.chan
, "\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
94 if hintnum
< self
.db
['hintnum']:
95 self
.steptimer
= threading
.Timer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
96 self
.steptimer
.start()
98 self
.steptimer
= threading
.Timer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
99 self
.steptimer
.start()
101 def doGameOver(self
):
102 def msg(line
): self
.getbot().msg(self
.getchan(), line
)
103 def person(num
): return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
104 def pts(num
): return self
.db
['users'][self
.db
['ranks'][num
]]['points']
107 msg("\00312THE GAME IS OVER!!!")
108 msg("THE WINNER IS: %s (%s)" % (person(0), pts(0)))
109 msg("2ND PLACE: %s (%s)" % (person(1), pts(1)))
110 msg("3RD PLACE: %s (%s)" % (person(2), pts(2)))
111 [msg("%dth place: %s (%s)" % (i
+1, person(i
), pts(i
))) for i
in range(3,10)]
112 except IndexError: pass
113 except Exception as e
: msg("DERP! %r" % (e
))
115 self
.db
['users'] = {}
116 self
.db
['ranks'] = []
121 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
122 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
123 self
.getbot().parent
.cfg
.get('trivia', 'con'),
124 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
125 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
126 except: pass #don't care if errors happen updating twitter.
128 self
.__init
__(self
.questionfile
, self
.parent
, True)
130 def endPointVote(self
):
131 self
.getchan().msg("Voting has ended!")
132 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
133 for i
in range(len(votelist
)-1):
135 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
136 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
138 self
.db
['target'] = votelist
[-1][0]
139 self
.pointvote
= None
141 self
.nextquestion() #start the game!
143 def nextquestion(self
, qskipped
=False, iteration
=0):
144 if self
.gameover
== True:
145 return self
.doGameOver()
147 self
.getchan().msg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
148 self
.missedquestions
+= 1
150 self
.missedquestions
= 0
152 if isinstance(self
.steptimer
, threading
._Timer
):
153 self
.steptimer
.cancel()
157 self
.revealpossibilities
= None
160 if self
.missedquestions
> self
.db
['maxmissedquestions']:
162 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game.")
164 if state
.nextq
is not None:
168 nextq
= random
.choice(self
.db
['questions'])
170 if nextq
['question'][0] == "!":
171 nextq
= specialQuestion(nextq
)
173 if iteration
< 10 and 'lastasked' in nextq
and nextq
['lastasked'] - time
.time() < 24*60*60:
174 return self
.nextquestion(iteration
=iteration
+1) #short-circuit to pick another question
175 nextq
['lastasked'] = time
.time()
177 nextq
['answer'] = nextq
['answer'].lower()
179 qtext
= "\00304,01Next up: "
180 qary
= nextq
['question'].split(None)
182 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(random
.randrange(0x61,0x7A)) #a-z
183 self
.getbot().msg(self
.chan
, qtext
)
187 if isinstance(self
.curq
['answer'], basestring
): self
.hintanswer
= self
.curq
['answer']
188 else: self
.hintanswer
= random
.choice(self
.curq
['answer'])
190 self
.steptimer
= threading
.Timer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
191 self
.steptimer
.start()
193 def checkanswer(self
, answer
):
194 if self
.curq
is None:
196 elif isinstance(self
.curq
['answer'], basestring
):
197 return answer
.lower() == self
.curq
['answer']
198 else: # assume it's a list or something.
199 return answer
.lower() in self
.curq
['answer']
201 def addpoint(self
, user_obj
, count
=1):
202 user_nick
= str(user_obj
)
203 user
= user_nick
.lower() # save this separately as we use both
204 if user
in self
.db
['users']:
205 self
.db
['users'][user
]['points'] += count
207 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
208 self
.db
['ranks'].append(user
)
210 self
.db
['ranks'].sort(key
=lambda nick
: state
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
211 for i
in range(0, len(self
.db
['ranks'])):
212 nick
= self
.db
['ranks'][i
]
213 self
.db
['users'][nick
]['rank'] = i
215 if self
.db
['users'][user
]['points'] >= state
.db
['target']:
218 return self
.db
['users'][user
]['points']
220 def points(self
, user
):
221 user
= str(user
).lower()
222 if user
in self
.db
['users']:
223 return self
.db
['users'][user
]['points']
227 def rank(self
, user
):
228 user
= str(user
).lower()
229 if user
in self
.db
['users']:
230 return self
.db
['users'][user
]['rank']+1
232 return len(self
.db
['users'])+1
234 def targetuser(self
, user
):
235 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
237 user
= str(user
).lower()
238 if user
in self
.db
['users']:
239 rank
= self
.db
['users'][user
]['rank']
241 return "you're in the lead!"
243 return self
.db
['ranks'][rank
-1]
245 return self
.db
['ranks'][-1]
246 def targetpoints(self
, user
):
247 if len(self
.db
['ranks']) == 0: return 0
249 user
= str(user
).lower()
250 if user
in self
.db
['users']:
251 rank
= self
.db
['users'][user
]['rank']
255 return self
.db
['users'][self
.db
['ranks'][rank
-1]]['points']
257 return self
.db
['users'][self
.db
['ranks'][-1]]['points']
259 state
= TriviaState("/home/jrunyon/erebus/modules/trivia.json") #TODO get path from config
261 @lib.hookchan(state
.db
['chan'])
262 def trivia_checkanswer(bot
, user
, chan
, *args
):
263 line
= ' '.join([str(arg
) for arg
in args
])
264 if state
.checkanswer(line
):
265 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
)))
266 if state
.hintsgiven
== 0:
267 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
270 @lib.hook('points', needchan
=False)
271 def cmd_points(bot
, user
, chan
, realtarget
, *args
):
272 if chan
== realtarget
: replyto
= chan
275 if len(args
) != 0: who
= args
[0]
278 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
280 @lib.hook('give', clevel
=lib
.OP
, needchan
=False)
282 def cmd_give(bot
, user
, chan
, realtarget
, *args
):
285 numpoints
= int(args
[1])
288 balance
= state
.addpoint(whoto
, numpoints
)
290 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
292 @lib.hook('setnext', clevel
=lib
.OP
, needchan
=False)
294 def cmd_setnext(bot
, user
, chan
, realtarget
, *args
):
295 line
= ' '.join([str(arg
) for arg
in args
])
296 linepieces
= line
.split('*')
297 if len(linepieces
) < 2:
298 bot
.msg(user
, "Error: need <question>*<answer>")
300 question
= linepieces
[0].strip()
301 answer
= linepieces
[1].strip()
302 state
.nextq
= {'question':question,'answer':answer}
303 bot
.msg(user
, "Done.")
305 @lib.hook('skip', clevel
=lib
.KNOWN
, needchan
=False)
306 def cmd_skip(bot
, user
, chan
, realtarget
, *args
):
307 state
.nextquestion(True)
309 @lib.hook('start', needchan
=False)
310 def cmd_start(bot
, user
, chan
, realtarget
, *args
):
311 if chan
== realtarget
: replyto
= chan
314 if state
.curq
is None and state
.pointvote
is None:
316 elif state
.pointvote
is not None:
317 bot
.msg(replyto
, "There's a vote in progress!")
319 bot
.msg(replyto
, "Game is already started!")
321 #FIXME @lib.hook('stop', clevel=lib.KNOWN, needchan=False)
322 @lib.hook('stop', needchan
=False) #FIXME
323 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
325 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
327 bot
.msg(user
, "Game isn't running.")
330 if state
.curq
is not None:
333 state
.steptimer
.cancel()
334 except Exception as e
:
335 print "!!! steptimer.cancel(): e"
340 @lib.hook('rank', needchan
=False)
341 def cmd_rank(bot
, user
, chan
, realtarget
, *args
):
342 if chan
== realtarget
: replyto
= chan
345 if len(args
) != 0: who
= args
[0]
348 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
)))
350 @lib.hook('top10', needchan
=False)
351 def cmd_top10(bot
, user
, chan
, realtarget
, *args
):
352 if len(state
.db
['ranks']) == 0:
353 return bot
.msg(state
.db
['chan'], "No one is ranked!")
356 for nick
in state
.db
['ranks'][0:10]:
357 user
= state
.db
['users'][nick
]
358 replylist
.append("%s (%s)" % (user
['realnick'], user
['points']))
359 bot
.msg(state
.db
['chan'], ', '.join(replylist
))
361 @lib.hook('settarget', clevel
=lib
.MASTER
, needchan
=False)
362 def cmd_settarget(bot
, user
, chan
, realtarget
, *args
):
364 state
.db
['target'] = int(args
[0])
365 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
367 if state
.votetimer
is not None:
368 state
.votetimer
.cancel()
369 state
.votetimer
= None
370 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
372 bot
.msg(user
, "Failed to set target.")
374 @lib.hook('vote', needchan
=False)
375 def cmd_vote(bot
, user
, chan
, realtarget
, *args
):
376 if state
.votetimer
is not None:
377 if int(args
[0]) in state
.voteamounts
:
378 state
.voteamounts
[int(args
[0])] += 1
379 bot
.msg(user
, "Your vote has been recorded.")
381 bot
.msg(user
, "Sorry - that's not an option!")
383 bot
.msg(user
, "There's no vote in progress.")
385 @lib.hook('maxmissed', clevel
=lib
.MASTER
, needchan
=False)
386 def cmd_maxmissed(bot
, user
, chan
, realtarget
, *args
):
388 state
.db
['maxmissedquestions'] = int(args
[0])
389 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
391 bot
.msg(user
, "Failed to set maxmissed.")
393 @lib.hook('hinttimer', clevel
=lib
.MASTER
, needchan
=False)
394 def cmd_hinttimer(bot
, user
, chan
, realtarget
, *args
):
396 state
.db
['hinttimer'] = float(args
[0])
397 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
399 bot
.msg(user
, "Failed to set hint timer.")
401 @lib.hook('hintnum', clevel
=lib
.MASTER
, needchan
=False)
402 def cmd_hintnum(bot
, user
, chan
, realtarget
, *args
):
404 state
.db
['hintnum'] = int(args
[0])
405 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
407 bot
.msg(user
, "Failed to set hintnum.")
409 @lib.hook('findq', clevel
=lib
.KNOWN
, needchan
=False)
410 def cmd_findquestion(bot
, user
, chan
, realtarget
, *args
):
411 matches
= [str(i
) for i
in range(len(state
.db
['questions'])) if state
.db
['questions'][i
]['question'] == ' '.join(args
)] #FIXME: looser equality check
413 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
414 elif len(matches
) == 1:
415 bot
.msg(user
, "One match: %s" % (matches
[0]))
417 bot
.msg(user
, "No match.")
419 @lib.hook('delq', clevel
=lib
.OP
, needchan
=False)
420 @lib.hook('deleteq', clevel
=lib
.OP
, needchan
=False)
421 def cmd_deletequestion(bot
, user
, chan
, realtarget
, *args
):
423 backup
= state
.db
['questions'][int(args
[0])]
424 del state
.db
['questions'][int(args
[0])]
425 bot
.msg(user
, "Deleted %s*%s" % (backup
['question'], backup
['answer']))
427 bot
.msg(user
, "Couldn't delete that question.")
429 @lib.hook('addq', clevel
=lib
.OP
, needchan
=False)
430 def cmd_addquestion(bot
, user
, chan
, realtarget
, *args
):
431 line
= ' '.join([str(arg
) for arg
in args
])
432 linepieces
= line
.split('*')
433 if len(linepieces
) < 2:
434 bot
.msg(user
, "Error: need <question>*<answer>")
436 question
= linepieces
[0].strip()
437 answer
= linepieces
[1].strip()
438 state
.db
['questions'].append({'question':question,'answer':answer}
)
439 bot
.msg(user
, "Done. Question is #%s" % (len(state
.db
['questions'])-1))
442 @lib.hook('triviahelp', needchan
=False)
443 def cmd_triviahelp(bot
, user
, chan
, realtarget
, *args
):
444 bot
.msg(user
, "START")
445 bot
.msg(user
, "TOP10")
446 bot
.msg(user
, "POINTS [<user>]")
447 bot
.msg(user
, "RANK [<user>]")
448 if bot
.parent
.channel(state
.db
['chan']).levelof(user
.auth
) >= lib
.KNOWN
:
449 bot
.msg(user
, "SKIP (>=KNOWN )")
450 bot
.msg(user
, "STOP (>=KNOWN )")
451 bot
.msg(user
, "FINDQ <question> (>=KNOWN )")
452 if bot
.parent
.channel(state
.db
['chan']).levelof(user
.auth
) >= lib
.OP
:
453 bot
.msg(user
, "GIVE <user> [<points>] (>=OP )")
454 bot
.msg(user
, "SETNEXT <q>*<a> (>=OP )")
455 bot
.msg(user
, "ADDQ <q>*<a> (>=OP )")
456 bot
.msg(user
, "DELETEQ <q>*<a> (>=OP ) [aka DELQ]")
457 if bot
.parent
.channel(state
.db
['chan']).levelof(user
.auth
) >= lib
.MASTER
:
458 bot
.msg(user
, "SETTARGET <points> (>=MASTER)")
459 bot
.msg(user
, "MAXMISSED <questions> (>=MASTER)")
460 bot
.msg(user
, "HINTTIMER <float seconds> (>=MASTER)")
461 bot
.msg(user
, "HINTNUM <hints> (>=MASTER)")
464 def num_417(bot
, textline
):
465 bot
.msg(state
.db
['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
466 state
.nextquestion(False)
469 def specialQuestion(oldq
):
470 newq
= {'question': oldq['question'], 'answer': oldq['answer']}
471 qtype
= oldq
['question'].upper()
473 if qtype
== "!MONTH":
474 newq
['question'] = "What month is it currently (in UTC)?"
475 newq
['answer'] = time
.strftime("%B").lower()
476 elif qtype
== "!MATH+":
477 randnum1
= random
.randrange(0, 11)
478 randnum2
= random
.randrange(0, 11)
479 newq
['question'] = "What is %d + %d?" % (randnum1
, randnum2
)
480 newq
['answer'] = spellout(randnum1
+randnum2
)
485 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
486 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
487 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"