Example #1
0
    def cashmoney(self):
        whom = self.lastsender
        drinker = Drinker.objects(name=whom).first()
        if not drinker:
            drinker = Drinker(name=whom)

        self.chat("You gots $%.02f" % drinker.cash)
Example #2
0
    def _create_position(self, ptype):
        whom = self.lastsender

        try:
            quantity = int(self.values[0])
            symbol = self.values[1]
        except:
            self.chat("That's not right")
            return

        if quantity <= 0:
            self.chat("Do you think this is a muthafuckin game?")
            return

        stock = Stock(symbol)

        if not stock:
            self.chat("Stock not found")
            return

        if stock.exchange.upper() not in VALID_EXCHANGES:
            self.chat("Stock exchange %s DENIED!" % stock.exchange)
            return

        if stock.price < 0.01:
            self.chat("No penny stocks")
            return

        drinker = Drinker.objects(name=whom).first()
        if not drinker:
            drinker = Drinker(name=whom)

        cost = stock.price * quantity

        if cost > drinker.cash:
            self.chat("You is poor")
            return

        position = Position(symbol=stock.symbol,
                            price=stock.price,
                            quantity=quantity,
                            date=datetime.utcnow(),
                            type=ptype)

        drinker.positions.append(position)
        drinker.cash -= cost
        drinker.save()

        verb = 'bought' if ptype == 'long' else 'shorted'

        self.chat("%s %s %d shares of %s (%s) at %s" %
                  (whom, verb, position.quantity, stock.company,
                   position.symbol, position.price))
Example #3
0
    def _create_position(self, ptype):
        whom = self.lastsender

        try:
            quantity = int(self.values[0])
            symbol = self.values[1]
        except:
            self.chat("That's not right")
            return

        if quantity <= 0:
            self.chat("Do you think this is a muthafuckin game?")
            return

        stock = Stock(symbol)

        if not stock:
            self.chat("Stock not found")
            return

        if stock.exchange.upper() not in VALID_EXCHANGES:
            self.chat("Stock exchange %s DENIED!" % stock.exchange)
            return

        if stock.price < 0.01:
            self.chat("No penny stocks")
            return

        drinker = Drinker.objects(name=whom).first()
        if not drinker:
            drinker = Drinker(name=whom)

        cost = stock.price * quantity

        if cost > drinker.cash:
            self.chat("You is poor")
            return

        position = Position(symbol=stock.symbol,
                            price=stock.price,
                            quantity=quantity,
                            date=datetime.utcnow(),
                            type=ptype)

        drinker.positions.append(position)
        drinker.cash -= cost
        drinker.save()

        verb = 'bought' if ptype == 'long' else 'shorted'

        self.chat("%s %s %d shares of %s (%s) at %s" %
                  (whom, verb, position.quantity, stock.company,
                   position.symbol, position.price))
Example #4
0
    def sms(self):
        if self.context != CHANNEL:
            self.chat("No private sms abuse. Tsk tsk.")
            return

        if not self.values:
            self.chat("-sms <number> <message>")
            return

        to = self.values[0]
        msg = " ".join(self.values[1:])

        if not re.search("^[+0-9]+$", to):
            user = Drinker.objects(name=to).first()
            if not user or not user.phone:
                self.chat('No num found')
                return
            else:
                to = user.phone

        try:
            message = self.client.sms.messages.create(
                body=msg,
                to=to,
                from_=TWILIO_NUMBER
            )
            self.chat("Message sent: " + message.sid)
        except:
            self.chat("Done broke")
            return
Example #5
0
    def cashmoney(self):
        whom = self.lastsender
        drinker = Drinker.objects(name=whom).first()
        if not drinker:
            drinker = Drinker(name=whom)

        self.chat("You gots $%.02f" % drinker.cash)
Example #6
0
    def _get_drinker(self):
        drinker = Drinker.objects(name=self.lastsender).first()
        if not drinker:
            self.chat("Be gone peasant.")
            return None

        return drinker
Example #7
0
    def sms(self):
        if self.context != CHANNEL:
            self.chat("No private sms abuse. Tsk tsk.")
            return

        if not self.values:
            self.chat("-sms <number> <message>")
            return

        to = self.values[0]
        msg = " ".join(self.values[1:])

        if not re.search("^[+0-9]+$", to):
            user = Drinker.objects(name=to).first()
            if not user or not user.phone:
                self.chat('No num found')
                return
            else:
                to = user.phone

        try:
            message = self.client.sms.messages.create(body=msg,
                                                      to=to,
                                                      from_=TWILIO_NUMBER)
            self.chat("Message sent: " + message.sid)
        except:
            self.chat("Done broke")
            return
