Example #1
0
	def _start (self, irc, prefix=True):
		if self.tache != 0:
			schedule.removeEvent(self.tache)
			self.tache = 0
		if self.en_cours:
			s = self.c.getSolution ()
			sr = ""
			if s[0] == 0:
				sr = "Le compte est bon: "
			else:
				sr = "Loin de %s: " % str(s[0])
			sr += "|".join (s[1])
			irc.reply (sr, prefixNick=False)
			self.en_cours = False
			if not self.tries:
				irc.reply ("Fin du jeu", prefixNick=prefix)
				return
		self.tries = False
		self.c.generate ()
		irc.reply (self.c.nombres, prefixNick=prefix)
		irc.reply ("Cible: %d" % self.c.res_cible, prefixNick=prefix)
		self.en_cours = True
		def f():
			self.tache = 0
			self._start (irc, prefix=False)
		self.tache = schedule.addEvent(f, time.time() + 300)
Example #2
0
 def die(self):
     for name in self._names:
         try:
             schedule.removeEvent(name)
         except KeyError:
             pass
     self._names = []
Example #3
0
 def __init__(self, irc, channel, num, plugin):
     self.rng = random.Random()
     self.rng.seed()
     self.registryValue = plugin.registryValue
     self.irc = irc
     self.channel = channel
     self.num = num
     self.numAsked = 0
     self.hints = 0
     self.games = plugin.games
     self.scores = plugin.scores
     self.scorefile = plugin.scorefile
     self.questionfile = self.registryValue('questionFile')
     self.total = num
     self.active = True
     self.questions = []
     self.roundscores = {}
     self.unanswered = 0
     f = open(self.questionfile, 'r')
     line = f.readline()
     while line:
         self.questions.append(line.strip('\n\r'))
         line = f.readline()
     f.close()
     try:
         schedule.removeEvent('next_%s' % self.channel)
     except KeyError:
         pass
     self.newquestion()
Example #4
0
 def die(self):
     # remove scheduler event
     try:
         schedule.removeEvent('mwrcEvent')
     except KeyError:
         pass
     self.__parent.die()
Example #5
0
 def stop_previous_task(self, task):
     try:
         schedule.removeEvent(task)
         return 'Stopped'
         pass
     except:
         pass
Example #6
0
    def __init__(self, irc):
        self.__parent = super(Bantracker, self)
        self.__parent.__init__(irc)
        self.default_irc = irc
        self.lastMsgs = {}
        self.lastStates = {}
        self.replies = {}
        self.logs = ircutils.IrcDict()
        self.nicks = {}
        self.hosts = {}
        self.bans = ircutils.IrcDict()

        self.thread_timer = threading.Timer(10.0, dequeue, args=(self,irc))
        self.thread_timer.start()

        db = self.registryValue('database')
        if db:
            self.db = sqlite3.connect(db)
        else:
            self.db = None
        self.get_bans(irc)
        self.get_nicks(irc)
        self.pendingReviews = PersistentCache('bt.reviews.db')
        self.pendingReviews.open()
        self._banreviewfix()
        # add scheduled event for check bans that need review, check every hour
        try:
            schedule.removeEvent(self.name())
        except:
            pass
        schedule.addPeriodicEvent(lambda : self.reviewBans(irc), 60*60,
                name=self.name())
Example #7
0
 def cutwire(self, irc, cutWire):
     self.cutWire = cutWire
     self.responded = True
     if self.goodWire.lower() == self.cutWire.lower():
         self.irc.queueMsg(
             ircmsgs.privmsg(
                 self.channel,
                 '%s has cut the %s wire!  This has defused the bomb!' %
                 (self.victim, self.cutWire)))
         self.irc.queueMsg(
             ircmsgs.privmsg(
                 self.channel,
                 'He then quickly rearms the bomb and throws it back at %s with just seconds on the clock!'
                 % self.sender))
         self.victim = self.sender
         self.thrown = True
         schedule.rescheduleEvent('%s_bomb' % self.channel,
                                  time.time() + 5)
         if self.victim == irc.nick:
             time.sleep(1)
             self.irc.queueMsg(ircmsgs.privmsg(self.channel, '@duck'))
             time.sleep(1)
             self.duck(self.irc, irc.nick)
     else:
         schedule.removeEvent('%s_bomb' % self.channel)
         self.detonate(irc)
    def _topic_callback(self):
        self.topic_lock.acquire()

        sections = {
            lambda: len(TestingRCBugs().get_bugs()): 'RC bug count:',
            NewQueue().get_size: 'NEW queue:',
            RmQueue().get_size: 'RM queue:',
        }

        try:
            values = {}
            for callback, prefix in sections.iteritems():
                values[callback] = callback()

            for channel in self.irc.state.channels:
                new_topic = topic = self.irc.state.getTopic(channel)

                for callback, prefix in sections.iteritems():
                    if values[callback]:
                        new_topic = rewrite_topic(new_topic, prefix, values[callback])

                if topic != new_topic:
                    log.info("Queueing change of topic in #%s to '%s'" % (channel, new_topic))
                    self.queued_topics[channel] = new_topic

                    event_name = '%s_topic' % channel
                    try:
                        schedule.removeEvent(event_name)
                    except KeyError:
                        pass
                    schedule.addEvent(lambda channel=channel: self._update_topic(channel),
                        time.time() + 60, event_name)
        finally:
            self.topic_lock.release()
Example #9
0
 def stop_polling(self):
     logger.info("Stopping GEA job %s" % self.job_name)
     try:
         schedule.removeEvent(self.job_name)
     except KeyError:
         logger.error('Attempted to stop nonexistant GEA job: %s' %
                      self.job_name)
Example #10
0
 def answer(self, msg):
     channel = msg.args[0]
     correct = False
     for ans in self.a:
         guess = re.sub('[^a-zA-Z0-9]+', '', msg.args[1]).lower()
         answer = re.sub('[^a-zA-Z0-9]+', '', ans).lower()
         dist = self.DL(guess, answer)
         flexibility = self.registryValue('flexibility', self.channel)
         if dist <= len(ans) / flexibility:
             correct = True
         #if self.registryValue('debug'):
         #    self.reply('Distance: %d' % dist)
     if correct:
         name = "{0}:{1}".format(channel, msg.nick)
         if not name in self.scores:
             self.scores[name] = 0
         self.scores[name] += self.p
         if not name in self.roundscores:
             self.roundscores[name] = 0
         self.roundscores[name] += self.p
         self.unanswered = 0
         self.reply(
             _('%s got it! The full answer was: %s. Points: %d') %
             (msg.nick, self.a[0], self.scores[name]))
         schedule.removeEvent('next_%s' % self.channel)
         self.writeScores()
         self.newquestion()
