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
):
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
):
25 return lib
.modstop(*args
, **kwargs
)
28 import json
, random
, threading
, re
, time
, datetime
32 except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
34 def findnth(haystack
, needle
, n
): #http://stackoverflow.com/a/1884151
35 parts
= haystack
.split(needle
, n
+1)
38 return len(haystack
)-len(parts
[-1])-len(needle
)
40 class TriviaState(object):
41 def __init__(self
, parent
=None, pointvote
=False):
42 if parent
is not None:
43 self
.gotParent(parent
, pointvote
)
45 def gotParent(self
, parent
, pointvote
=False):
47 self
.questionfile
= self
.parent
.cfg
.get('trivia', 'jsonpath')
48 self
.db
= json
.load(open(self
.questionfile
, "r"))
49 self
.chan
= self
.db
['chan']
52 self
.nextquestiontimer
= None
55 self
.hintanswer
= None
57 self
.revealpossibilities
= None
59 self
.missedquestions
= 0
61 if 'starttime' not in self
.db
or self
.db
['starttime'] is None:
62 self
.db
['starttime'] = time
.time()
65 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']])))
66 self
.getchan().msg("You have %s seconds." % (self
.db
['votetimer']))
67 self
.voteamounts
= dict([(x
, 0) for x
in self
.db
['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
68 self
.pointvote
= threading
.Timer(self
.db
['votetimer'], self
.endPointVote
)
69 self
.pointvote
.start()
76 if threading
is not None and threading
._Timer
is not None:
77 if isinstance(self
.steptimer
, threading
._Timer
):
78 self
.steptimer
.cancel()
79 if isinstance(self
.nextquestiontimer
, threading
._Timer
):
80 self
.nextquestiontimer
.cancel()
81 self
.nextquestiontimer
= None
82 if json
is not None and json
.dump
is not None:
83 json
.dump(self
.db
, open(self
.questionfile
, "w"))#, indent=4, separators=(',', ': '))
86 return self
.parent
.channel(self
.chan
)
88 return self
.getchan().bot
90 def nexthint(self
, hintnum
):
91 answer
= self
.hintanswer
93 if self
.hintstr
is None or self
.revealpossibilities
is None or self
.reveal
is None:
94 self
.hintstr
= list(re
.sub(r
'[a-zA-Z0-9]', '*', answer
))
95 self
.revealpossibilities
= range(''.join(self
.hintstr
).count('*'))
96 self
.reveal
= int(''.join(self
.hintstr
).count('*') * (7/24.0))
98 for i
in range(self
.reveal
):
99 revealcount
= random
.choice(self
.revealpossibilities
)
100 revealloc
= findnth(''.join(self
.hintstr
), '*', revealcount
)
101 self
.revealpossibilities
.remove(revealcount
)
102 self
.hintstr
[revealloc
] = answer
[revealloc
]
103 self
.parent
.channel(self
.chan
).bot
.msg(self
.chan
, "\00304,01Here's a hint: %s" % (''.join(self
.hintstr
)))
107 if hintnum
< self
.db
['hintnum']:
108 self
.steptimer
= threading
.Timer(self
.db
['hinttimer'], self
.nexthint
, args
=[hintnum
+1])
109 self
.steptimer
.start()
111 self
.steptimer
= threading
.Timer(self
.db
['hinttimer'], self
.nextquestion
, args
=[True])
112 self
.steptimer
.start()
114 def doGameOver(self
):
115 msg
= self
.getchan().msg
116 def person(num
): return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
117 def pts(num
): return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
120 msg("\00312THE GAME IS OVER!!!")
121 msg("THE WINNER IS: %s (%s)" % (person(0), pts(0)))
122 msg("2ND PLACE: %s (%s)" % (person(1), pts(1)))
123 msg("3RD PLACE: %s (%s)" % (person(2), pts(2)))
124 [msg("%dth place: %s (%s)" % (i
+1, person(i
), pts(i
))) for i
in range(3,10)]
125 except IndexError: pass
126 except Exception as e
: msg("DERP! %r" % (e
))
128 if self
.db
['hofpath'] is not None and self
.db
['hofpath'] != '':
131 self
.db
['users'] = {}
132 self
.db
['ranks'] = []
137 t
= twitter
.Twitter(auth
=twitter
.OAuth(self
.getbot().parent
.cfg
.get('trivia', 'token'),
138 self
.getbot().parent
.cfg
.get('trivia', 'token_sec'),
139 self
.getbot().parent
.cfg
.get('trivia', 'con'),
140 self
.getbot().parent
.cfg
.get('trivia', 'con_sec')))
141 t
.statuses
.update(status
="Round is over! The winner was %s" % (winner
))
142 except: pass #don't care if errors happen updating twitter.
144 self
.__init
__(self
.parent
, True)
148 try: return self
.db
['users'][self
.db
['ranks'][num
]]['realnick']
149 except: return "none"
151 try: return str(self
.db
['users'][self
.db
['ranks'][num
]]['points'])
155 f
= open(self
.db
['hofpath'], 'rb+')
156 for i
in range(self
.db
['hoflines']): #skip this many lines
161 f
.write((self
.db
['hofformat']+"\n") % {
162 'date': time
.strftime("%F", time
.gmtime()),
163 'duration': str(datetime
.timedelta(seconds
=time
.time()-self
.db
['starttime'])),
164 'targetscore': self
.db
['target'],
165 'firstperson': person(0),
166 'firstscore': pts(0),
167 'secondperson': person(1),
168 'secondscore': pts(1),
169 'thirdperson': person(2),
170 'thirdscore': pts(2),
174 except Exception as e
:
180 def endPointVote(self
):
181 self
.getchan().msg("Voting has ended!")
182 votelist
= sorted(self
.voteamounts
.items(), key
=lambda item
: item
[1]) #sort into list of tuples: [(option, number_of_votes), ...]
183 for i
in range(len(votelist
)-1):
185 self
.getchan().msg("%s place: %s (%s votes)" % (len(votelist
)-i
, item
[0], item
[1]))
186 self
.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist
[-1][0], votelist
[-1][1]))
188 self
.db
['target'] = votelist
[-1][0]
189 self
.pointvote
= None
191 self
.nextquestion() #start the game!
193 def nextquestion(self
, qskipped
=False, iteration
=0, skipwait
=False):
194 if self
.gameover
== True:
195 return self
.doGameOver()
197 self
.getchan().msg("\00304Fail! The correct answer was: %s" % (self
.hintanswer
))
198 self
.missedquestions
+= 1
200 self
.missedquestions
= 0
202 if isinstance(self
.steptimer
, threading
._Timer
):
203 self
.steptimer
.cancel()
204 if isinstance(self
.nextquestiontimer
, threading
._Timer
):
205 self
.nextquestiontimer
.cancel()
206 self
.nextquestiontimer
= None
210 self
.revealpossibilities
= None
213 if self
.missedquestions
> self
.db
['maxmissedquestions']:
215 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game.")
218 self
._nextquestion
(qskipped
, iteration
)
221 self
.nextquestiontimer
= threading
.Timer(self
.db
['questionpause'], self
._nextquestion
, args
=[qskipped
, iteration
])
222 self
.nextquestiontimer
.start()
224 def _nextquestion(self
, qskipped
, iteration
):
226 if self
.nextq
is not None:
230 nextq
= random
.choice(self
.db
['questions'])
232 if nextq
[0][0] == "!":
233 nextq
= specialQuestion(nextq
)
235 if len(nextq
) > 2 and nextq
[2] - time
.time() < 7*24*60*60 and iteration
< 10:
236 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
238 nextq
[2] = time
.time()
240 nextq
.append(time
.time())
242 nextq
[1] = nextq
[1].lower()
244 qtext
= "\00304,01Next up: "
245 qary
= nextq
[0].split(None)
247 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(random
.randrange(0x61,0x7A)) #a-z
248 self
.getbot().msg(self
.chan
, qtext
)
252 if isinstance(self
.curq
[1], basestring
): self
.hintanswer
= self
.curq
[1]
253 else: self
.hintanswer
= random
.choice(self
.curq
[1])
255 self
.steptimer
= threading
.Timer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
256 self
.steptimer
.start()
258 def checkanswer(self
, answer
):
259 if self
.curq
is None:
261 elif isinstance(self
.curq
[1], basestring
):
262 return answer
.lower() == self
.curq
[1]
263 else: # assume it's a list or something.
264 return answer
.lower() in self
.curq
[1]
266 def addpoint(self
, user_obj
, count
=1):
267 user_nick
= str(user_obj
)
268 user
= user_nick
.lower() # save this separately as we use both
269 if user
in self
.db
['users']:
270 self
.db
['users'][user
]['points'] += count
272 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
273 self
.db
['ranks'].append(user
)
275 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
276 for i
in range(0, len(self
.db
['ranks'])):
277 nick
= self
.db
['ranks'][i
]
278 self
.db
['users'][nick
]['rank'] = i
280 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
283 return self
.db
['users'][user
]['points']
285 def points(self
, user
):
286 user
= str(user
).lower()
287 if user
in self
.db
['users']:
288 return self
.db
['users'][user
]['points']
292 def rank(self
, user
):
293 user
= str(user
).lower()
294 if user
in self
.db
['users']:
295 return self
.db
['users'][user
]['rank']+1
297 return len(self
.db
['users'])+1
299 def targetuser(self
, user
):
300 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
302 user
= str(user
).lower()
303 if user
in self
.db
['users']:
304 rank
= self
.db
['users'][user
]['rank']
306 return "you're in the lead!"
308 return self
.db
['ranks'][rank
-1]
310 return self
.db
['ranks'][-1]
311 def targetpoints(self
, user
):
312 if len(self
.db
['ranks']) == 0: return 0
314 user
= str(user
).lower()
315 if user
in self
.db
['users']:
316 rank
= self
.db
['users'][user
]['rank']
320 return self
.db
['users'][self
.db
['ranks'][rank
-1]]['points']
322 return self
.db
['users'][self
.db
['ranks'][-1]]['points']
324 state
= TriviaState()
326 # we have to hook this in modstart, since we don't know the channel until then.
327 def trivia_checkanswer(bot
, user
, chan
, *args
):
328 line
= ' '.join([str(arg
) for arg
in args
])
329 if state
.checkanswer(line
):
330 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
)))
331 if state
.hintsgiven
== 0:
332 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
335 @lib.hook('points', needchan
=False)
336 def cmd_points(bot
, user
, chan
, realtarget
, *args
):
337 if chan
== realtarget
: replyto
= chan
340 if len(args
) != 0: who
= args
[0]
343 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
345 @lib.hook('give', glevel
=lib
.STAFF
, needchan
=False)
347 def cmd_give(bot
, user
, chan
, realtarget
, *args
):
350 numpoints
= int(args
[1])
353 balance
= state
.addpoint(whoto
, numpoints
)
355 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
357 @lib.hook('setnextid', glevel
=1, needchan
=False)
358 def cmd_setnextid(bot
, user
, chan
, realtarget
, *args
):
361 state
.nextq
= state
.db
['questions'][qid
]
362 bot
.msg(user
, "Done. Next question is: %s" % (state
.nextq
[0]))
363 except Exception as e
:
364 bot
.msg(user
, "Error: %s" % (e
))
366 @lib.hook('setnext', glevel
=lib
.STAFF
, needchan
=False)
368 def cmd_setnext(bot
, user
, chan
, realtarget
, *args
):
369 line
= ' '.join([str(arg
) for arg
in args
])
370 linepieces
= line
.split('*')
371 if len(linepieces
) < 2:
372 bot
.msg(user
, "Error: need <question>*<answer>")
374 question
= linepieces
[0].strip()
375 answer
= linepieces
[1].strip()
376 state
.nextq
= [question
, answer
]
377 bot
.msg(user
, "Done.")
379 @lib.hook('skip', glevel
=1, needchan
=False)
380 def cmd_skip(bot
, user
, chan
, realtarget
, *args
):
381 state
.nextquestion(qskipped
=True, skipwait
=True)
383 @lib.hook('start', needchan
=False)
384 def cmd_start(bot
, user
, chan
, realtarget
, *args
):
385 if chan
== realtarget
: replyto
= chan
388 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
389 state
.nextquestion(skipwait
=True)
390 elif state
.pointvote
is not None:
391 bot
.msg(replyto
, "There's a vote in progress!")
393 bot
.msg(replyto
, "Game is already started!")
395 @lib.hook('stop', glevel
=1, needchan
=False)
396 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
398 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
400 bot
.msg(user
, "Game isn't running.")
404 if state
.curq
is not None:
407 state
.steptimer
.cancel()
408 except Exception as e
:
409 print "!!! steptimer.cancel(): %s %r" % (e
,e
)
411 state
.nextquestiontimer
.cancel()
412 state
.nextquestiontimer
= None
413 except Exception as e
:
414 print "!!! nextquestiontimer.cancel(): %s %r" % (e
,e
)
421 @lib.hook('rank', needchan
=False)
422 def cmd_rank(bot
, user
, chan
, realtarget
, *args
):
423 if chan
== realtarget
: replyto
= chan
426 if len(args
) != 0: who
= args
[0]
429 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
)))
431 @lib.hook('top10', needchan
=False)
432 def cmd_top10(bot
, user
, chan
, realtarget
, *args
):
433 if len(state
.db
['ranks']) == 0:
434 return bot
.msg(state
.db
['chan'], "No one is ranked!")
437 for nick
in state
.db
['ranks'][0:10]:
438 user
= state
.db
['users'][nick
]
439 replylist
.append("%s (%s)" % (user
['realnick'], user
['points']))
440 bot
.msg(state
.db
['chan'], ', '.join(replylist
))
442 @lib.hook('settarget', glevel
=lib
.ADMIN
, needchan
=False)
443 def cmd_settarget(bot
, user
, chan
, realtarget
, *args
):
445 state
.db
['target'] = int(args
[0])
446 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
448 if state
.pointvote
is not None:
449 state
.pointvote
.cancel()
450 state
.pointvote
= None
451 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
452 except Exception as e
:
454 bot
.msg(user
, "Failed to set target.")
456 @lib.hook('vote', needchan
=False)
457 def cmd_vote(bot
, user
, chan
, realtarget
, *args
):
458 if state
.pointvote
is not None:
459 if int(args
[0]) in state
.voteamounts
:
460 state
.voteamounts
[int(args
[0])] += 1
461 bot
.msg(user
, "Your vote has been recorded.")
463 bot
.msg(user
, "Sorry - that's not an option!")
465 bot
.msg(user
, "There's no vote in progress.")
467 @lib.hook('maxmissed', glevel
=lib
.ADMIN
, needchan
=False)
468 def cmd_maxmissed(bot
, user
, chan
, realtarget
, *args
):
470 state
.db
['maxmissedquestions'] = int(args
[0])
471 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
473 bot
.msg(user
, "Failed to set maxmissed.")
475 @lib.hook('hinttimer', glevel
=lib
.ADMIN
, needchan
=False)
476 def cmd_hinttimer(bot
, user
, chan
, realtarget
, *args
):
478 state
.db
['hinttimer'] = float(args
[0])
479 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
481 bot
.msg(user
, "Failed to set hint timer.")
483 @lib.hook('hintnum', glevel
=lib
.ADMIN
, needchan
=False)
484 def cmd_hintnum(bot
, user
, chan
, realtarget
, *args
):
486 state
.db
['hintnum'] = int(args
[0])
487 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
489 bot
.msg(user
, "Failed to set hintnum.")
491 @lib.hook('questionpause', glevel
=lib
.ADMIN
, needchan
=False)
492 def cmd_questionpause(bot
, user
, chan
, realtarget
, *args
):
494 state
.db
['questionpause'] = float(args
[0])
495 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
497 bot
.msg(user
, "Failed to set questionpause.")
499 @lib.hook('findq', glevel
=1, needchan
=False)
500 def cmd_findquestion(bot
, user
, chan
, realtarget
, *args
):
501 matches
= [str(i
) for i
in range(len(state
.db
['questions'])) if state
.db
['questions'][i
][0] == ' '.join(args
)] #TODO looser equality check
503 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
504 elif len(matches
) == 1:
505 bot
.msg(user
, "One match: %s" % (matches
[0]))
507 bot
.msg(user
, "No match.")
509 @lib.hook('delq', glevel
=lib
.STAFF
, needchan
=False)
510 @lib.hook('deleteq', glevel
=lib
.STAFF
, needchan
=False)
511 def cmd_deletequestion(bot
, user
, chan
, realtarget
, *args
):
513 backup
= state
.db
['questions'][int(args
[0])]
514 del state
.db
['questions'][int(args
[0])]
515 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]))
517 bot
.msg(user
, "Couldn't delete that question.")
519 @lib.hook('addq', glevel
=lib
.STAFF
, needchan
=False)
520 def cmd_addquestion(bot
, user
, chan
, realtarget
, *args
):
521 line
= ' '.join([str(arg
) for arg
in args
])
522 linepieces
= line
.split('*')
523 if len(linepieces
) < 2:
524 bot
.msg(user
, "Error: need <question>*<answer>")
526 question
= linepieces
[0].strip()
527 answer
= linepieces
[1].strip()
528 state
.db
['questions'].append([question
, answer
])
529 bot
.msg(user
, "Done. Question is #%s" % (len(state
.db
['questions'])-1))
532 @lib.hook('triviahelp', needchan
=False)
533 def cmd_triviahelp(bot
, user
, chan
, realtarget
, *args
):
535 bot
.msg(user
, "START")
536 bot
.msg(user
, "TOP10")
537 bot
.msg(user
, "POINTS [<user>]")
538 bot
.msg(user
, "RANK [<user>]")
540 bot
.msg(user
, "START (ANYONE )")
541 bot
.msg(user
, "TOP10 (ANYONE )")
542 bot
.msg(user
, "POINTS [<user>] (ANYONE )")
543 bot
.msg(user
, "RANK [<user>] (ANYONE )")
545 bot
.msg(user
, "SKIP (>=KNOWN)")
546 bot
.msg(user
, "STOP (>=KNOWN)")
547 bot
.msg(user
, "FINDQ <question> (>=KNOWN)")
548 if user
.glevel
>= lib
.STAFF
:
549 bot
.msg(user
, "GIVE <user> [<points>] (>=STAFF)")
550 bot
.msg(user
, "SETNEXT <q>*<a> (>=STAFF)")
551 bot
.msg(user
, "ADDQ <q>*<a> (>=STAFF)")
552 bot
.msg(user
, "DELETEQ <q>*<a> (>=STAFF) [aka DELQ]")
553 if user
.glevel
>= lib
.ADMIN
:
554 bot
.msg(user
, "SETTARGET <points> (>=ADMIN)")
555 bot
.msg(user
, "MAXMISSED <questions> (>=ADMIN)")
556 bot
.msg(user
, "HINTTIMER <float seconds> (>=ADMIN)")
557 bot
.msg(user
, "HINTNUM <hints> (>=ADMIN)")
558 bot
.msg(user
, "QUESTIONPAUSE <float seconds> (>=ADMIN)")
561 def num_417(bot
, textline
):
562 bot
.msg(state
.db
['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
563 state
.nextquestion(qskipped
=False, skipwait
=True)
566 def specialQuestion(oldq
):
567 newq
= [oldq
[0], oldq
[1]]
568 qtype
= oldq
[0].upper()
570 if qtype
== "!MONTH":
571 newq
[0] = "What month is it currently (in UTC)?"
572 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
573 elif qtype
== "!MATH+":
574 randnum1
= random
.randrange(0, 11)
575 randnum2
= random
.randrange(0, 11)
576 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
577 newq
[1] = spellout(randnum1
+randnum2
)
582 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
583 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
584 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"