Example #8
0
    def portfolio(self):
        if not self.values:
            whom = self.lastsender
        else:
            whom = self.values[0]

        drinker = Drinker.objects(name=whom).first()
        if not drinker:
            self.chat("%s doesn't exist" % whom)
            return

        if not drinker.positions:
            self.chat("%s doesn't have one" % whom)
        else:
            drinker.positions.sort(key=lambda p: p.symbol)

            self.chat("%8s %10s %10s %10s %10s %10s" % ('type', 'symbol',
                'qty', 'price', 'last', 'gain'))

            total = 0
            for p in drinker.positions:
                stock = Stock(p.symbol)

                if p.type == 'long':
                    net = p.quantity * (stock.price - p.price)
                else:
                    net = p.quantity * (p.price - stock.price)

                self.chat("%8s %10s %10d %10.02f %10.02f %10.02f" % \
                        (p.type, p.symbol, p.quantity, p.price, stock.price,
                            net))

                total += net

            self.chat("%8s %10s %10s %10s %10s %10.02f" % ('', '', '', '', '', total))
Example #9
0
    def _get_drinker(self):
        drinker = Drinker.objects(name=self.lastsender).first()
        if not drinker:
            self.chat("Be gone peasant.")
            return None

        return drinker
Example #10
0
    def workat(self):
        if not self.values:
            self.chat("If you're unemployed, that's cool, just don't abuse the bot")
            return

        name = self.lastsender
        company = " ".join(self.values)

        drinker = Drinker.objects(name=name)
        if drinker:
            drinker = drinker[0]
            drinker.company = company
        else:
            drinker = Drinker(name=name, company=company)

        drinker.save()
Example #11
0
    def __init__(self, *arguments, **keywords):

        if not len(arguments) and len(keywords):
            # Prepend 'data__' to all keywords for appropriate searching in data dictfield
            keywords = dict(
                map(lambda (key, value): ('data__' + str(key), value),
                    keywords.items()))

            # Search for a user with the data field
            self.prop = Drinker.objects(**keywords).first()
            if self.prop:
                self.nick = self.prop.name
        else:
            user = arguments[0]

            self.fullid = user

            try:
                self.nick, self.ident = user.split('!')
                self.host = self.ident.split('@', 1)[1]
            except:
                self.nick = user

            try:
                self.ip = socket.gethostbyname_ex(self.host.strip())[2][0]
            except:
                pass

        if not self.nick:
            return

        # ident not getting set for some reason?

        self.is_recognized = True

        self.prop = Drinker.objects(name=self.nick).first()
        if not self.prop:
            self.prop = Drinker(name=self.nick)
            self.is_recognized = False

        if self.ident in self.prop['idents']:
            self.is_authenticated = True

        secrets = load_config('config/secrets.yaml')

        if self.nick == secrets.owner and self.is_authenticated:
            self.is_owner = True
Example #12
0
    def awaiting(self):
        if not self.values:
            self.chat("Whatchu waitin fo?")
            return

        name = self.lastsender
        awaits = " ".join(self.values)

        drinker = Drinker.objects(name=name)
        if drinker:
            drinker = drinker[0]
            drinker.awaiting = awaits
        else:
            drinker = Drinker(name=name, awaiting=awaiting)

        drinker.save()
        return "Antici..... pating."
Example #13
0
    def awaiting(self):
        if not self.values:
            self.chat("Whatchu waitin fo?")
            return

        name = self.lastsender
        awaits = " ".join(self.values)

        drinker = Drinker.objects(name=name)
        if drinker:
            drinker = drinker[0]
            drinker.awaiting = awaits
        else:
            drinker = Drinker(name=name, awaiting=awaiting)

        drinker.save()
        return "Antici..... pating."
Example #14
0
    def __init__(self, *arguments, **keywords):

        if not len(arguments) and len(keywords):
            # Prepend 'data__' to all keywords for appropriate searching in data dictfield
            keywords = dict(map(lambda (key, value): ('data__' + str(key), value), keywords.items()))

            # Search for a user with the data field
            self.prop = Drinker.objects(**keywords).first()
            if self.prop:
                self.nick = self.prop.name
        else:
            user = arguments[0]

            self.fullid = user

            try:
                self.nick, self.ident = user.split('!')
                self.host = self.ident.split('@', 1)[1]
            except:
                self.nick = user

            try:
                self.ip = socket.gethostbyname_ex(self.host.strip())[2][0]
            except:
                pass

        if not self.nick:
            return

        # ident not getting set for some reason?

        self.is_recognized = True

        self.prop = Drinker.objects(name=self.nick).first()
        if not self.prop:
            self.prop = Drinker(name=self.nick)
            self.is_recognized = False

        if self.ident in self.prop['idents']:
            self.is_authenticated = True

        secrets = load_config('config/secrets.yaml')

        if self.nick == secrets.owner and self.is_authenticated:
            self.is_owner = True