Example #11
0
    def start(self, irc, msg, args, channel, optlist):
        """[<channel>] [--num <number of questions>] [--cat <category>]

        Starts a game of Jeopardy! <channel> is only necessary if the message
        isn't sent in the channel itself."""
        optlist = dict(optlist)
        if 'num' in optlist:
            num = optlist.get('num')
        else:
            num = self.registryValue('defaultRoundLength', channel)
        if 'cat' in optlist:
            category = optlist.get('cat')
        else:
            category = 'random'
        channel = ircutils.toLower(channel)
        if channel in self.games:
            if not self.games[channel].active:
                del self.games[channel]
                try:
                    schedule.removeEvent('next_%s' % channel)
                except KeyError:
                    pass
                irc.reply(_('Orphaned Jeopardy! game found and removed.'))
                irc.reply("This... is... Jeopardy!", prefixNick=False)
                self.games[channel] = self.Game(irc, channel, num, category,
                                                self)
            else:
                self.games[channel].num += num
                self.games[channel].total += num
                irc.reply(_('%d questions added to active game!') % num)
        else:
            irc.reply("This... is... Jeopardy!", prefixNick=False)
            self.games[channel] = self.Game(irc, channel, num, category, self)
        irc.noReply()
Example #12
0
 def cutwire(self, irc, cutWire):
     self.cutWire = cutWire
     self.responded = True
     specialWires = False
     if self.rng.randint(1,len(self.wires)) == 1 or self.victim.lower()=='jacksonmj':
         specialWires = True
     if self.cutWire.lower() == 'potato' and specialWires:
         self.irc.queueMsg(ircmsgs.privmsg(self.channel, '%s has turned the bomb into a potato! This has rendered it mostly harmless, and slightly %s.' % (self.victim, self.goodWire)))
         self.defuse()
     elif self.cutWire.lower() == 'pizza' and specialWires:
         self.irc.queueMsg(ircmsgs.privmsg(self.channel, '%s has turned the bomb into a pizza! %s\'s pants have been ruined by the pizza stuffed into them, but at least they haven\'t exploded.' % (self.victim, self.victim)))
         self.defuse()
     elif self.goodWire.lower() == self.cutWire.lower():
         self.irc.queueMsg(ircmsgs.privmsg(self.channel, '%s has cut the %s wire!  This has defused the bomb!' % (self.victim, self.cutWire)))
         if self.victim.lower() != self.sender.lower():
             self.irc.queueMsg(ircmsgs.privmsg(self.channel, 'He then quickly rearms the bomb and throws it back at %s with just seconds on the clock!' % self.sender))
             tmp = self.victim
             self.victim = self.sender
             self.sender = tmp
             self.thrown = True
             schedule.rescheduleEvent('%s_bomb' % self.channel, time.time() + 10)
             if self.victim == irc.nick:
                 time.sleep(1)
                 self.irc.queueMsg(ircmsgs.privmsg(self.channel, '@duck'))
                 time.sleep(1)
                 self.duck(self.irc, irc.nick)
         else:
             self.defuse()
     else:
         schedule.removeEvent('%s_bomb' % self.channel)
         self.detonate(irc)
Example #13
0
        def defuse(self):
            if not self.active:
                return

            self.active = False
            self.thrown = False
            schedule.removeEvent('{}_bomb'.format(self.channel))
Example #14
0
    def start(self, irc, msg, args, channel, num):
        """[<kanal>] [<broj pitanja>]

        Zapocinje novu igru.  <kanal> nije obavezan osim u slucaju da komandu dajete botu na PM."""
        if num == None:
            num = self.registryValue('defaultRoundLength', channel)
        #elif num > 100:
        #    irc.reply('Zao nam je ali za sada ne mozete igrati sa vise '
        #              'od 100 pitanja :(')
        #    num = 100
        channel = ircutils.toLower(channel)
        if channel in self.games:
            if not self.games[channel].active:
                del self.games[channel]
                try:
                    schedule.removeEvent('next_%s' % channel)
                except KeyError:
                    pass
                irc.reply(_('Orphaned trivia game found and removed.'))
            else:
                self.games[channel].num += num
                self.games[channel].total += num
                irc.reply(_('%d pitanja dodano u trenutnu igru!') % num)
        else:
            self.games[channel] = self.Game(irc, channel, num, self)
        irc.noReply()
Example #15
0
    def _start(self, irc, prefix=True):
        if self.tache != 0:
            schedule.removeEvent(self.tache)
            self.tache = 0
        if self.en_cours:
            s = self.c.getSolution()
            sr = ""
            if s[0] == 0:
                sr = "Le compte est bon: "
            else:
                sr = "Loin de %s: " % str(s[0])
            sr += "|".join(s[1])
            irc.reply(sr, prefixNick=False)
            self.en_cours = False
            if not self.tries:
                irc.reply("Fin du jeu", prefixNick=prefix)
                return
        self.tries = False
        self.c.generate()
        irc.reply(self.c.nombres, prefixNick=prefix)
        irc.reply("Cible: %d" % self.c.res_cible, prefixNick=prefix)
        self.en_cours = True

        def f():
            self.tache = 0
            self._start(irc, prefix=False)

        self.tache = schedule.addEvent(f, time.time() + 300)
Example #16
0
 def doPrivmsg(self, irc, msg):
     channel = msg.args[0]
     nick = msg.prefix.split('!')[0]
     if channel not in self.states:
         return
     reply = None
     state = self.states[channel]
     for mode, answer in state.answers:
         if mode == 'r':
             if msg.args[1].lower() == answer.lower():
                 state.adjust(nick, state.question[0])
                 reply = _('Congratulations %s! The answer was %r.')
                 reply %= (nick, answer)
         elif mode == 'm':
             if answer.match(msg.args[1]):
                 state.adjust(nick, state.question[0])
                 reply = _('Congratulations %s! The answer was %r.')
                 reply %= (nick, msg.args[1])
     if reply is not None:
         schedule.removeEvent('Eureka-nextClue-%s' % channel)
         otherAnswers = [y for x,y in state.answers
                 if x == 'r' and y.lower() != msg.args[1].lower()]
         if len(otherAnswers) == 1:
             reply += ' ' + _('Another valid answer is: \'%s\'.')
             reply %= otherAnswers[0]
         elif len(otherAnswers) >= 2:
             reply += ' ' + _('Other valid answers are: \'%s\'.')
             reply %= '\', \''.join([x for x in otherAnswers])
         irc.reply(reply, prefixNick=False)
         self._ask(irc, channel, True)
        def defuse(self):
            if not self.active:
                return

            self.active = False
            self.thrown = False
            schedule.removeEvent("{}_bomb".format(self.channel))
