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
201 if 'topicformat' in self
.db
and self
.db
['topicformat'] is not None:
202 self
.getbot().conn
.send("TOPIC %s" % (self
.db
['chan']))
204 if isinstance(self
.steptimer
, threading
._Timer
):
205 self
.steptimer
.cancel()
206 if isinstance(self
.nextquestiontimer
, threading
._Timer
):
207 self
.nextquestiontimer
.cancel()
208 self
.nextquestiontimer
= None
212 self
.revealpossibilities
= None
215 if self
.missedquestions
> self
.db
['maxmissedquestions']:
217 self
.getbot().msg(self
.getchan(), "%d questions unanswered! Stopping the game.")
220 self
._nextquestion
(qskipped
, iteration
)
223 self
.nextquestiontimer
= threading
.Timer(self
.db
['questionpause'], self
._nextquestion
, args
=[qskipped
, iteration
])
224 self
.nextquestiontimer
.start()
226 def _nextquestion(self
, qskipped
, iteration
):
228 if self
.nextq
is not None:
232 nextq
= random
.choice(self
.db
['questions'])
234 if nextq
[0][0] == "!":
235 nextq
= specialQuestion(nextq
)
237 if len(nextq
) > 2 and nextq
[2] - time
.time() < 7*24*60*60 and iteration
< 10:
238 return self
._nextquestion
(iteration
=iteration
+1) #short-circuit to pick another question
240 nextq
[2] = time
.time()
242 nextq
.append(time
.time())
244 nextq
[1] = nextq
[1].lower()
246 qtext
= "\00304,01Next up: "
247 qary
= nextq
[0].split(None)
249 qtext
+= "\00304,01"+qword
+"\00301,01"+chr(random
.randrange(0x61,0x7A)) #a-z
250 self
.getbot().msg(self
.chan
, qtext
)
254 if isinstance(self
.curq
[1], basestring
): self
.hintanswer
= self
.curq
[1]
255 else: self
.hintanswer
= random
.choice(self
.curq
[1])
257 self
.steptimer
= threading
.Timer(self
.db
['hinttimer'], self
.nexthint
, args
=[1])
258 self
.steptimer
.start()
260 def checkanswer(self
, answer
):
261 if self
.curq
is None:
263 elif isinstance(self
.curq
[1], basestring
):
264 return answer
.lower() == self
.curq
[1]
265 else: # assume it's a list or something.
266 return answer
.lower() in self
.curq
[1]
268 def addpoint(self
, user_obj
, count
=1):
269 user_nick
= str(user_obj
)
270 user
= user_nick
.lower() # save this separately as we use both
271 if user
in self
.db
['users']:
272 self
.db
['users'][user
]['points'] += count
274 self
.db
['users'][user
] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
275 self
.db
['ranks'].append(user
)
277 self
.db
['ranks'].sort(key
=lambda nick
: self
.db
['users'][nick
]['points'], reverse
=True) #re-sort ranks, rather than dealing with anything more efficient
278 for i
in range(0, len(self
.db
['ranks'])):
279 nick
= self
.db
['ranks'][i
]
280 self
.db
['users'][nick
]['rank'] = i
282 if self
.db
['users'][user
]['points'] >= self
.db
['target']:
285 return self
.db
['users'][user
]['points']
287 def points(self
, user
):
288 user
= str(user
).lower()
289 if user
in self
.db
['users']:
290 return self
.db
['users'][user
]['points']
294 def rank(self
, user
):
295 user
= str(user
).lower()
296 if user
in self
.db
['users']:
297 return self
.db
['users'][user
]['rank']+1
299 return len(self
.db
['users'])+1
301 def targetuser(self
, user
):
302 if len(self
.db
['ranks']) == 0: return "no one is ranked!"
304 user
= str(user
).lower()
305 if user
in self
.db
['users']:
306 rank
= self
.db
['users'][user
]['rank']
308 return "you're in the lead!"
310 return self
.db
['ranks'][rank
-1]
312 return self
.db
['ranks'][-1]
313 def targetpoints(self
, user
):
314 if len(self
.db
['ranks']) == 0: return 0
316 user
= str(user
).lower()
317 if user
in self
.db
['users']:
318 rank
= self
.db
['users'][user
]['rank']
322 return self
.db
['users'][self
.db
['ranks'][rank
-1]]['points']
324 return self
.db
['users'][self
.db
['ranks'][-1]]['points']
326 state
= TriviaState()
328 # we have to hook this in modstart, since we don't know the channel until then.
329 def trivia_checkanswer(bot
, user
, chan
, *args
):
330 line
= ' '.join([str(arg
) for arg
in args
])
331 if state
.checkanswer(line
):
332 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
)))
333 if state
.hintsgiven
== 0:
334 bot
.msg(chan
, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user
, state
.addpoint(user
)))
337 @lib.hook('points', needchan
=False)
338 def cmd_points(bot
, user
, chan
, realtarget
, *args
):
339 if chan
== realtarget
: replyto
= chan
342 if len(args
) != 0: who
= args
[0]
345 bot
.msg(replyto
, "%s has %d points." % (who
, state
.points(who
)))
347 @lib.hook('give', glevel
=lib
.STAFF
, needchan
=False)
349 def cmd_give(bot
, user
, chan
, realtarget
, *args
):
352 numpoints
= int(args
[1])
355 balance
= state
.addpoint(whoto
, numpoints
)
357 bot
.msg(chan
, "%s gave %s %d points. New balance: %d" % (user
, whoto
, numpoints
, balance
))
359 @lib.hook('setnextid', glevel
=1, needchan
=False)
360 def cmd_setnextid(bot
, user
, chan
, realtarget
, *args
):
363 state
.nextq
= state
.db
['questions'][qid
]
364 bot
.msg(user
, "Done. Next question is: %s" % (state
.nextq
[0]))
365 except Exception as e
:
366 bot
.msg(user
, "Error: %s" % (e
))
368 @lib.hook('setnext', glevel
=lib
.STAFF
, needchan
=False)
370 def cmd_setnext(bot
, user
, chan
, realtarget
, *args
):
371 line
= ' '.join([str(arg
) for arg
in args
])
372 linepieces
= line
.split('*')
373 if len(linepieces
) < 2:
374 bot
.msg(user
, "Error: need <question>*<answer>")
376 question
= linepieces
[0].strip()
377 answer
= linepieces
[1].strip()
378 state
.nextq
= [question
, answer
]
379 bot
.msg(user
, "Done.")
381 @lib.hook('skip', glevel
=1, needchan
=False)
382 def cmd_skip(bot
, user
, chan
, realtarget
, *args
):
383 state
.nextquestion(qskipped
=True, skipwait
=True)
385 @lib.hook('start', needchan
=False)
386 def cmd_start(bot
, user
, chan
, realtarget
, *args
):
387 if chan
== realtarget
: replyto
= chan
390 if state
.curq
is None and state
.pointvote
is None and state
.nextquestiontimer
is None:
391 state
.nextquestion(skipwait
=True)
392 elif state
.pointvote
is not None:
393 bot
.msg(replyto
, "There's a vote in progress!")
395 bot
.msg(replyto
, "Game is already started!")
397 @lib.hook('stop', glevel
=1, needchan
=False)
398 def cmd_stop(bot
, user
, chan
, realtarget
, *args
):
400 bot
.msg(state
.chan
, "Game stopped by %s" % (user
))
402 bot
.msg(user
, "Game isn't running.")
406 if state
.curq
is not None:
409 state
.steptimer
.cancel()
410 except Exception as e
:
411 print "!!! steptimer.cancel(): %s %r" % (e
,e
)
413 state
.nextquestiontimer
.cancel()
414 state
.nextquestiontimer
= None
415 except Exception as e
:
416 print "!!! nextquestiontimer.cancel(): %s %r" % (e
,e
)
423 @lib.hook('rank', needchan
=False)
424 def cmd_rank(bot
, user
, chan
, realtarget
, *args
):
425 if chan
== realtarget
: replyto
= chan
428 if len(args
) != 0: who
= args
[0]
431 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
)))
433 @lib.hook('top10', needchan
=False)
434 def cmd_top10(bot
, user
, chan
, realtarget
, *args
):
435 if len(state
.db
['ranks']) == 0:
436 return bot
.msg(state
.db
['chan'], "No one is ranked!")
439 for nick
in state
.db
['ranks'][0:10]:
440 user
= state
.db
['users'][nick
]
441 replylist
.append("%s (%s)" % (user
['realnick'], user
['points']))
442 bot
.msg(state
.db
['chan'], ', '.join(replylist
))
444 @lib.hook('settarget', glevel
=lib
.ADMIN
, needchan
=False)
445 def cmd_settarget(bot
, user
, chan
, realtarget
, *args
):
447 state
.db
['target'] = int(args
[0])
448 bot
.msg(state
.db
['chan'], "Target has been changed to %s points!" % (state
.db
['target']))
450 if state
.pointvote
is not None:
451 state
.pointvote
.cancel()
452 state
.pointvote
= None
453 bot
.msg(state
.db
['chan'], "Vote has been cancelled!")
454 except Exception as e
:
456 bot
.msg(user
, "Failed to set target.")
458 @lib.hook('vote', needchan
=False)
459 def cmd_vote(bot
, user
, chan
, realtarget
, *args
):
460 if state
.pointvote
is not None:
461 if int(args
[0]) in state
.voteamounts
:
462 state
.voteamounts
[int(args
[0])] += 1
463 bot
.msg(user
, "Your vote has been recorded.")
465 bot
.msg(user
, "Sorry - that's not an option!")
467 bot
.msg(user
, "There's no vote in progress.")
469 @lib.hook('maxmissed', glevel
=lib
.ADMIN
, needchan
=False)
470 def cmd_maxmissed(bot
, user
, chan
, realtarget
, *args
):
472 state
.db
['maxmissedquestions'] = int(args
[0])
473 bot
.msg(state
.db
['chan'], "Max missed questions before round ends has been changed to %s." % (state
.db
['maxmissedquestions']))
475 bot
.msg(user
, "Failed to set maxmissed.")
477 @lib.hook('hinttimer', glevel
=lib
.ADMIN
, needchan
=False)
478 def cmd_hinttimer(bot
, user
, chan
, realtarget
, *args
):
480 state
.db
['hinttimer'] = float(args
[0])
481 bot
.msg(state
.db
['chan'], "Time between hints has been changed to %s." % (state
.db
['hinttimer']))
483 bot
.msg(user
, "Failed to set hint timer.")
485 @lib.hook('hintnum', glevel
=lib
.ADMIN
, needchan
=False)
486 def cmd_hintnum(bot
, user
, chan
, realtarget
, *args
):
488 state
.db
['hintnum'] = int(args
[0])
489 bot
.msg(state
.db
['chan'], "Max number of hints has been changed to %s." % (state
.db
['hintnum']))
491 bot
.msg(user
, "Failed to set hintnum.")
493 @lib.hook('questionpause', glevel
=lib
.ADMIN
, needchan
=False)
494 def cmd_questionpause(bot
, user
, chan
, realtarget
, *args
):
496 state
.db
['questionpause'] = float(args
[0])
497 bot
.msg(state
.db
['chan'], "Pause between questions has been changed to %s." % (state
.db
['questionpause']))
499 bot
.msg(user
, "Failed to set questionpause.")
501 @lib.hook('findq', glevel
=1, needchan
=False)
502 def cmd_findquestion(bot
, user
, chan
, realtarget
, *args
):
503 matches
= [str(i
) for i
in range(len(state
.db
['questions'])) if state
.db
['questions'][i
][0] == ' '.join(args
)] #TODO looser equality check
505 bot
.msg(user
, "Multiple matches: %s" % (', '.join(matches
)))
506 elif len(matches
) == 1:
507 bot
.msg(user
, "One match: %s" % (matches
[0]))
509 bot
.msg(user
, "No match.")
511 @lib.hook('delq', glevel
=lib
.STAFF
, needchan
=False)
512 @lib.hook('deleteq', glevel
=lib
.STAFF
, needchan
=False)
513 def cmd_deletequestion(bot
, user
, chan
, realtarget
, *args
):
515 backup
= state
.db
['questions'][int(args
[0])]
516 del state
.db
['questions'][int(args
[0])]
517 bot
.msg(user
, "Deleted %s*%s" % (backup
[0], backup
[1]))
519 bot
.msg(user
, "Couldn't delete that question.")
521 @lib.hook('addq', glevel
=lib
.STAFF
, needchan
=False)
522 def cmd_addquestion(bot
, user
, chan
, realtarget
, *args
):
523 line
= ' '.join([str(arg
) for arg
in args
])
524 linepieces
= line
.split('*')
525 if len(linepieces
) < 2:
526 bot
.msg(user
, "Error: need <question>*<answer>")
528 question
= linepieces
[0].strip()
529 answer
= linepieces
[1].strip()
530 state
.db
['questions'].append([question
, answer
])
531 bot
.msg(user
, "Done. Question is #%s" % (len(state
.db
['questions'])-1))
534 @lib.hook('triviahelp', needchan
=False)
535 def cmd_triviahelp(bot
, user
, chan
, realtarget
, *args
):
537 bot
.msg(user
, "START")
538 bot
.msg(user
, "TOP10")
539 bot
.msg(user
, "POINTS [<user>]")
540 bot
.msg(user
, "RANK [<user>]")
542 bot
.msg(user
, "START (ANYONE )")
543 bot
.msg(user
, "TOP10 (ANYONE )")
544 bot
.msg(user
, "POINTS [<user>] (ANYONE )")
545 bot
.msg(user
, "RANK [<user>] (ANYONE )")
547 bot
.msg(user
, "SKIP (>=KNOWN)")
548 bot
.msg(user
, "STOP (>=KNOWN)")
549 bot
.msg(user
, "FINDQ <question> (>=KNOWN)")
550 if user
.glevel
>= lib
.STAFF
:
551 bot
.msg(user
, "GIVE <user> [<points>] (>=STAFF)")
552 bot
.msg(user
, "SETNEXT <q>*<a> (>=STAFF)")
553 bot
.msg(user
, "ADDQ <q>*<a> (>=STAFF)")
554 bot
.msg(user
, "DELETEQ <q>*<a> (>=STAFF) [aka DELQ]")
555 if user
.glevel
>= lib
.ADMIN
:
556 bot
.msg(user
, "SETTARGET <points> (>=ADMIN)")
557 bot
.msg(user
, "MAXMISSED <questions> (>=ADMIN)")
558 bot
.msg(user
, "HINTTIMER <float seconds> (>=ADMIN)")
559 bot
.msg(user
, "HINTNUM <hints> (>=ADMIN)")
560 bot
.msg(user
, "QUESTIONPAUSE <float seconds> (>=ADMIN)")
563 def num_417(bot
, textline
):
564 bot
.msg(state
.db
['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
565 state
.nextquestion(qskipped
=False, skipwait
=True)
568 def num_TOPIC(bot
, textline
):
569 pieces
= textline
.split(None, 4)
571 if chan
!= state
.db
['chan']:
573 gottopic
= pieces
[4][1:]
575 formatted
= state
.db
['topicformat'] % {
576 'chan': state
.db
['chan'],
577 'top': state
.db
['users'][state
.db
['ranks'][0]]['realnick'],
578 'top3': '/'.join([state
.db
['users'][state
.db
['ranks'][x
]]['realnick'] for x
in range(3) if x
< len(state
.db
['ranks'])]),
579 'topscore': state
.db
['users'][state
.db
['ranks'][0]]['points'],
580 'target': state
.db
['target'],
582 if gottopic
!= formatted
:
583 state
.getbot().conn
.send("TOPIC %s :%s" % (state
.db
['chan'], formatted
))
586 def specialQuestion(oldq
):
587 newq
= [oldq
[0], oldq
[1]]
588 qtype
= oldq
[0].upper()
590 if qtype
== "!MONTH":
591 newq
[0] = "What month is it currently (in UTC)?"
592 newq
[1] = time
.strftime("%B", time
.gmtime()).lower()
593 elif qtype
== "!MATH+":
594 randnum1
= random
.randrange(0, 11)
595 randnum2
= random
.randrange(0, 11)
596 newq
[0] = "What is %d + %d?" % (randnum1
, randnum2
)
597 newq
[1] = spellout(randnum1
+randnum2
)
602 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
603 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
604 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"