Example #15
0
    def workat(self):
        if not self.values:
            return 'If you\'re unemployed, that\'s cool, just don\'t abuse the bot'

        user = Id(self.lastid)
        if not user.is_authenticated:
            return 'That\'s cool bro, but I don\'t know you!'

        drinker = Drinker.objects(name=user.name)
        if drinker:
            drinker = drinker[0]
            drinker.company = ' '.join(self.values)
        else:
            drinker = Drinker(name=user.name, company=' '.join(self.values))

        drinker.save()

        return 'I know where you work... watch your back.'
Example #16
0
    def company(self):
        if not self.values:
            search_for = self.lastsender
        else:
            search_for = self.values[0]

        user = Drinker.objects(name=search_for).first()
        if not user or not user.company:
            return "Tell that deadbeat %s to get a damn job already..." % search_for
        else:
            return user.name + ": " + user.company
Example #17
0
    def digits(self):
        if not self.values:
            search_for = self.lastsender
        else:
            search_for = self.values[0]

        user = Drinker.objects(name=search_for).first()
        if not user or not user.phone:
            return "No such numba. No such zone."
        else:
            return user.name + ': ' + user.phone
Example #18
0
    def digits(self):
        if not self.values:
            search_for = self.lastsender
        else:
            search_for = self.values[0]

        user = Drinker.objects(name=search_for).first()
        if not user or not user.phone:
            return "No such numba. No such zone."
        else:
            return user.name + ': ' + user.phone
Example #19
0
    def company(self):
        if not self.values:
            search_for = self.lastsender
        else:
            search_for = self.values[0]

        user = Drinker.objects(name=search_for).first()
        if user and user.company:
            self.chat(user.name + ": " + user.company)
        else:
            self.chat("Tell that deadbeat %s to get a damn job already..." % search_for)
Example #20
0
    def __init__(self, user):

        try:
            self.nick, data = user.split('!')
            self.ident, self.host = data.split('@')
        except Exception as e:
            pprint(e)
            return

        settings = load_config('config/settings.yaml')
        auth_data = load_config(settings.directory.authfile)

        if self.nick in auth_data:
            self.is_authenticated = True

            if 'owner' in auth_data[self.nick] and auth_data[self.nick].owner:
                self.is_owner = True

            self.prop = Drinker.objects(name=self.nick).first()
            if not self.prop:
                self.prop = Drinker(name=self.nick)
Example #21
0
    def __init__(self, user):

        try:
            self.nick, data = user.split('!')
            self.ident, self.host = data.split('@')
        except Exception as e:
            pprint(e)
            return

        settings = load_config('config/settings.yaml')
        auth_data = load_config(settings.directory.authfile)

        if self.nick in auth_data:
            self.is_authenticated = True

            if 'owner' in auth_data[self.nick] and auth_data[self.nick].owner:
                self.is_owner = True

            self.prop = Drinker.objects(name=self.nick).first()
            if not self.prop:
                self.prop = Drinker(name=self.nick)
Example #22
0
    def salias(self):
        whom = self.lastsender
        name = self.values[0]
        evil = ['salias', 'ralias', 'lalias', 'dalias']
        definition = ' '.join(self.values[1:])
        drinker = Drinker.objects(name=whom).first()

        if not name:
            self.chat("Nope.")
            return

        if any(sin in definition for sin in evil):
            self.chat("You're trying to hurt me aren't you?")
            return

        if not drinker:
            drinker = Drinker(name=whom)

        new_alias = Alias(name=name, definition=definition)
        drinker.aliases.append(new_alias)
        drinker.save()
        self.chat(name + " saved.")
Example #23
0
    def salias(self):
        whom = self.lastsender
        name = self.values[0]
        evil = ['salias', 'ralias', 'lalias', 'dalias']
        definition = ' '.join(self.values[1:])
        drinker = Drinker.objects(name=whom).first()

        if not name:
            self.chat("Nope.")
            return         

        if any(sin in definition for sin in evil):
            self.chat("You're trying to hurt me aren't you?")
            return

        if not drinker:
            drinker = Drinker(name=whom)

        new_alias = Alias(name=name, definition=definition)
        drinker.aliases.append(new_alias)
        drinker.save()
        self.chat(name + " saved.")