Example #18
0
 def __init__(self, irc):
     self.__parent = super(Twitter, self)
     self.__parent.__init__(irc)
     self.irc = irc
     self.mentionSince = None
     self.tweetsSince = None
     self.snarfdb = SNARFDB()
     try:
         schedule.removeEvent('Mentions')
     except KeyError:
         pass
     try:
         schedule.removeEvent('Tweets')
     except KeyError:
         pass
     t_consumer_key = self.registryValue('consumer_key')
     t_consumer_secret = self.registryValue('consumer_secret')
     t_access_key = self.registryValue('access_key')
     t_access_secret = self.registryValue('access_secret')
     self.api = twitter.Api(consumer_key=t_consumer_key, consumer_secret=t_consumer_secret, access_token_key=t_access_key, access_token_secret=t_access_secret)
     if self.registryValue('displayTweets'):
         statuses = self.api.GetUserTimeline(include_rts=True, count=1)
         if len(statuses) > 0:
             self.tweetsSince = statuses[0].id
         def tweetsCaller():
             self._tweets(irc)
         schedule.addPeriodicEvent(tweetsCaller, 300, 'Tweets')
     if self.registryValue('displayReplies'):
         statuses = self.api.GetMentions()
         if len(statuses) > 0:
             self.mentionSince = statuses[0].id
         def mentionCaller():
             self._mention(irc)
         schedule.addPeriodicEvent(mentionCaller, 300, 'Mentions')
Example #19
0
        def cutwire(self, irc, cutWire):
            self.cutWire = cutWire
            self.responded = True
            specialWires = False

            if self.rng.randint(1, len(self.wires)) == 1 or self.victim.lower() == 'jacksonmj':
                specialWires = True

            if self.cutWire.lower() == 'potato' and specialWires:
                self.irc.queueMsg(ircmsgs.privmsg(self.channel, '{} has turned the bomb into a potato! This has rendered it mostly harmless, and slightly{}.'.format(self.victim, self.goodWire)))
                self.defuse()
            elif self.cutWire.lower() == 'pizza' and specialWires:
                self.irc.queueMsg(ircmsgs.privmsg(self.channel, '{0} has turned the bomb into a pizza! {0}\'s pants have been ruined by the pizza stuffed into them, but at least they haven\'t exploded.'.format(self.victim)))
                self.defuse()
            elif self.goodWire.lower() == self.cutWire.lower():
                self.irc.queueMsg(ircmsgs.privmsg(self.channel, '{} has cut the {} wire!  This has defused the bomb!'.format(self.victim, self.cutWire)))

                if self.victim.lower() != self.sender.lower():
                    self.irc.queueMsg(ircmsgs.privmsg(self.channel, 'He then quickly rearms the bomb and throws it back at {} with just seconds on the clock!'.format(self.sender)))
                    tmp = self.victim
                    self.victim = self.sender
                    self.sender = tmp
                    self.thrown = True
                    schedule.rescheduleEvent('{}_bomb'.format(self.channel), time.time() + 10)

                    if self.victim == irc.nick:
                        time.sleep(1)
                        self.irc.queueMsg(ircmsgs.privmsg(self.channel, '@duck'))
                        time.sleep(1)
                        self.duck(self.irc, irc.nick)
                else:
                    self.defuse()
            else:
                schedule.removeEvent('{}_bomb'.format(self.channel))
                self.detonate(irc)
Example #20
0
 def stopHello():
     print "Going to stop %s" % eventName
     try:
         schedule.removeEvent(eventName)
         print "Event %s stopped" % eventName
     except Exception as e:
         print e
Example #21
0
    def start(self, irc, msg, args, channel, num):
        """[<channel>] [<number of questions>]

        Starts a game of trivia.  <channel> is only necessary if the message
        isn't sent in the channel itself."""
        if num == None:
            num = self.registryValue('defaultRoundLength', channel)
        #elif num > 100:
        #    irc.reply('sorry, for now, you can\'t start games with more '
        #              'than 100 questions :(')
        #    num = 100
        channel = ircutils.toLower(channel)
        if channel in self.games:
            if not self.games[channel].active:
                del self.games[channel]
                try:
                    schedule.removeEvent('next_%s' % channel)
                except KeyError:
                    pass
                irc.reply(_('Orphaned trivia game found and removed.'))
            else:
                self.games[channel].num += num
                self.games[channel].total += num
                irc.reply(_('%d questions added to active game!') % num)
        else:
            self.games[channel] = self.Game(irc, channel, num, self)
        irc.noReply()
Example #22
0
    def __init__(self, irc):
        self.__parent = super(SubredditAnnouncer, self)
        self.__parent.__init__(irc)
        self.savefile = conf.supybot.directories.data.dirize("subredditAnnouncer.db")
        self.headers = {"User-Agent": "SubredditAnnouncer ([email protected])"}

        def checkForPosts():
            self.checkReddit(irc)
        try:
            schedule.addPeriodicEvent(checkForPosts,
                                      self.registryValue('checkinterval')*60,
                                      'redditCheck', False)
        except AssertionError:
            schedule.removeEvent('redditCheck')
            schedule.addPeriodicEvent(checkForPosts,
                                      self.registryValue('checkinterval')*60,
                                      'redditCheck', False)
        try:
            if self.registryValue('dsn') != "":
                if "raven" in dir():  # Check that raven was actually imported
                    self.raven = raven.Client(self.registryValue("dsn"))
                else:
                    self.log.error("dsn defined but raven not installed! Please pip install raven")
        except NonExistentRegistryEntry:
            pass
Example #23
0
    def _giveClue(self, irc, channel, now=False):
        state = self.states[channel]
        (delay, clue, valid) = state.getClue()

        def event():
            try:
                schedule.removeEvent("Eureka-nextClue-%s" % channel)
            except KeyError:
                pass
            if clue is None:
                assert valid is None
                irc.reply(
                    _("Nobody replied with (one of this) " "answer(s): %s.")
                    % ", ".join([y for x, y in state.answers if x == "r"]),
                    prefixNick=False,
                )
                self._ask(irc, channel)
            else:
                irc.reply(_("Another clue: %s") % clue, prefixNick=False)
                self._giveClue(irc, channel)

        eventName = "Eureka-nextClue-%s" % channel
        if now and eventName in schedule.schedule.events:
            schedule.schedule.events[eventName]()
            schedule.removeEvent(eventName)
        schedule.addEvent(event, time.time() + delay, eventName)
