示例#1
0
def set_player_data(player_id=None, playername=None):
    """
    Sets prices and points for all the players of the user
    :param player_id: Id of the football player
    :param playername: Football player name
    :return: Players of the user id
    """
    days_left = days_wo_price(player_id)
    prices, points = list(), list()
    if days_left:
        dates, prices, points = get_player_data(player_id=player_id)
        if days_left >= 365:
            days_left = len(dates)

        if not db.rowcount('SELECT idp FROM players WHERE idp=%s' % player_id):
            playername, position, club_id, price = com.get_player_info(player_id)
            set_new_player(player_id, playername, position, club_id)

        db.many_commit_query('INSERT IGNORE INTO prices (idp,date,price) VALUES (%s' % player_id + ',%s,%s)',
                             zip(dates[:days_left], prices[:days_left]))
        for point in points:
            db.nocommit_query('INSERT INTO points (idp,gameday,points) VALUES (%s,%s,%s) \
                              ON DUPLICATE KEY UPDATE points=%s' % (player_id, point[0], point[1], point[1]))
        db.commit()
        if len(dates) != len(prices):
            print "%sThe prices arrays and dates haven't the same size.%s" % (RED, ENDC)

    return prices, points
示例#2
0
def main():
    parser = argparse.ArgumentParser(description='Helps you to play in Comunio.')

    parser.add_argument('-i', '--init', action='store_true', dest='init',
                        help='Initialize the database with users, clubs, players and transactions.')
    parser.add_argument('-u', '--update', action='store_true', dest='update',
                        help='Update all data of all players and users.')
    parser.add_argument('-b', '--buy', action='store_true', dest='buy',
                        help='Check all the players to buy.')
    parser.add_argument('-s', '--sell', action='store_true', dest='sell',
                        help='Players that you should sell.')
    parser.add_argument('-m', '--mail', action='store_true', dest='mail',
                        help='Send email with the results.')

    args = parser.parse_args()
    sleep(1)
    if not com.logged:
        print "Not logged in Comunio, existing."
        exit(0)

    # INIT
    if args.init:
        print '\n[*] Initializing the database.'
        if db.rowcount('SELECT * FROM users'):
            res = raw_input(
                '\tDatabase contains data, %sdo you want to remove%s it and load data again? (y/n) ' % (RED, ENDC))
            if res == 'y':
                db.commit_query('SET FOREIGN_KEY_CHECKS=0;')
                queries = db.simple_query('SELECT Concat("DELETE FROM ",table_schema,".",TABLE_NAME, " WHERE 1;") \
                    FROM INFORMATION_SCHEMA.TABLES WHERE table_schema in ("tradunio");')
                for query in queries:
                    print query[0],
                    db.commit_query(query[0])
                    print '%sdone%s.' % (GREEN, ENDC)
                db.commit_query('SET FOREIGN_KEY_CHECKS=1;')
            else:
                print "\tExecution aborted."
                exit(0)

        users = set_users_data()
        set_transactions()
        for user_id in users:
            username, points, teamvalue, money, maxbid = users[user_id]
            players = set_user_players(user_id, username)
            for player in players:
                player_id, playername, club_id, clubname, value, points, position = player
                set_player_data(player_id=player_id, playername=playername)

    # UPDATE
    if args.update:
        print '\n[*] Updating money, team value, save players, prices and transactions.'
        users = set_users_data()
        set_transactions()
        max_players_text = ''
        for user_id in users:
            username, userpoints, teamvalue, money, maxbid = users[user_id]
            players = set_user_players(user_id, username)
            for player in players:
                player_id, playername, club_id, clubname, value, points, position = player
                if club_id == 25:
                    # Player is not in Primera División
                    continue
                set_player_data(player_id=player_id, playername=playername)

            if user_id == com.get_myid():
                _ = [player.pop(0) for player in players]
                _ = [player.pop(1) for player in players]
                if args.mail:
                    if len(players) < max_players - 4:
                        num_players = '<font color="%s">%s</font>' % (GREEN_HTML, len(players))
                    elif len(players) < max_players - 2:
                        num_players = '<font color="%s">%s</font>' % (YELLOW_HTML, len(players))
                    else:
                        num_players = '<font color="%s">%s</font>' % (RED_HTML, len(players))

                    text = 'User: %s #Players: %s<br/>' % (username, num_players)
                    text += u'Teamvalue: %s € - Money: %s € - Max bid: %s € - Points: %s<br/>' % (
                        format(teamvalue, ",d"), format(money, ",d"), format(maxbid, ",d"), format(userpoints, ",d"))
                    text = text.encode('utf8')
                    headers = ['Name', 'Club', 'Value', 'Points', 'Position']
                    text += tabulate(players, headers, tablefmt="html", numalign="right", floatfmt=",.0f").encode(
                        'utf8')
                    send_email(fr_email, to_email, 'Tradunio update %s' % today, text)
                else:
                    print_user_data(username, teamvalue, money, maxbid, userpoints, players)

            if len(players) > max_players:
                max_players_text += 'User %s has reached the max players allowed with #%s<br/>'\
                                    % (username, len(players))

        if max_players_text:
            send_email(fr_email, admin_email, 'User max players reached %s' % today, max_players_text)

    # BUY
    if args.buy:
        print '\n[*] Checking players to buy in the market.'
        max_gameday = db.simple_query('SELECT MAX(gameday) from points')[0][0]
        players_on_sale = sorted(com.players_onsale(com.community_id, only_computer=False), key=itemgetter(2),
                                 reverse=True)
        gamedays = [('%3s' % gameday) for gameday in range(max_gameday - 4, max_gameday + 1)]
        bids = check_bids_offers(kind='bids')
        table = list()
        for player in players_on_sale:
            player_id, playername, team_id, team, min_price, market_price, points, dat, owner, position = player
            to_buy = colorize_boolean(check_buy(player_id, playername, min_price, market_price))
            last_points = db.simple_query(
                'SELECT p.gameday,p.points \
                FROM players pl INNER JOIN points p ON p.idp=pl.idp AND pl.idp = "%s" \
                ORDER BY p.gameday DESC LIMIT 5' % player_id)[::-1]

            if not last_points and not db.rowcount('SELECT idp FROM players WHERE idp = %s' % player_id):
                set_new_player(player_id, playername, position, team_id)
                _, last_points = set_player_data(player_id=player_id, playername=playername)
                last_points = last_points[-5:]
            elif not last_points:
                _, last_points = set_player_data(player_id=player_id, playername=playername)
                last_points = last_points[-5:]
            elif team_id == 25:
                continue

            streak = sum([int(x[1]) for x in last_points])
            last_points = {gameday: points for (gameday, points) in last_points}
            last_points_array = list()
            for gameday in range(max_gameday - 4, max_gameday + 1):
                points = last_points.get(gameday, 0)
                points = colorize_points(points)
                last_points_array.append(points)

            prices = db.simple_query(
                'SELECT p.date,p.price \
                FROM players pl INNER JOIN prices p ON p.idp=pl.idp AND pl.idp = "%s" \
                ORDER BY p.date ASC' % player_id)
            day, week, month = 0, 0, 0

            try:
                day = colorize_profit(calculate_profit(prices[-2][1], market_price))
                week = colorize_profit(calculate_profit(prices[-8][1], market_price))
                month = colorize_profit(calculate_profit(prices[-30][1], market_price))
            except IndexError:
                pass

            bid, extra_price = 0.0, colorize_profit(0.0)
            if player_id in bids:
                bid = bids[player_id][2]
                extra_price = colorize_profit(bids[player_id][3])

            table.append([playername, position, to_buy, owner, month, week, day,
                          market_price, min_price, bid, extra_price, ' '.join(last_points_array), streak])

        headers = ['Name', 'Position', 'To Buy?', 'Owner', 'Month ago', 'Week ago', 'Day ago',
                   'Mkt. price', 'Min. price', 'Bid', 'Extra', ' '.join(gamedays), 'Streak']
        table = sorted(table, key=itemgetter(12), reverse=True)

        if args.mail:
            text = tabulate(table, headers, tablefmt="html", numalign="right", floatfmt=",.0f").encode('utf8')
            send_email(fr_email, to_email, 'Tradunio players to buy %s' % today, text)
        else:
            print tabulate(table, headers, tablefmt="psql", numalign="right", floatfmt=",.0f")

    # SELL
    if args.sell:
        print '\n[*] Checking players to sell.'
        max_gameday = db.simple_query('SELECT MAX(gameday) from points')[0][0]
        gamedays = [('%3s' % gameday) for gameday in range(max_gameday - 4, max_gameday + 1)]
        console, table = list(), list()
        players = get_user_players(user_id=com.myid)
        offers = check_bids_offers(kind='offers')
        for player in players:
            player_id, playername, club_id, club_name, position = player
            bought_date, bought_price, market_price, to_sell, profit = check_sell(player_id)

            last_points = db.simple_query(
                'SELECT p.gameday,p.points \
                FROM players pl INNER JOIN points p ON p.idp=pl.idp AND pl.idp = "%s" \
                ORDER BY p.gameday DESC LIMIT 5' % player_id)[::-1]

            if not last_points and not db.rowcount('SELECT idp FROM players WHERE idp = %s' % player_id):
                set_new_player(player_id, playername, position, club_id)
                _, last_points = set_player_data(player_id=player_id, playername=playername)
                last_points = last_points[-5:]
            elif not last_points:
                _, last_points = set_player_data(player_id=player_id, playername=playername)
                last_points = last_points[-5:]

            streak = sum([int(x[1]) for x in last_points])
            last_points = {gameday: points for (gameday, points) in last_points}
            last_points_array = list()
            for gameday in range(max_gameday - 4, max_gameday + 1):
                points = last_points.get(gameday, 0)
                points = colorize_points(points)
                last_points_array.append(points)

            prices = db.simple_query(
                'SELECT p.date,p.price \
                FROM players pl INNER JOIN prices p ON p.idp=pl.idp AND pl.idp = "%s" \
                ORDER BY p.date ASC' % player_id)
            day, week, month = 0, 0, 0

            try:
                day = colorize_profit(calculate_profit(prices[-2][1], market_price))
                week = colorize_profit(calculate_profit(prices[-8][1], market_price))
                month = colorize_profit(calculate_profit(prices[-30][1], market_price))
            except IndexError:
                pass

            to_sell = colorize_boolean(to_sell)
            profit_color = colorize_profit(profit)

            offer, extra_price, who = 0.0, colorize_profit(0.0), '-'
            if player_id in offers:
                who = offers[player_id][1]
                offer = offers[player_id][2]
                extra_price = colorize_profit(offers[player_id][3])

            table.append(
                [playername, position, to_sell, bought_date, month, week, day, ' '.join(last_points_array),
                 streak, bought_price, market_price, profit_color, offer, who, extra_price])

        table = sorted(table, key=itemgetter(8), reverse=True)
        headers = ['Name', 'Position', 'To sell?', 'Purchase date', 'Month ago', 'Week ago', 'Day ago',
                   ' '.join(gamedays), 'Streak', 'Purchase price', 'Mkt price', 'Profit', 'Offer', 'Who', 'Profit']
        if args.mail:
            text = tabulate(table, headers, tablefmt="html", numalign="right", floatfmt=",.0f").encode('utf8')
            send_email(fr_email, to_email, 'Tradunio players to sell %s' % today, text)
        else:
            print tabulate(table, headers, tablefmt="psql", numalign="right", floatfmt=",.0f")

    com.logout()
    db.close_connection()