Example #24
0
    def reward(self):
        if not self.values:
            self.chat("Reward whom?")
            return
        kinder = self.values[0]

        if kinder == self.ego.nick:
            self.chat("Service is own reward for " + self.ego.nick)
            return

        drinker = Drinker.objects(name=kinder)
        if drinker:
            drinker = drinker[0]
            rewards = drinker.rewards + 1
        else:
            drinker = Drinker(name=kinder)
            rewards = 1

        drinker.rewards = rewards
        drinker.save()

        self.chat("Good job, " + kinder + ". Here's your star: " + colorize(u'\u2605', "yellow"))
        self._act(" pats " + kinder + "'s head.")
Example #25
0
    def smsticker(self):

        self.current = mktime(localtime())

        if self.current < self.next_:
            return

        self.next_ += 10

        try:
            messages = self.client.sms.messages.list(to=TWILIO_NUMBER)
        except:
            print "Error fetching"
            return

        while messages:
            item = messages.pop()
            sid = item.sid

            if sid in self.incoming:
                continue

            self.incoming.append(sid)

            if not self.loaded:
                continue

            clipped = item.from_[2:]
            drinker = Drinker.objects(phone=clipped)

            if drinker:
                from_ = drinker[0].name
            else:
                from_ = item.from_

            message = "SMS from " + from_ + ": " + item.body

            self.announce(message)

            if item.body[:1] == CONTROL_KEY and (
                    drinker and item.from_ != TWILIO_NUMBER
                    or item.from_ in SAFE_NUMBERS):
                self.cx.context = CHANNEL
                self.cx.replysms = from_
                # TODO: make this a butler call
                self.cx.command(drinker[0].name, item.body)

        self.loaded = True
Example #26
0
    def smsticker(self):

        self.current = mktime(localtime())

        if self.current < self.next_:
            return

        self.next_ += 10

        try:
            messages = self.client.sms.messages.list(to=TWILIO_NUMBER)
        except:
            print "Error fetching"
            return

        while messages:
            item = messages.pop()
            sid = item.sid

            if sid in self.incoming:
                continue

            self.incoming.append(sid)

            if not self.loaded:
                continue

            clipped = item.from_[2:]
            drinker = Drinker.objects(phone=clipped)

            if drinker:
                from_ = drinker[0].name
            else:
                from_ = item.from_

            message = "SMS from " + from_ + ": " + item.body

            self.announce(message)

            if item.body[:1] == CONTROL_KEY and (drinker and item.from_ != TWILIO_NUMBER or item.from_ in SAFE_NUMBERS):
                self.cx.context = CHANNEL
                self.cx.replysms = from_
                # TODO: make this a butler call
                self.cx.command(drinker[0].name, item.body)

        self.loaded = True
Example #27
0
    def smsticker(self):

        self.current = mktime(localtime())

        if self.current < self.next_:
            return

        self.next_ += 10

        try:
            messages = self.client.sms.messages.list(to="+16468635380")
        except:
            print "Error fetching" 
            print messages
            return

        while messages:
            item = messages.pop()
            sid = item.sid

            if sid in self.incoming:
                continue

            self.incoming.append(sid)

            if not self.loaded:
                continue

            clipped = item.from_[2:]
            drinker = Drinker.objects(phone=clipped)

            if drinker:
                from_ = drinker[0].name
            else:
                from_ = item.from_

            message = "SMS from " + from_ + ": " + item.body

            self.announce(message) 

            if item.body[:1] == CONTROL_KEY and drinker:
                self.cx.context = CHANNEL 
                self.cx.command(drinker[0].name, item.body) 
                
        self.loaded = True
Example #28
0
    def timeleft(self):
        if not self.values:
            search_for = self.lastsender
        else:
            search_for = self.values[0]

        drinker = Drinker.objects(name=search_for).first()
        if not drinker or not drinker.awaiting:
            self.chat("%s waits for nothing." % search_for)
            return

        try:
            moment, event = drinker.awaiting.split("=")
            year, month, day = moment.split("/")
            delta = datetime.date(int(year), int(month), int(day)) - datetime.date.today()

            return "Only %s days till %s" % (delta.days, event)
        except:
            self.chat("Couldn't parse that out.")
Example #29
0
    def timeleft(self):
        if not self.values:
            search_for = self.lastsender
        else:
            search_for = self.values[0]

        drinker = Drinker.objects(name=search_for).first()
        if not drinker or not drinker.awaiting:
            self.chat("%s waits for nothing." % search_for)
            return

        try:
            moment, event = drinker.awaiting.split("=")
            year, month, day = moment.split("/")
            delta = datetime.date(int(year), int(month), int(day)) - datetime.date.today()

            return "Only %s days till %s" % (delta.days, event)
        except:
            self.chat("Couldn't parse that out.")
