Ejemplo n.º 1
0
def home():

    if request.method == "POST":
        # delete old votes
        all_txns = set([
            vote.split("-")[0] for vote in request.form
            if vote.split("-")[1] == "none"
        ])
        for txn in all_txns:
            deleteTradeVotes(txn, session.get("user_id"))
        # add votes
        for txn in request.form:
            transaction_id, roster_id = txn.split("-")
            if roster_id != "none":
                addTradeVote(transaction_id, session.get("user_id"),
                             int(roster_id))
        return redirect(url_for("home", _external=True))

    week = getTimeframe()["week"]
    teams = getTeams(True)
    return render_template(
        "home.html",
        matchups=getMatchups(week, teams),
        trades=getTrades(week + 1, teams),
        logged_in=session.get("user_id"),
    )
Ejemplo n.º 2
0
def getOwner(user, pw):
    """Verifies user is an owner in the league."""
    client = SleeperGraphQLClient()
    query = gql("""
        query getUserID ($user: String! $pw: String!) {
            login(email_or_phone_or_username: $user password: $pw) {
                avatar
                display_name
                real_name
                email
                phone
                user_id
            }
        }
        """)
    try:
        data = client.request(query, {"user": user, "pw": pw})
    except TransportQueryError:
        return None
    userID = data["login"]["user_id"]
    season = getTimeframe()["season"]
    leagues = requests.get(
        f"https://api.sleeper.app/v1/user/{userID}/leagues/nfl/{season}").json(
        )
    leagueIDs = [league["league_id"] for league in leagues]
    if os.getenv("LEAGUE_ID") in leagueIDs:
        db = getDB()
        db.users.update({"user_id": data["login"]["user_id"]},
                        data["login"],
                        upsert=True)
        return userID
    return None
Ejemplo n.º 3
0
def getMatchups(week=None, teams=None):
    """Gets matchups for current week."""
    leagueID = os.getenv("LEAGUE_ID")
    week = week or getTimeframe()["week"]
    teams = teams or getTeams(True)

    data = requests.get(
        f"https://api.sleeper.app/v1/league/{leagueID}/matchups/{week}").json(
        )

    # get all matchup IDs
    matchups = {
        str(matchupid): []
        for matchupid in set([matchup["matchup_id"] for matchup in data])
    }

    # add in team names and scores
    teamHash = {team["id"].split("|")[1]: team for team in teams}
    for matchup in data:
        matchups[str(matchup["matchup_id"])].append({
            "team":
            teamHash[str(matchup["roster_id"])],
            "score":
            round(matchup["points"], 2),
        })

    return matchups.values()
Ejemplo n.º 4
0
def _getCoachesPoll(teams):

    # get current week from Sportsdata API
    time = getTimeframe()

    # initialize dict of team rankings
    ranks = {team["id"]: [] for team in teams}

    db = getDB()
    votes = db.coaches_polls.find({
        "week": time["week"],
        "season": time["season"]
    })
    for vote in votes:
        for i, team in enumerate(vote["rankings"]):
            ranks[team].append(i + 1)

    teamsWithRank = [{
        "id": team["id"],
        "name": team["name"],
        "owner": team["owner"],
        "rank": floor(mean(ranks[team["id"]] or [1])),
        "topVotes": ranks[team["id"]].count(1),
    } for team in teams]

    return {
        "week": time["week"],
        "season": time["season"],
        "numVotes": votes.count(),
        "teams": sorted(teamsWithRank, key=lambda team: team["rank"]),
    }
Ejemplo n.º 5
0
def addCoachesPollVote(votes, userID):
    """Adds one vote to the database."""

    # votes should be in the form ["team|3", "team|4", "team|1", etc...]
    db = getDB()
    time = getTimeframe()
    db.coaches_polls.update(
        {
            "user_id": userID,
            "week": time["week"],
            "season": time["season"]
        },
        {
            "user_id": userID,
            "week": time["week"],
            "season": time["season"],
            "rankings": votes,
        },
        upsert=True,
    )
Ejemplo n.º 6
0
def getTrades(currentWeek=None, teams=None, n=5):
    """Gets recent transactions"""
    leagueID = os.getenv("LEAGUE_ID")
    currentWeek = currentWeek or getTimeframe()["week"]
    teams = teams or getTeams(True)
    db = getDB()

    # recursively search until I find 5 trades
    tradesData = []

    def findTrades(week):
        txns = requests.get(
            f"https://api.sleeper.app/v1/league/{leagueID}/transactions/{week}"
        ).json()

        # filter for only trades of two teams
        tradesData.extend([
            trade for trade in txns
            if trade["type"] == "trade" and len(trade["roster_ids"]) == 2
        ])
        if len(tradesData) < n:
            findTrades(week - 1)

    findTrades(currentWeek)
    tradesData = tradesData[:n]

    # get player info
    id_list_list = [trade["adds"].keys() for trade in tradesData]
    id_list = set([item for sublist in id_list_list for item in sublist])
    allPlayers = getPlayerData(db, id_list)

    trades = []

    def getTradeData(roster_id):
        players = [
            key for key in tradeData["adds"].keys()
            if tradeData["adds"][key] == roster_id
        ]
        picks = [
            pick for pick in tradeData["draft_picks"]
            if pick["owner_id"] == roster_id
        ]
        draftConvert = {1: "1st", 2: "2nd", 3: "3rd"}
        voteData = db.trade_votes.find({
            "transaction_id":
            tradeData["transaction_id"],
            "roster_id":
            roster_id,
        })
        voteUsers = [vote["user_id"] for vote in voteData]

        return {
            "team": [
                team for team in teams
                if team["id"].split("|")[1] == str(roster_id)
            ][0],
            "players": [allPlayers[player_id] for player_id in players],
            "picks": [{
                "season":
                pick["season"],
                "round":
                draftConvert[pick["round"]],
                "owner": [
                    team for team in teams
                    if team["id"].split("|")[1] == str(pick["roster_id"])
                ][0]["owner"],
            } for pick in picks],
            "votes":
            voteUsers,
        }

    for tradeData in tradesData:
        trade = {
            "transaction_id": tradeData["transaction_id"],
            "team1": getTradeData(tradeData["roster_ids"][0]),
            "team2": getTradeData(tradeData["roster_ids"][1]),
        }
        trades.append(trade)

    return trades