Example #24
0
    def _topic_callback(self):
        sections = {
            self.testing_rc_bugs.get_number_bugs: 'RC bug count',
            self.stable_rc_bugs.get_number_bugs: 'Stable RC bug count',
            self.new_queue.get_size: 'NEW queue',
            RmQueue().get_size: 'RM queue',
        }

        with self.topic_lock:
            values = {}
            for callback, prefix in sections.iteritems():
                values[callback] = callback()

            for channel in self.irc.state.channels:
                new_topic = topic = self.irc.state.getTopic(channel)

                for callback, prefix in sections.iteritems():
                    if values[callback]:
                        new_topic = rewrite_topic(new_topic, prefix, values[callback])

                if topic != new_topic:
                    log.info("Queueing change of topic in #%s to '%s'" % (channel, new_topic))
                    self.queued_topics[channel] = new_topic

                    event_name = '%s_topic' % channel
                    try:
                        schedule.removeEvent(event_name)
                    except KeyError:
                        pass
                    schedule.addEvent(lambda channel=channel: self._update_topic(channel),
                        time.time() + 60, event_name)
Example #25
0
 def doPrivmsg(self, irc, msg):
     channel = msg.args[0]
     nick = msg.prefix.split("!")[0]
     if channel not in self.states:
         return
     reply = None
     state = self.states[channel]
     for mode, answer in state.answers:
         if mode == "r":
             if msg.args[1].lower() == answer.lower():
                 state.adjust(nick, state.question[0])
                 reply = _("Congratulations %s! The answer was %s.")
                 reply %= (nick, answer)
         elif mode == "m":
             if answer.match(msg.args[1]):
                 state.adjust(nick, state.question[0])
                 reply = _("Congratulations %s! The answer was %s.")
                 reply %= (nick, msg.args[1])
     if reply is not None:
         schedule.removeEvent("Eureka-nextClue-%s" % channel)
         otherAnswers = [y for x, y in state.answers if x == "r" and y.lower() != msg.args[1].lower()]
         if len(otherAnswers) == 1:
             reply += " " + _("Another valid answer is: '%s'.")
             reply %= otherAnswers[0]
         elif len(otherAnswers) >= 2:
             reply += " " + _("Other valid answers are: '%s'.")
             reply %= "', '".join([x for x in otherAnswers])
         irc.reply(reply, prefixNick=False)
         self._ask(irc, channel, True)
Example #26
0
    def __init__(self, irc):
        self.__parent = super(SubredditAnnouncer, self)
        self.__parent.__init__(irc)
        self.savefile = conf.supybot.directories.data.dirize(
            "subredditAnnouncer.db")
        self.headers = {"User-Agent": "SubredditAnnouncer ([email protected])"}

        def checkForPosts():
            self.checkReddit(irc)

        try:
            schedule.addPeriodicEvent(checkForPosts,
                                      self.registryValue('checkinterval') * 60,
                                      'redditCheck', False)
        except AssertionError:
            schedule.removeEvent('redditCheck')
            schedule.addPeriodicEvent(checkForPosts,
                                      self.registryValue('checkinterval') * 60,
                                      'redditCheck', False)
        try:
            if self.registryValue('dsn') != "":
                if "raven" in dir():  # Check that raven was actually imported
                    self.raven = raven.Client(self.registryValue("dsn"))
                else:
                    self.log.error(
                        "dsn defined but raven not installed! Please pip install raven"
                    )
        except NonExistentRegistryEntry:
            pass
Example #27
0
    def _run_game (self, irc):
        if self.task != 0:
            schedule.removeEvent(self.task)
            self.task = 0

        if self.no_answer is 3:
            self.started = False
            irc.queueMsg(ircmsgs.privmsg(CHANNEL, 'Jeu Stoppé'))
            return

        if self.started:
            if self.tries['score'] != 0:
                self.no_answer = 0
                self._display_best_try(irc)
                self._best_word(irc)
                self._update_score_db()
                self._display_top(irc)
                self._init_tries()
            else:
                self.no_answer += 1
            self._choose_letters(irc)

        def f():
            self.task = 0
            self._run_game (irc)
        if self.started:
            self.task = schedule.addEvent(f, time.time() + LAPS_TIME)
Example #28
0
 def stop(self):
     self.reply(_('Jeopardy! stopping.'))
     self.active = False
     try:
         schedule.removeEvent('next_%s' % self.channel)
         schedule.removeEvent('new_%s' % self.channel)
     except KeyError:
         pass
     scores = iter(self.roundscores.items())
     sorted = []
     for i in range(0, len(self.roundscores)):
         item = next(scores)
         sorted.append(item)
     def cmp(a, b):
         return b[1] - a[1]
     sorted.sort(key=lambda item: item[1], reverse=True)
     max = 3
     if len(sorted) < max:
         max = len(sorted)
         #self.reply('max: %d.  len: %d' % (max, len(sorted)))
     s = _('Top finishers:')
     if max > 0:
         recipients = []
         maxp = sorted[0][1]
         for i in range(0, max):
             item = sorted[i]
             s = _('%s (%s: %s)') % (s, str(item[0].split(':')[1]), item[1])
         self.reply(s)
     try:
         del self.games[dynamic.channel]
     except KeyError:
         return
Example #29
0
 def _schedule_next_event(self):
     """
     (Re)schedules the next game event (start, time left warning, end)
     as appropriate.
     """
     # Unschedule any previous event
     try:
         schedule.removeEvent(self.event_name)
     except KeyError:
         pass
     if self.state == Boggle.State.PREGAME:
         # Schedule "get ready" message
         schedule.addEvent(self._get_ready, self.init_time + self.delay,
                           self.event_name)
     elif self.state == Boggle.State.READY:
         # Schedule game start
         schedule.addEvent(self._begin_game,
                           self.init_time + self.delay + 3, self.event_name)
     elif self.state == Boggle.State.ACTIVE:
         if self.warnings:
             # Warn almost half a second early, in case there is a little
             # latency before the event is triggered. (Otherwise a 30 second
             # warning sometimes shows up as 29 seconds remaining.)
             warn_time = self.end_time - self.warnings[0] - 0.499
             schedule.addEvent(self._time_warning, warn_time,
                               self.event_name)
             self.warnings = self.warnings[1:]
         else:
             # Schedule game end
             schedule.addEvent(self._end_game, self.end_time,
                               self.event_name)
Example #30
0
 def die(self):
     try:
         schedule.removeEvent(self.name())
         schedule.removeEvent(self.name() + 'b')
     except AssertionError:
         pass
     self.cache.clear()