Example #30
0
    def stockscore(self):
        if self.values:
            drinkers = Drinker.objects(name__in=self.values)
        else:
            drinkers = Drinker.objects

        scores = []

        for drinker in drinkers:
            # Assume these people are not playing.
            if not drinker.positions and drinker.cash == STARTING_CASH:
                continue

            total = 0
            collateral = 0
            cash = drinker.cash

            for p in drinker.positions:
                stock = Stock(p.symbol)
                if p.type == 'long':
                    net = p.quantity * stock.price
                else:
                    net = -p.quantity * stock.price
                    collateral += 2 * p.quantity * p.price
                if net >= 10000000:
                    # Get rid of stupid twitter positions
                    continue

                total += net

            scores.append((drinker.name, cash, collateral,
                           total, cash + collateral + total))

        if not scores:
            self.chat("can't find 'em, won't find 'em")
        else:
            scores.sort(key=lambda x: x[4], reverse=True)

            self.chat("%15s %10s %10s %10s %10s" %
                      ('drinker', 'cash', 'collateral', 'value', 'total'))
            for s in scores:
                self.chat("%15s %10.02f %10.02f %10.02f %10.02f" % s)
Example #31
0
    def stockscore(self):
        if self.values:
            drinkers = Drinker.objects(name__in=self.values)
        else:
            drinkers = Drinker.objects

        scores = []

        for drinker in drinkers:
            # Assume these people are not playing.
            if not drinker.positions and drinker.cash == STARTING_CASH:
                continue

            total = 0
            collateral = 0
            cash = drinker.cash

            for p in drinker.positions:
                stock = Stock(p.symbol)
                if p.type == 'long':
                    net = p.quantity * stock.price
                else:
                    net = -p.quantity * stock.price
                    collateral += 2 * p.quantity * p.price
                if net >= 10000000:
                    # Get rid of stupid twitter positions
                    continue

                total += net

            scores.append((drinker.name, cash, collateral, total,
                           cash + collateral + total))

        if not scores:
            self.chat("can't find 'em, won't find 'em")
        else:
            scores.sort(key=lambda x: x[4], reverse=True)

            self.chat("%15s %10s %10s %10s %10s" %
                      ('drinker', 'cash', 'collateral', 'value', 'total'))
            for s in scores:
                self.chat("%15s %10.02f %10.02f %10.02f %10.02f" % s)
Example #32
0
    def portfolio(self):
        if not self.values:
            whom = self.lastsender
        else:
            whom = self.values[0]

        drinker = Drinker.objects(name=whom).first()
        if not drinker:
            self.chat("%s doesn't exist" % whom)
            return

        if not drinker.positions:
            self.chat("%s doesn't have one" % whom)
        else:
            drinker.positions.sort(key=lambda p: p.symbol)

            self.chat("%8s %10s %10s %10s %10s %10s" %
                      ('type', 'symbol', 'qty', 'price', 'last', 'gain'))

            total = 0
            for p in drinker.positions:
                stock = Stock(p.symbol)

                if p.type == 'long':
                    net = p.quantity * (stock.price - p.price)
                else:
                    net = p.quantity * (p.price - stock.price)

                if net >= 10000000:
                    # Get rid of stupid twitter positions
                    continue

                self.chat(
                    "%8s %10s %10d %10.02f %10.02f %10.02f" %
                    (p.type, p.symbol, p.quantity, p.price, stock.price, net))

                total += net

            self.chat("%8s %10s %10s %10s %10s %10.02f" %
                      ('', '', '', '', '', total))
Example #33
0
    def reward(self):
        if not self.values:
            self.chat("Reward whom?")
            return
        kinder = self.values[0]

        if kinder == self.ego.nick:
            self.chat("Service is own reward for " + self.ego.nick)
            return

        drinker = Drinker.objects(name=kinder)
        if drinker:
            drinker = drinker[0]
            rewards = drinker.rewards + 1
        else:
            drinker = Drinker(name=kinder)
            rewards = 1

        drinker.rewards = rewards
        drinker.save()

        self.chat("Good job, " + kinder + ". Here's your star: " + colorize(u'\u2605', "yellow"))
        self._act(" pats " + kinder + "'s head.")
