Пример #1
0
    def check(self, cardinal, user, channel, msg):
        """Check a specific stock for current value and daily change"""
        nick = user.nick

        match = re.match(CHECK_REGEX, msg)
        if match.group(1):
            # this group should only be present when a relay bot is relaying a
            # message for another user
            if not self.is_relay_bot(user):
                return

            nick = util.strip_formatting(match.group(1))

        symbol = match.group(2).upper()
        try:
            data = yield self.get_daily(symbol)
        except Exception as exc:
            self.logger.warning("Error trying to look up symbol {}: {}".format(
                symbol, exc))
            cardinal.sendMsg(channel,
                             "{}: I couldn't look that symbol up".format(nick))
            return

        cardinal.sendMsg(
            channel,
            "Symbol: \x02{}\x02 | Current: {} | Daily Change: {}".format(
                symbol, data['close'], colorize(data['change'])))
Пример #2
0
    def predict_relayed(self, cardinal, user, channel, msg):
        """Hack to support relayed messages"""
        match = re.match(PREDICT_RELAY_REGEX, msg)

        # this regex should only match when a relay bot is relaying a message
        # for another user - make sure this is really a relay bot
        if not self.is_relay_bot(user):
            return

        user = user_info(util.strip_formatting(match.group(1)),
                         user.user,
                         user.vhost,
                         )

        yield self.predict(cardinal, user, channel, match.group(2))
Пример #3
0
    def sendMsg(self, channel, message, length=None):
        """Wrapper command to send messages.

        Keyword arguments:
          channel -- Channel to send message to.
          message -- Message to send.
          length -- Length of message. Twisted will calculate if None given.
        """
        try:
            if not self.channels[channel].allows_color():
                message = strip_formatting(message)
        except KeyError:
            pass

        self.logger.info("Sending in %s: %s" % (channel, message))

        self.msg(channel, message, length)
Пример #4
0
    def parse_prediction(self, user, message):
        match = re.match(PREDICT_REGEX, message)

        # Fix nick if relay bot sent the message
        nick = user.nick
        if match.group(1):
            if not self.is_relay_bot(user):
                return None

            nick = util.strip_formatting(match.group(1))

        # Convert symbol to uppercase
        symbol = match.group(2).upper()

        data = yield self.get_daily(symbol)
        if market_is_open():
            # get value at previous close
            base = data['previous close']
        else:
            # get latest price
            base = data['price']

        negative_percentage = match.group(3) == '-'
        percentage = float(match.group(4)) if match.group(4) else None
        price = float(match.group(5)) if match.group(5) else None

        if percentage:
            prediction = percentage * .01 * base
            if negative_percentage:
                prediction = base - prediction
            else:
                prediction = base + prediction
        elif price:
            prediction = price
        else:
            # this shouldn't happen
            self.logger.warning("No price or percentage: {}".format(message))
            return None

        return (
            nick,
            symbol,
            prediction,
            base,
        )
Пример #5
0
    def parse_prediction(self, user, message):
        match = re.match(PREDICT_REGEX, message)

        # Fix nick if relay bot sent the message
        nick = user.nick
        if match.group(1):
            if not self.is_relay_bot(user):
                defer.returnValue(None)

            nick = util.strip_formatting(match.group(1))

        # Convert symbol to uppercase
        symbol = match.group(2).upper()

        data = yield self.get_daily(symbol)
        if market_is_open():
            # get value at previous close
            base = data['previous close']
        else:
            # get value at close
            base = data['close']

        prediction = float(match.group(4))
        negative = match.group(3) == '-'

        prediction = prediction * .01 * base
        if negative:
            prediction = base - prediction
        else:
            prediction = base + prediction

        defer.returnValue((
            nick,
            symbol,
            prediction,
            base,
        ))
Пример #6
0
    def format_seen(self, nick):
        with self.db() as db:
            if nick.lower() not in db['users']:
                return "Sorry, I haven't seen {}.".format(nick)

            entry = db['users'][nick.lower()]

        dt_timestamp = datetime.fromtimestamp(
            entry['timestamp'],
            tz=timezone.utc,
        )
        t_seen = dt_timestamp.strftime("%Y-%m-%d %H:%M:%S")
        t_ago = self._pretty_seconds(
            (datetime.now(tz=timezone.utc).replace(microsecond=0) -
             dt_timestamp).total_seconds())

        message = "I last saw {} {} ago ({}). ".format(nick, t_ago, t_seen)

        action, params = entry['action'], entry['params']
        if action == PRIVMSG:
            last_msg = params[1]
            if is_action(last_msg):
                last_msg = parse_action(nick, last_msg)

            message += "{} sent \"{}\" to {}.".format(
                nick,
                strip_formatting(last_msg),
                params[0],
            )
        elif action == NOTICE:
            message += "{} sent notice \"{}\" to {}.".format(
                nick,
                strip_formatting(params[1]),
                params[0],
            )
        elif action == JOIN:
            message += "{} joined {}.".format(nick, params[0])
        elif action == PART:
            message += "{} left {}{}.".format(
                nick,
                params[0],
                (" ({})".format(strip_formatting(params[1]))
                 if params[1] else ""),
            )
        elif action == NICK:
            message += "{} renamed themselves {}.".format(nick, params[0])
        elif action == MODE:
            message += "{} set mode {} on channel {}.".format(
                nick,
                params[1],
                params[0],
            )
        elif action == TOPIC:
            message += "{} set {}'s topic to \"{}\".".format(
                nick,
                params[0],
                strip_formatting(params[1]),
            )
        elif action == QUIT:
            message += "{} quit{}.".format(
                nick,
                (" ({})".format(strip_formatting(params[0]))
                 if params[0] else ""),
            )

        return message
Пример #7
0
def test_strip_formatting(input_, expected):
    assert util.strip_formatting(input_) == expected