Example #31
0
    def __init__(self, irc):
        self.__parent = super(Twitter, self)
        self.__parent.__init__(irc)
        self.irc = irc
        self.mentionSince = None
        self.snarfdb = SNARFDB()
        try:
            schedule.removeEvent('Mentions')
        except KeyError:
            pass
        t_consumer_key = self.registryValue('consumer_key')
        t_consumer_secret = self.registryValue('consumer_secret')
        t_access_key = self.registryValue('access_key')
        t_access_secret = self.registryValue('access_secret')
        self.api = twitter.Api(consumer_key=t_consumer_key,
                               consumer_secret=t_consumer_secret,
                               access_token_key=t_access_key,
                               access_token_secret=t_access_secret)
        if self.registryValue('displayReplies'):
            statuses = self.api.GetMentions()
            if len(statuses) > 0:
                self.mentionSince = statuses[0].id

            def mentionCaller():
                self._mention(irc)

            schedule.addPeriodicEvent(mentionCaller, 300, 'Mentions')
Example #32
0
 def answer(self, msg):
     correct = False
     channel = msg.args[0]
     for ans in self.a:
         dist = self.DL(str.lower(msg.args[1]), str.lower(ans))
         flexibility = self.registryValue('flexibility', self.channel)
         if dist <= len(ans) / flexibility:
             correct = True
         #if self.registryValue('debug'):
         #    self.reply('Distance: %d' % dist)
     if correct:
         if not channel in self.scores:
             self.scores[channel] = {}
         if not msg.nick in self.scores[channel]:
             self.scores[channel][msg.nick] = 0
         self.scores[channel][msg.nick] += 1
         if not msg.nick in self.roundscores:
             self.roundscores[msg.nick] = 0
         self.roundscores[msg.nick] += 1
         self.unanswered = 0
         self.reply(_('%s got it!  The full answer was: %s. Points: %d') %
                    (msg.nick, self.a[0], self.scores[channel][msg.nick]))
         schedule.removeEvent('next_%s' % self.channel)
         self.writeScores()
         self.newquestion()
Example #33
0
 def die(self):
     for user in self._users:
         schedule.removeEvent(user)
     for search in self._searches:
         schedule.removeEvent(search)
     self._streams = []
     self._searches = []
Example #34
0
    def closepoll(self, irc, msg, args, channel, pollid):
        """[channel] <id>
        Closes the poll with the given <id>. Further votes will not be
        allowed. <channel> is only necessary if the message isn't sent in
        the channel itself."""

        db = self.getDb(channel)
        cursor = db.cursor()

        # query to check poll exists and if it is closed
        pollinfo = self._poll_info(db, pollid)
        if pollinfo is None:
            irc.error('Poll id doesnt exist')
            return
        if pollinfo[1] is not None:
            irc.error('Poll already closed on %s' %
                      pollinfo[1].strftime('%Y-%m-%d at %-I:%M %p'))
            return

        # close the poll in db
        self._execute_query(cursor, 'UPDATE polls SET closed=? WHERE id=?',
                            datetime.datetime.now(), pollid)
        db.commit()

        try:
            schedule.removeEvent('%s_poll_%s' % (channel, pollid))
            self.poll_schedules.remove('%s_poll_%s' % (channel, pollid))
        except:
            self.log.warning('Failed to remove schedule event')

        irc.replySuccess()
Example #35
0
 def answer(self, msg):
     correct = False
     for ans in self.a:
         dist = self.DL(str.lower(msg.args[1]), str.lower(ans))
         flexibility = self.registryValue('flexibility', self.channel)
         if dist <= len(ans) / flexibility:
             correct = True
         #if self.registryValue('debug'):
         #    self.reply('Distance: %d' % dist)
     if correct:
         if not msg.nick in self.scores:
             self.scores[msg.nick] = 0
         self.scores[msg.nick] += 1
         if not msg.nick in self.roundscores:
             self.roundscores[msg.nick] = 0
         self.roundscores[msg.nick] += 1
         self.unanswered = 0
         gotit = '%s got it!' % (msg.nick)
         gotit = ircutils.bold(gotit)
         points= ircutils.bold('Points')
         self.reply('%s The full answer was: %s. %s: %d' %
                    (gotit, self.a[0], points, self.scores[msg.nick]))
         schedule.removeEvent('next_%s' % self.channel)
         self.writeScores()
         self.newquestion()
Example #36
0
 def __init__(self, irc):
     self.__parent = super(Hardball, self)
     self.__parent.__init__(irc)
     # initial states for channels.
     self.channels = {}  # dict for channels with values as teams/ids
     self._loadpickle()  # load saved data.
     # initial states for games.
     self.games = None
     self.nextcheck = None
     # dupedict.
     self.dupedict = {}
     # base url.
     self.baseurl = b64decode('aHR0cDovL2dkMi5tbGIuY29t')
     try:
         self.nohitterInning = self.registryValue('inningToAnnounceNoHitter')
     except:
         self.log.info('Registry value for no-hitter inning not set, defaulting to 7')
         self.nohitterInning = 7
     # fill in the blanks.
     if not self.games:
         self.games = self._fetchgames()
     # now schedule our events.
     def checkhardballcron():
         self.checkhardball(irc)
     try:  # check scores.
         schedule.addPeriodicEvent(checkhardballcron, self.registryValue('checkInterval'), now=False, name='checkhardball')
     except AssertionError:
         try:
             schedule.removeEvent('checkhardball')
         except KeyError:
             pass
         schedule.addPeriodicEvent(checkhardballcron, self.registryValue('checkInterval'), now=False, name='checkhardball')
Example #37
0
 def stop(self):
     self.reply(_('Trivia stopping.'))
     self.active = False
     try:
         schedule.removeEvent('next_%s' % self.channel)
     except KeyError:
         pass
     scores = self.roundscores.iteritems()
     sorted = []
     for i in range(0, len(self.roundscores)):
         item = scores.next()
         sorted.append(item)
     def cmp(a, b):
         return b[1] - a[1]
     sorted.sort(cmp)
     max = 3
     if len(sorted) < max:
         max = len(sorted)
         #self.reply('max: %d.  len: %d' % (max, len(sorted)))
     s = _('Top finishers: ')
     if max > 0:
         recipients = []
         maxp = sorted[0][1]
         for i in range(0, max):
             item = sorted[i]
             s = _('%s %s %s.') % (s, item[0], item[1])
         self.reply(s)
     del self.games[self.channel]
Example #38
0
 def die(self):
     # remove scheduler event
     try:
         schedule.removeEvent('mwrcEvent')
     except KeyError:
         pass
     self.__parent.die()