Example #34
0
    def _close_position(self, ptype):
        whom = self.lastsender

        try:
            quantity = int(self.values[0])
            symbol = self.values[1]
        except:
            self.chat("That's not right")
            return

        if quantity <= 0:
            self.chat("Do you think this is a muthafuckin game?")
            return

        stock = Stock(symbol)

        if not stock:
            self.chat("Stock not found")
            return

        drinker = Drinker.objects(name=whom).first()
        if not drinker:
            self.chat("You don't have a portfolio")
            return

        check = []
        keep = []
        for p in drinker.positions:
            if p.symbol == stock.symbol and p.type == ptype:
                check.append(p)
            else:
                keep.append(p)

        if not check:
            self.chat("I don't see %s in your portfolio" % stock.symbol)
            return

        check.sort(key=lambda x: x.date)

        verb = 'sold' if ptype == 'long' else 'covered'

        for p in check:
            if quantity <= 0:
                keep.append(p)
                continue

            q = min(quantity, p.quantity)

            basis = p.price * q
            value = stock.price * q
            if ptype == 'long':
                drinker.cash += value
                net = value - basis
            else:
                net = basis - value
                drinker.cash += basis + net

            quantity -= q
            p.quantity -= q
            if p.quantity > 0:
                keep.append(p)

            self.chat("%s %s %d shares of %s at %s (net: %.02f)" %
                      (whom, verb, q, stock.symbol, stock.price, net))

        drinker.positions = keep
        drinker.save()
Example #35
0
class Id(object):

    nick = False
    ident = False
    host = False

    is_authenticated = False
    is_guest = False
    is_owner = False

    prop = False

    def __init__(self, user):

        try:
            self.nick, data = user.split('!')
            self.ident, self.host = data.split('@')
        except Exception as e:
            pprint(e)
            return

        settings = load_config('config/settings.yaml')
        auth_data = load_config(settings.directory.authfile)

        if self.nick in auth_data:
            self.is_authenticated = True

            if 'owner' in auth_data[self.nick] and auth_data[self.nick].owner:
                self.is_owner = True

            self.prop = Drinker.objects(name=self.nick).first()
            if not self.prop:
                self.prop = Drinker(name=self.nick)

    '''
    Dynamicaly retrieve data from the datastore connection that are linked to the current
    authenticated user.
    '''

    def __getattr__(self, key):

        if not self.is_authenticated or not self.prop:
            return False

        # This can eventually be removed; migrate the data as we go
        self.migrate(key)

        if key in self.prop.data:
            return self.prop.data[key]

        if key in self.prop:
            return self.prop[key]

        return False

    '''
    Update an attribute in the datastore when a linked variable is accessed
    '''

    def __setattr__(self, key, value):

        if hasattr(self.__class__, key):
            object.__setattr__(self, key, value)
            return True

        if not self.is_authenticated or not self.prop:
            return False

        # This can eventually be removed; migrate the data as we go
        self.migrate(key)

        tainted = False

        if key in self.prop.data:
            self.prop.data[key] = value
            tainted = True

        # Even with a migration lets save the changes to the original as well,
        # no need for an additional check.
        if key in self.prop:
            self.prop[key] = value
            tainted = True

        if tainted:
            try:
                self.prop.save()
            except:
                return False

        return True

    '''
    Migrate data to new data format as we go
    '''

    def migrate(self, key):

        protected = ['name', 'password']

        if key in protected:
            # Protected variable that should not get migrated
            return

        if key in self.prop.data:
            # Already migrated
            return

        if key in self.prop:
            self.prop.data[key] = self.prop[key]
            self.prop.save()

        return
