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 def nextquestion(self
, qskipped
=False, iteration
=0):
142 if self
.gameover
== True:
143 return self
.doGameOver()
145 self
.getchan().msg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
146 self
.missedquestions
+= 1
148 self
.missedquestions
= 0
150 if isinstance(self
.steptimer
, threading
._Timer
):
151 self
.steptimer
.cancel()
155 self
.revealpossibilities
= None
158 if self
.missedquestions
> self
.db
['maxmissedquestions']:
160 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game.")
162 if state
.nextq
is not None:
166 nextq
= random
.choice(self
.db
['questions'])
168 if nextq
['question'][0] == "!":
169 nextq
= specialQuestion(nextq
)
171 if iteration
< 10 and 'lastasked' in nextq
and nextq
['lastasked'] - time
.time() < 24*60*60:
172 return self
.nextquestion(iteration
=iteration
+1) #short-circuit to pick another question
173 nextq
['lastasked'] = time
.time()
175 nextq
['answer'] = nextq
['answer'].lower()
177 qtext
= "\00304,01Next up: "
178 qary
= nextq
['question'].split(None)
180 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(random
.randrange(0x61,0x7A)) #a-z
181 self
.getbot().msg(self
.chan
, qtext
)
185 if isinstance(self
.curq
['answer'], basestring
): self
.hintanswer
= self
.curq
['answer']
186 else: self
.hintanswer
= random
.choice(self
.curq
['answer'])
188 self
.steptimer
= threading
.Timer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
189 self
.steptimer
.start()
191 def checkanswer(self
, answer
):
192 if self
.curq
is None:
194 elif isinstance(self
.curq
['answer'], basestring
):
195 return answer
.lower() == self
.curq
['answer']
196 else: # assume it's a list or something.
197 return answer
.lower() in self
.curq
['answer']
199 def addpoint(self
, user_obj
, count
=1):
200 user_nick
= str(user_obj
)
201 user
= user_nick
.lower() # save this separately as we use both
202 if user
in self
.db
['users']:
203 self
.db
['users'][user
]['points'] += count
205 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
206 self
.db
['ranks'].append(user
)
208 self
.db
['ranks'].sort(key
=lambda nick
: state
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
209 for i
in range(0, len(self
.db
['ranks'])):
210 nick
= self
.db
['ranks'][i
]
211 self
.db
['users'][nick
]['rank'] = i
213 if self
.db
['users'][user
]['points'] >= state
.db
['target']:
216 return self
.db
['users'][user
]['points']
218 def points(self
, user
):
219 user
= str(user
).lower()
220 if user
in self
.db
['users']:
221 return self
.db
['users'][user
]['points']
225 def rank(self
, user
):
226 user
= str(user
).lower()
227 if user
in self
.db
['users']:
228 return self
.db
['users'][user
]['rank']+1
230 return len(self
.db
['users'])+1
232 def targetuser(self
, user
):
233 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
235 user
= str(user
).lower()
236 if user
in self
.db
['users']:
237 rank
= self
.db
['users'][user
]['rank']
239 return "you're in the lead!"
241 return self
.db
['ranks'][rank
-1]
243 return self
.db
['ranks'][-1]
244 def targetpoints(self
, user
):
245 if len(self
.db
['ranks']) == 0: return 0
247 user
= str(user
).lower()
248 if user
in self
.db
['users']:
249 rank
= self
.db
['users'][user
]['rank']
253 return self
.db
['users'][self
.db
['ranks'][rank
-1]]['points']
255 return self
.db
['users'][self
.db
['ranks'][-1]]['points']
257 state
= TriviaState("/home/jrunyon/erebus/modules/trivia.json") #TODO get path from config
259 @lib.hookchan(state
.db
['chan'])
260 def trivia_checkanswer(bot
, user
, chan
, *args
):
261 line
= ' '.join([str(arg
) for arg
in args
])
262 if state
.checkanswer(line
):
263 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
)))
264 if state
.hintsgiven
== 0:
265 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
268 @lib.hook('points', needchan
=False)
269 def cmd_points(bot
, user
, chan
, realtarget
, *args
):
270 if chan
== realtarget
: replyto
= chan
273 if len(args
) != 0: who
= args
[0]
276 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
278 @lib.hook('give', clevel
=lib
.OP
, needchan
=False)
280 def cmd_give(bot
, user
, chan
, realtarget
, *args
):
283 numpoints
= int(args
[1])
286 balance
= state
.addpoint(whoto
, numpoints
)
288 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
290 @lib.hook('setnext', clevel
=lib
.OP
, needchan
=False)
292 def cmd_setnext(bot
, user
, chan
, realtarget
, *args
):
293 line
= ' '.join([str(arg
) for arg
in args
])
294 linepieces
= line
.split('*')
295 if len(linepieces
) < 2:
296 bot
.msg(user
, "Error: need <question>*<answer>")
298 question
= linepieces
[0].strip()
299 answer
= linepieces
[1].strip()
300 state
.nextq
= {'question':question,'answer':answer}
301 bot
.msg(user
, "Done.")
303 @lib.hook('skip', clevel
=lib
.KNOWN
, needchan
=False)
304 def cmd_skip(bot
, user
, chan
, realtarget
, *args
):
305 state
.nextquestion(True)
307 @lib.hook('start', needchan
=False)
308 def cmd_start(bot
, user
, chan
, realtarget
, *args
):
309 if chan
== realtarget
: replyto
= chan
312 if state
.curq
is None and state
.pointvote
is None:
314 elif state
.pointvote
is not None:
315 bot
.msg(replyto
, "There's a vote in progress!")
317 bot
.msg(replyto
, "Game is already started!")
319 #FIXME @lib.hook('stop', clevel=lib.KNOWN, needchan=False)
320 @lib.hook('stop', needchan
=False) #FIXME
321 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
323 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
325 bot
.msg(user
, "Game isn't running.")
328 if state
.curq
is not None:
331 state
.steptimer
.cancel()
332 except Exception as e
:
333 print "!!! steptimer.cancel(): e"
338 @lib.hook('rank', needchan
=False)
339 def cmd_rank(bot
, user
, chan
, realtarget
, *args
):
340 if chan
== realtarget
: replyto
= chan
343 if len(args
) != 0: who
= args
[0]
346 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
)))
348 @lib.hook('top10', needchan
=False)
349 def cmd_top10(bot
, user
, chan
, realtarget
, *args
):
350 if len(state
.db
['ranks']) == 0:
351 return bot
.msg(state
.db
['chan'], "No one is ranked!")
354 for nick
in state
.db
['ranks'][0:10]:
355 user
= state
.db
['users'][nick
]
356 replylist
.append("%s (%s)" % (user
['realnick'], user
['points']))
357 bot
.msg(state
.db
['chan'], ', '.join(replylist
))
359 @lib.hook('settarget', clevel
=lib
.MASTER
, needchan
=False)
360 def cmd_settarget(bot
, user
, chan
, realtarget
, *args
):
362 state
.db
['target'] = int(args
[0])
363 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
365 bot
.msg(user
, "Failed to set target.")
367 @lib.hook('maxmissed', clevel
=lib
.MASTER
, needchan
=False)
368 def cmd_maxmissed(bot
, user
, chan
, realtarget
, *args
):
370 state
.db
['maxmissedquestions'] = int(args
[0])
371 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
373 bot
.msg(user
, "Failed to set maxmissed.")
375 @lib.hook('hinttimer', clevel
=lib
.MASTER
, needchan
=False)
376 def cmd_hinttimer(bot
, user
, chan
, realtarget
, *args
):
378 state
.db
['hinttimer'] = float(args
[0])
379 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
381 bot
.msg(user
, "Failed to set hint timer.")
383 @lib.hook('hintnum', clevel
=lib
.MASTER
, needchan
=False)
384 def cmd_hintnum(bot
, user
, chan
, realtarget
, *args
):
386 state
.db
['hintnum'] = int(args
[0])
387 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
389 bot
.msg(user
, "Failed to set hintnum.")
391 @lib.hook('findq', clevel
=lib
.KNOWN
, needchan
=False)
392 def cmd_findquestion(bot
, user
, chan
, realtarget
, *args
):
393 matches
= [str(i
) for i
in range(len(state
.db
['questions'])) if state
.db
['questions'][i
]['question'] == ' '.join(args
)] #FIXME: looser equality check
395 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
396 elif len(matches
) == 1:
397 bot
.msg(user
, "One match: %s" % (matches
[0]))
399 bot
.msg(user
, "No match.")
401 @lib.hook('delq', clevel
=lib
.OP
, needchan
=False)
402 @lib.hook('deleteq', clevel
=lib
.OP
, needchan
=False)
403 def cmd_deletequestion(bot
, user
, chan
, realtarget
, *args
):
405 backup
= state
.db
['questions'][int(args
[0])]
406 del state
.db
['questions'][int(args
[0])]
407 bot
.msg(user
, "Deleted %s*%s" % (backup
['question'], backup
['answer']))
409 bot
.msg(user
, "Couldn't delete that question.")
411 @lib.hook('addq', clevel
=lib
.OP
, needchan
=False)
412 def cmd_addquestion(bot
, user
, chan
, realtarget
, *args
):
413 line
= ' '.join([str(arg
) for arg
in args
])
414 linepieces
= line
.split('*')
415 if len(linepieces
) < 2:
416 bot
.msg(user
, "Error: need <question>*<answer>")
418 question
= linepieces
[0].strip()
419 answer
= linepieces
[1].strip()
420 state
.db
['questions'].append({'question':question,'answer':answer}
)
421 bot
.msg(user
, "Done. Question is #%s" % (len(state
.db
['questions'])-1))
424 @lib.hook('triviahelp', needchan
=False)
425 def cmd_triviahelp(bot
, user
, chan
, realtarget
, *args
):
426 bot
.msg(user
, "START")
427 bot
.msg(user
, "TOP10")
428 bot
.msg(user
, "POINTS [<user>]")
429 bot
.msg(user
, "RANK [<user>]")
430 if bot
.parent
.channel(state
.db
['chan']).levelof(user
.auth
) >= lib
.KNOWN
:
431 bot
.msg(user
, "SKIP (>=KNOWN )")
432 bot
.msg(user
, "STOP (>=KNOWN )")
433 bot
.msg(user
, "FINDQ <question> (>=KNOWN )")
434 if bot
.parent
.channel(state
.db
['chan']).levelof(user
.auth
) >= lib
.OP
:
435 bot
.msg(user
, "GIVE <user> [<points>] (>=OP )")
436 bot
.msg(user
, "SETNEXT <q>*<a> (>=OP )")
437 bot
.msg(user
, "ADDQ <q>*<a> (>=OP )")
438 bot
.msg(user
, "DELETEQ <q>*<a> (>=OP ) [aka DELQ]")
439 if bot
.parent
.channel(state
.db
['chan']).levelof(user
.auth
) >= lib
.MASTER
:
440 bot
.msg(user
, "SETTARGET <points> (>=MASTER)")
441 bot
.msg(user
, "MAXMISSED <questions> (>=MASTER)")
442 bot
.msg(user
, "HINTTIMER <float seconds> (>=MASTER)")
443 bot
.msg(user
, "HINTNUM <hints> (>=MASTER)")
446 def num_417(bot
, textline
):
447 bot
.msg(state
.db
['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
448 state
.nextquestion(False)
451 def specialQuestion(oldq
):
452 newq
= {'question': oldq['question'], 'answer': oldq['answer']}
453 qtype
= oldq
['question'].upper()
455 if qtype
== "!MONTH":
456 newq
['question'] = "What month is it currently (in UTC)?"
457 newq
['answer'] = time
.strftime("%B").lower()
458 elif qtype
== "!MATH+":
459 randnum1
= random
.randrange(0, 11)
460 randnum2
= random
.randrange(0, 11)
461 newq
['question'] = "What is %d + %d?" % (randnum1
, randnum2
)
462 newq
['answer'] = spellout(randnum1
+randnum2
)
467 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
468 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
469 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"