Example #39
0
    def _giveClue(self, irc, channel, now=False):
        state = self.states[channel]
        (delay, clue, valid) = state.getClue()

        def event():
            try:
                schedule.removeEvent('Eureka-nextClue-%s' % channel)
            except KeyError:
                pass
            if clue is None:
                assert valid is None
                irc.reply(_('Nobody replied with (one of this) '
                            'answer(s): %r.') %
                          ', '.join([y for x, y in state.answers if x == 'r']),
                          prefixNick=False)
                self._ask(irc, channel)
            else:
                irc.reply(_('Another clue: %s') % clue, prefixNick=False)
                self._giveClue(irc, channel)

        eventName = 'Eureka-nextClue-%s' % channel
        if now and eventName in schedule.schedule.events:
            schedule.schedule.events[eventName]()
            schedule.removeEvent(eventName)
        schedule.addEvent(event, time.time() + delay, eventName)
Example #40
0
    def __init__(self, irc):
        self.__parent = super(Twitter, self)
        self.__parent.__init__(irc)
        self.irc = irc
        self.mentionSince = None
        try:
            schedule.removeEvent("Mentions")
        except KeyError:
            pass
        t_consumer_key = self.registryValue("consumer_key")
        t_consumer_secret = self.registryValue("consumer_secret")
        t_access_key = self.registryValue("access_key")
        t_access_secret = self.registryValue("access_secret")
        self.api = twitter.Api(
            consumer_key=t_consumer_key,
            consumer_secret=t_consumer_secret,
            access_token_key=t_access_key,
            access_token_secret=t_access_secret,
        )
        if self.registryValue("displayReplies"):
            statuses = self.api.GetMentions()
            self.mentionSince = statuses[0].id

            def mentionCaller():
                self._mention(irc)

            schedule.addPeriodicEvent(mentionCaller, 300, "Mentions")
Example #41
0
 def run_callback(callback, id_):
     ''' Run the callback 'now' on main thread. '''
     try:
         schedule.removeEvent(id_)
     except KeyError:
         pass
     schedule.addEvent(callback, time.time(), id_)
Example #42
0
 def die(self):
     for user in self._users:
         schedule.removeEvent(user)
     for search in self._searches:
         schedule.removeEvent(search)
     self._streams = []
     self._searches = []
Example #43
0
    def polloff(self, irc, msg, args, channel, pollid):
        """[<channel>] <id>
        Stops the poll with the given <id> from announcing. <channel> is
        only necessary if the message is not sent in the channel itself."""

        db = self.getDb(channel)
        cursor = db.cursor()

        # query to grab poll info, then check it exists, isnt already off, and warn them if it is closed
        pollinfo = self._poll_info(db, pollid)
        if pollinfo is None:
            irc.error('That poll id does not exist')
            return
        if pollinfo[0] == 0:
            irc.error('Poll is already off')
            return
        if pollinfo[1] is not None:
            irc.reply('Note: you are turning off a closed poll')

        # iquery to turn the poll "off", meaning it wont be scheduled to announce
        self._execute_query(cursor,
                            'UPDATE polls SET isAnnouncing=? WHERE id=?', 0,
                            pollid)
        db.commit()

        try:
            schedule.removeEvent('%s_poll_%s' % (channel, pollid))
            self.poll_schedules.remove('%s_poll_%s' % (channel, pollid))
        except:
            irc.error('Removing scedule failed')
            return

        irc.replySuccess()
Example #44
0
    def start(self, irc, msg, args, channel, num):
        """[<channel>] [<number of questions>]

        Starts a game of trivia.  <channel> is only necessary if the message
        isn't sent in the channel itself."""
        if num == None:
            num = self.registryValue('defaultRoundLength', channel)
        #elif num > 100:
        #    irc.reply('sorry, for now, you can\'t start games with more '
        #              'than 100 questions :(')
        #    num = 100
        channel = ircutils.toLower(channel)
        if channel in self.games:
            if not self.games[channel].active:
                del self.games[channel]
                try:
                    schedule.removeEvent('next_%s' % channel)
                except KeyError:
                    pass
                irc.reply('Orphaned trivia game found and removed.')
            else:
                self.games[channel].num += num
                self.games[channel].total += num
                irc.reply('%d questions added to active game!' % num)
        else:
            self.games[channel] = self.Game(irc, channel, num, self)
        irc.noReply()
Example #45
0
 def __init__(self, irc, channel, num, plugin):
     self.rng = random.Random()
     self.rng.seed()
     self.registryValue = plugin.registryValue
     self.irc = irc
     self.channel = channel
     self.num = num
     self.numAsked = 0
     self.hints = 0
     self.games = plugin.games
     self.scores = plugin.scores
     self.scorefile = plugin.scorefile
     self.questionfile = self.registryValue('questionFile')
     self.total = num
     self.active = True
     self.questions = []
     self.roundscores = {}
     self.unanswered = 0
     f = open(self.questionfile, 'r')
     line = f.readline()
     while line:
         self.questions.append(line.strip('\n\r'))
         line = f.readline()
     f.close()
     try:
         schedule.removeEvent('next_%s' % self.channel)
     except KeyError:
         pass
     self.newquestion()
Example #46
0
    def closepoll(self, irc, msg, args, channel, pollid):
        """[channel] <id>
        Closes the poll with the given <id>. Further votes will not be
        allowed. <channel> is only necessary if the message isn't sent in
        the channel itself."""

        db = self.getDb(channel)
        cursor = db.cursor()

        # query to check poll exists and if it is closed
        pollinfo = self._poll_info(db, pollid)
        if pollinfo is None:
            irc.error('Poll id doesnt exist')
            return
        if pollinfo[1] is not None:
            irc.error('Poll already closed on %s' % pollinfo[1].strftime('%Y-%m-%d at %-I:%M %p'))
            return

        # close the poll in db
        self._execute_query(cursor, 'UPDATE polls SET closed=? WHERE id=?', datetime.datetime.now(), pollid)
        db.commit()

        try:
            schedule.removeEvent('%s_poll_%s' % (channel, pollid))
            self.poll_schedules.remove('%s_poll_%s' % (channel, pollid))
        except:
            self.log.warning('Failed to remove schedule event')
            return

        irc.replySuccess()
Example #47
0
        def stop(self):
            self.reply('Trivia stopping.')
            self.active = False
            try:
                schedule.removeEvent('next_%s' % self.channel)
            except KeyError:
                pass
            scores = self.roundscores.iteritems()
            sorted = []
            for i in range(0, len(self.roundscores)):
                item = scores.next()
                sorted.append(item)

            def cmp(a, b):
                return b[1] - a[1]

            sorted.sort(cmp)
            max = 3
            if len(sorted) < max:
                max = len(sorted)
                #self.reply('max: %d.  len: %d' % (max, len(sorted)))
            s = 'Top finishers: '
            if max > 0:
                recipients = []
                maxp = sorted[0][1]
                for i in range(0, max):
                    item = sorted[i]
                    s = '%s %s %s.' % (s, item[0], item[1])
                self.reply(s)
            del self.games[self.channel]