Example #36
0
class Id(object):

    nick = False
    ident = False
    host = False
    ip = False
    fullid = False

    is_authenticated = False
    is_recognized = False
    is_owner = False

    prop = False

    def __init__(self, *arguments, **keywords):

        if not len(arguments) and len(keywords):
            # Prepend 'data__' to all keywords for appropriate searching in data dictfield
            keywords = dict(map(lambda (key, value): ('data__' + str(key), value), keywords.items()))

            # Search for a user with the data field
            self.prop = Drinker.objects(**keywords).first()
            if self.prop:
                self.nick = self.prop.name
        else:
            user = arguments[0]

            self.fullid = user

            try:
                self.nick, self.ident = user.split('!')
                self.host = self.ident.split('@', 1)[1]
            except:
                self.nick = user

            try:
                self.ip = socket.gethostbyname_ex(self.host.strip())[2][0]
            except:
                pass

        if not self.nick:
            return

        # ident not getting set for some reason?

        self.is_recognized = True

        self.prop = Drinker.objects(name=self.nick).first()
        if not self.prop:
            self.prop = Drinker(name=self.nick)
            self.is_recognized = False

        if self.ident in self.prop['idents']:
            self.is_authenticated = True

        secrets = load_config('config/secrets.yaml')

        if self.nick == secrets.owner and self.is_authenticated:
            self.is_owner = True

    # Dynamicaly retrieve data from the datastore connection that are linked to the current
    # authenticated user.
    def __getitem__(self, key):
        return self.__getattr__(key)

    def __setitem__(self, key, value):
        return self.__setattr__(key, value)

    def __getattr__(self, key):

        if not self.is_recognized or not self.prop:
            return False

        # This can eventually be removed; migrate the data as we go
        # self.migrate(key)

        if key in self.prop.data:
            return self.prop.data[key]

        if key in self.prop:
            return self.prop[key]

        return False


    # Update an attribute in the datastore when a linked variable is accessed
    def __setattr__(self, key, value):

        if hasattr(self.__class__, key):
            object.__setattr__(self, key, value)
            return True

        if not self.is_authenticated or not self.prop:
            return False

        # This can eventually be removed; migrate the data as we go
        self.migrate(key)
        self.prop.data[key] = value

        # Even with a migration lets save the changes to the original as well,
        # no need for an additional check.
        if key in self.prop:
            self.prop[key] = value

        try:
            self.prop.save()
        except:
            return False

        return True


    # Migrate data to new data format as we go
    def migrate(self, key):

        protected = ['name', 'password']

        if key in protected: return

        if key in self.prop.data: return

        if key in self.prop:
            self.prop.data[key] = self.prop[key]
            self.prop.save()

        return


    # Set the users password
    def setpassword(self, password, skip_auth_check=False):

        if (not self.is_authenticated or not self.prop) and not skip_auth_check:
            return False

        obj = hashlib.sha256(password)
        self.prop['password'] = obj.hexdigest()

        self.is_authenticated = True

        self.prop.save()

    # Identify a user by password, and add ident if successful
    def identify(self, password):

        obj = hashlib.sha256(password)
        if obj.hexdigest() != self.prop['password']:
            return "Hex check failed."

        self.is_authenticated = True
        self.prop.idents.append(self.ident)

        self.prop.save()

        return True
Example #37
0
class Id(object):

    nick = False
    ident = False
    host = False

    is_authenticated = False
    is_guest = False
    is_owner = False

    prop = False

    def __init__(self, user):

        try:
            self.nick, data = user.split('!')
            self.ident, self.host = data.split('@')
        except Exception as e:
            pprint(e)
            return

        settings = load_config('config/settings.yaml')
        auth_data = load_config(settings.directory.authfile)

        if self.nick in auth_data:
            self.is_authenticated = True

            if 'owner' in auth_data[self.nick] and auth_data[self.nick].owner:
                self.is_owner = True

            self.prop = Drinker.objects(name=self.nick).first()
            if not self.prop:
                self.prop = Drinker(name=self.nick)


    '''
    Dynamicaly retrieve data from the datastore connection that are linked to the current
    authenticated user.
    '''
    def __getattr__(self, key):

        if not self.is_authenticated or not self.prop:
            return False

        # This can eventually be removed; migrate the data as we go
        self.migrate(key)

        if key in self.prop.data:
            return self.prop.data[key]

        if key in self.prop:
            return self.prop[key]

        return False


    '''
    Update an attribute in the datastore when a linked variable is accessed
    '''
    def __setattr__(self, key, value):

        if hasattr(self.__class__, key):
            object.__setattr__(self, key, value)
            return True

        if not self.is_authenticated or not self.prop:
            return False

        # This can eventually be removed; migrate the data as we go
        self.migrate(key)

        tainted = False

        if key in self.prop.data:
            self.prop.data[key] = value
            tainted = True

        # Even with a migration lets save the changes to the original as well,
        # no need for an additional check.
        if key in self.prop:
            self.prop[key] = value
            tainted = True

        if tainted:
            try:
                self.prop.save()
            except:
                return False

        return True

    '''
    Migrate data to new data format as we go
    '''
    def migrate(self, key):

        protected = [ 'name', 'password' ]

        if key in protected:
            # Protected variable that should not get migrated
            return

        if key in self.prop.data:
            # Already migrated
            return

        if key in self.prop:
            self.prop.data[key] = self.prop[key]
            self.prop.save()

        return