Example #48
0
    def polloff(self, irc, msg, args, channel, pollid):
        """[<channel>] <id>
        Stops the poll with the given <id> from announcing. <channel> is
        only necessary if the message is not sent in the channel itself."""

        db = self.getDb(channel)
        cursor = db.cursor()

        # query to grab poll info, then check it exists, isnt already off, and warn them if it is closed
        pollinfo = self._poll_info(db, pollid)
        if pollinfo is None:
            irc.error('That poll id does not exist')
            return
        if pollinfo[0] == 0:
            irc.error('Poll is already off')
            return
        if pollinfo[1] is not None:
            irc.reply('Note: you are turning off a closed poll')

        # iquery to turn the poll "off", meaning it wont be scheduled to announce
        self._execute_query(cursor, 'UPDATE polls SET isAnnouncing=? WHERE id=?', 0, pollid)
        db.commit()

        try:
            schedule.removeEvent('%s_poll_%s' % (channel, pollid))
            self.poll_schedules.remove('%s_poll_%s' % (channel, pollid))
        except:
            irc.error('Removing scedule failed')
            return

        irc.replySuccess()
Example #49
0
 def cutwire(self, irc, cutWire):
     self.cutWire = cutWire
     self.responded = True
     if self.thrown == True:
         self.irc.queueMsg(
             ircmsgs.privmsg(
                 self.channel,
                 'You don\'t have the coordination to cut wires on bombs in midair while they\'re flying towards your head!  Ducking might be a better idea.'
             ))
     else:
         if self.goodWire.lower() == self.cutWire.lower():
             self.irc.queueMsg(
                 ircmsgs.privmsg(
                     self.channel,
                     '%s has cut the %s wire!  This has defused the bomb!'
                     % (self.victim, self.cutWire)))
             self.irc.queueMsg(
                 ircmsgs.privmsg(
                     self.channel,
                     'He then quickly rearms the bomb and throws it back at %s with just seconds on the clock!'
                     % self.sender))
             self.victim = self.sender
             self.thrown = True
             schedule.rescheduleEvent('%s_bomb' % self.channel,
                                      time.time() + 5)
             if self.victim == irc.nick:
                 time.sleep(1)
                 self.irc.queueMsg(
                     ircmsgs.privmsg(self.channel, '@duck'))
                 time.sleep(1)
                 self.duck(self.irc, irc.nick)
         else:
             schedule.removeEvent('%s_bomb' % self.channel)
             self.detonate(irc)
Example #50
0
 def doPrivmsg(self, irc, msg):
     channel = msg.args[0]
     nick = msg.prefix.split('!')[0]
     if channel not in self.states:
         return
     reply = None
     state = self.states[channel]
     for mode, answer in state.answers:
         if mode == 'r':
             if msg.args[1].lower() == answer.lower():
                 state.adjust(nick, state.question[0])
                 reply = _('Congratulations %s! The answer was %s.')
                 reply %= (nick, answer)
     if reply is not None:
         schedule.removeEvent('Eureka-nextClue-%s' % channel)
         otherAnswers = [y for x,y in state.answers
                 if x == 'r' and y.lower() != msg.args[1].lower()]
         if len(otherAnswers) == 1:
             reply += ' ' + _('Another valid answer is: \'%s\'.')
             reply %= otherAnswers[0]
         elif len(otherAnswers) >= 2:
             reply += ' ' + _('Other valid answers are: \'%s\'.')
             reply %= '\', \''.join([x for x in otherAnswers])
         irc.reply(reply, prefixNick=False)
         self._ask(irc, channel, True)
Example #51
0
 def cutwire(self, irc, cutWire):
     cutWire = cutWire.replace("pink", ircutils.mircColor('pink', '13'))
     cutWire = cutWire.replace("red", ircutils.mircColor('red', '4'))
     cutWire = cutWire.replace("orange", ircutils.mircColor('orange', '7'))
     cutWire = cutWire.replace("yellow", ircutils.mircColor('yellow', '8'))
     cutWire = cutWire.replace("green", ircutils.mircColor('green', '3'))
     cutWire = cutWire.replace("blue", ircutils.mircColor('blue', '12'))
     cutWire = cutWire.replace("grey", ircutils.mircColor('grey', '14'))
     cutWire = cutWire.replace("purple", ircutils.mircColor('purple', '6'))
     cutWire = cutWire.replace("lime", ircutils.mircColor('lime', '9'))
     cutWire = cutWire.replace("teal", ircutils.mircColor('teal', '10'))
     cutWire = cutWire.replace("brown", ircutils.mircColor('brown', '5'))
     cutWire = cutWire.replace("cyan", ircutils.mircColor('cyan', '11'))
     self.cutWire = cutWire
     self.responded = True
     if self.thrown == True:
         self.irc.queueMsg(ircmsgs.privmsg(self.channel, 'You don\'t have the coordination to cut wires on bombs in midair while they\'re flying towards your head!  Ducking might be a better idea.'))
     else:
         if self.goodWire.lower() == self.cutWire.lower():
             self.irc.queueMsg(ircmsgs.privmsg(self.channel, '%s has cut the %s wire!  This has defused the bomb!' % (self.victim, self.cutWire)))
             self.irc.queueMsg(ircmsgs.privmsg(self.channel, '%s then quickly rearms the bomb and throws it back at %s with just seconds on the clock!' % (self.victim, self.sender)))
             self.victim = self.sender
             self.thrown = True
             schedule.rescheduleEvent('%s_bomb' % self.channel, time.time() + 10)
             if self.victim == irc.nick:
                 time.sleep(1)
                 self.irc.queueMsg(ircmsgs.privmsg(self.channel, '@duck'))
                 time.sleep(1)
                 self.duck(self.irc, irc.nick)
         else:
             schedule.removeEvent('%s_bomb' % self.channel)
             self.detonate(irc)