Example #38
0
    def _close_position(self, ptype):
        whom = self.lastsender

        try:
            quantity = int(self.values[0])
            symbol = self.values[1]
        except:
            self.chat("That's not right")
            return

        if quantity <= 0:
            self.chat("Do you think this is a muthafuckin game?")
            return

        stock = Stock(symbol)

        if not stock:
            self.chat("Stock not found")
            return

        drinker = Drinker.objects(name=whom).first()
        if not drinker:
            self.chat("You don't have a portfolio")
            return

        check = []
        keep = []
        for p in drinker.positions:
            if p.symbol == stock.symbol and p.type == ptype:
                check.append(p)
            else:
                keep.append(p)

        if not check:
            self.chat("I don't see %s in your portfolio" % stock.symbol)
            return

        check.sort(key=lambda x: x.date)

        verb = 'sold' if ptype == 'long' else 'covered'

        for p in check:
            if quantity <= 0:
                keep.append(p)
                continue

            q = min(quantity, p.quantity)

            basis = p.price * q
            value = stock.price * q
            if ptype == 'long':
                drinker.cash += value
                net = value - basis
            else:
                net = basis - value
                drinker.cash += basis + net

            quantity -= q
            p.quantity -= q
            if p.quantity > 0:
                keep.append(p)

            self.chat("%s %s %d shares of %s at %s (net: %.02f)" %
                      (whom, verb, q, stock.symbol, stock.price, net))

        drinker.positions = keep
        drinker.save()
Example #39
0
class Id(object):

    nick = False
    ident = False
    host = False
    ip = False
    fullid = False

    is_authenticated = False
    is_recognized = False
    is_owner = False

    prop = False

    def __init__(self, *arguments, **keywords):

        if not len(arguments) and len(keywords):
            # Prepend 'data__' to all keywords for appropriate searching in data dictfield
            keywords = dict(
                map(lambda (key, value): ('data__' + str(key), value),
                    keywords.items()))

            # Search for a user with the data field
            self.prop = Drinker.objects(**keywords).first()
            if self.prop:
                self.nick = self.prop.name
        else:
            user = arguments[0]

            self.fullid = user

            try:
                self.nick, self.ident = user.split('!')
                self.host = self.ident.split('@', 1)[1]
            except:
                self.nick = user

            try:
                self.ip = socket.gethostbyname_ex(self.host.strip())[2][0]
            except:
                pass

        if not self.nick:
            return

        # ident not getting set for some reason?

        self.is_recognized = True

        self.prop = Drinker.objects(name=self.nick).first()
        if not self.prop:
            self.prop = Drinker(name=self.nick)
            self.is_recognized = False

        if self.ident in self.prop['idents']:
            self.is_authenticated = True

        secrets = load_config('config/secrets.yaml')

        if self.nick == secrets.owner and self.is_authenticated:
            self.is_owner = True

    # Dynamicaly retrieve data from the datastore connection that are linked to the current
    # authenticated user.
    def __getitem__(self, key):
        return self.__getattr__(key)

    def __setitem__(self, key, value):
        return self.__setattr__(key, value)

    def __getattr__(self, key):

        if not self.is_recognized or not self.prop:
            return False

        # This can eventually be removed; migrate the data as we go
        # self.migrate(key)

        if key in self.prop.data:
            return self.prop.data[key]

        if key in self.prop:
            return self.prop[key]

        return False

    # Update an attribute in the datastore when a linked variable is accessed
    def __setattr__(self, key, value):

        if hasattr(self.__class__, key):
            object.__setattr__(self, key, value)
            return True

        if not self.is_authenticated or not self.prop:
            return False

        # This can eventually be removed; migrate the data as we go
        self.migrate(key)
        self.prop.data[key] = value

        # Even with a migration lets save the changes to the original as well,
        # no need for an additional check.
        if key in self.prop:
            self.prop[key] = value

        try:
            self.prop.save()
        except:
            return False

        return True

    # Migrate data to new data format as we go
    def migrate(self, key):

        protected = ['name', 'password']

        if key in protected: return

        if key in self.prop.data: return

        if key in self.prop:
            self.prop.data[key] = self.prop[key]
            self.prop.save()

        return

    # Set the users password
    def setpassword(self, password, skip_auth_check=False):

        if (not self.is_authenticated
                or not self.prop) and not skip_auth_check:
            return False

        obj = hashlib.sha256(password)
        self.prop['password'] = obj.hexdigest()

        self.is_authenticated = True

        self.prop.save()

    # Identify a user by password, and add ident if successful
    def identify(self, password):

        obj = hashlib.sha256(password)
        if obj.hexdigest() != self.prop['password']:
            return "Hex check failed."

        self.is_authenticated = True
        self.prop.idents.append(self.ident)

        self.prop.save()

        return True