Example #52
0
        def hint(self):
            if not self.active or self.correct:
                return
            try:
                schedule.removeEvent("event_%s" % self.channel)
            except:
                pass
            self.lastHint = self.currentHint
            if self.hints <= self.numHints and self.hints > 0 and self.numHints > 0:
                ans = self.a[0]
                self.show.setdefault(self.id, None)
                self.revealed.setdefault(self.id, None)
                hintPercentage = self.registryValue("hintPercentage",
                                                    self.channel)
                divider = round(self.divider * hintPercentage)
                self.divider -= divider
                if not self.show[self.id]:
                    self.show[self.id] = list(self.blank)
                if not self.revealed[self.id]:
                    self.revealed[self.id] = list(
                        range(len(self.show[self.id])))
                i = 0
                while i < divider and len(self.revealed[self.id]) > 1:
                    try:
                        rand = self.revealed[self.id].pop(
                            random.randint(0, len(self.revealed[self.id])) - 1)
                        if self.show[self.id][rand] == self.blankChar:
                            self.show[self.id][rand] = list(ans)[rand]
                            i += 1
                    except:
                        break
                self.currentHint = "".join(self.show[self.id])
            if self.hints > 0 and self.lastHint != self.currentHint:
                self.p -= int(round(self.p * self.reduction, -1))
            if self.points > self.p:
                points = self.p
            else:
                points = None
            if self.timeout > 0:
                timeLeft = str(round(self.endTime - time.time())).zfill(
                    len(str(self.timeout)))
                reply = self.hint_template.render(hint=self.currentHint,
                                                  time=timeLeft,
                                                  points=points)
                if self.showHints or self.showTime:

                    def event():
                        self.timedEvent()

                    eventTime = time.time() + self.waitTime
                    if eventTime < self.endTime:
                        schedule.addEvent(event, eventTime,
                                          "event_%s" % self.channel)
            else:
                reply = self.hint_template.render(hint=self.currentHint,
                                                  time=None,
                                                  points=points)
            self.reply(reply)
            self.hints += 1
Example #53
0
 def die(self):
     if hasattr(self, 'ltses'):
         del self.ltses
     try:
         schedule.removeEvent('checkmetadata')
         schedule.removeEvent('expiretorrents')
     except KeyError:
         pass
Example #54
0
    def setUp(self):
        # Avoid conflicts between tests.
        # We use .keys() in order to prevent this error:
        # RuntimeError: dictionary changed size during iteration
        for name in schedule.schedule.events.keys():
            schedule.removeEvent(name)
        self.prefix1 = '[email protected]'
        self.prefix2 = 'foo!bar@baz'
        self.prefix3 = 'toto!titi@tata'
        self.prefix4 = 'spam!egg@lol'
        path = conf.supybot.directories.data()
        self._path = os.path.join(os.path.abspath(path),
                'Eureka.%s.questions' % self.channel)
        ChannelPluginTestCase.setUp(self)
        with open(self._path, 'a') as fd:
            fd.write("""
            2 Who wrote this plugin?
            ---
            r ProgVal
            ---
            5 P***V**
            5 Pr**Va*
            2 Pro*Val
            === 5

            4 What is the name of this bot?
            ---
            r Limnoria
            r Supybot
            ---
            5 L******a
            2 Li****ia
            2 Lim**ria
            === 5

            3 Who is the original author of Supybot?
            ---
            r jemfinch
            ---
            1 j*******
            1 jem*****
            === 1

            1 Give a number.
            ---
            r 42
            m [0-9]+
            ---
            === 2

            1 Give another number.
            ---
            r 42
            m [0-9]+
            ---
            === 2
            """)
        self.prefix = self.prefix1 # Just to be sure
Example #55
0
    def setUp(self):
        # Avoid conflicts between tests.
        # We use .keys() in order to prevent this error:
        # RuntimeError: dictionary changed size during iteration
        for name in schedule.schedule.events.keys():
            schedule.removeEvent(name)
        self.prefix1 = '[email protected]'
        self.prefix2 = 'foo!bar@baz'
        self.prefix3 = 'toto!titi@tata'
        self.prefix4 = 'spam!egg@lol'
        path = conf.supybot.directories.data()
        self._path = os.path.join(os.path.abspath(path),
                'Eureka.%s.questions' % self.channel)
        ChannelPluginTestCase.setUp(self)
        with open(self._path, 'a') as fd:
            fd.write("""
            2 Who wrote this plugin?
            ---
            r ProgVal
            ---
            5 P***V**
            5 Pr**Va*
            2 Pro*Val
            === 5

            4 What is the name of this bot?
            ---
            r Limnoria
            r Supybot
            ---
            5 L******a
            2 Li****ia
            2 Lim**ria
            === 5

            3 Who is the original author of Supybot?
            ---
            r jemfinch
            ---
            1 j*******
            1 jem*****
            === 1

            1 Give a number.
            ---
            r 42
            m [0-9]+
            ---
            === 2

            1 Give another number.
            ---
            r 42
            m [0-9]+
            ---
            === 2
            """)
        self.prefix = self.prefix1 # Just to be sure
Example #56
0
        def cutwire(self, irc, cutWire):
            self.cutWire = cutWire
            self.responded = True
            specialWires = False

            if self.rng.randint(1, len(self.wires)) == 1:
                specialWires = True

            if self.cutWire.lower() == "potato" and specialWires:
                self.irc.queueMsg(
                    ircmsgs.privmsg(
                        self.channel,
                        "{} has turned the bomb into a potato! This has rendered it"
                        " mostly harmless, and slightly {}.".format(
                            self.victim, self.goodWire),
                    ))
                self.defuse()
            elif self.cutWire.lower() == "pizza" and specialWires:
                self.irc.queueMsg(
                    ircmsgs.privmsg(
                        self.channel,
                        "{} has turned the bomb into a pizza! Their pants have been"
                        " ruined by the pizza stuffed into them, but at least they"
                        " haven't exploded.".format(self.victim),
                    ))
                self.defuse()
            elif self.goodWire.lower() == self.cutWire.lower():
                self.irc.queueMsg(
                    ircmsgs.privmsg(
                        self.channel,
                        "{} has cut the {} wire! This has defused the bomb!".
                        format(self.victim, self.cutWire),
                    ))

                if self.victim.lower() != self.sender.lower():
                    self.irc.queueMsg(
                        ircmsgs.privmsg(
                            self.channel,
                            "{} quickly rearms the bomb and throws it back at {} with"
                            " just seconds on the clock!".format(
                                self.victim, self.sender),
                        ))
                    tmp = self.victim
                    self.victim = self.sender
                    self.sender = tmp
                    self.thrown = True
                    self.rethrown = True
                    schedule.rescheduleEvent("{}_bomb".format(self.channel),
                                             time.time() + 10)

                    if self.victim == irc.nick:
                        self.defuse()
                else:
                    self.defuse()
            else:
                schedule.removeEvent("{}_bomb".format(self.channel))
                self.detonate(irc)
Example #57
0
        def skip(self):
            self.reply(_("Question skipped. The answer was: %s") % self.a[0])

            self.unanswered = 0
            try:
                schedule.removeEvent('next_%s' % self.channel)
            except KeyError:
                pass
            self.newquestion()
Example #58
0
 def hintcommand(self):
     if self.hints >= self.registryValue('numHints', self.channel):
         self.reply(_("Sorry, you're out of hints for this question."))
     else:
         try:
             schedule.removeEvent('next_%s' % self.channel)
         except KeyError:
             pass
         self.hint()