Skip to content

Commit

Permalink
requested amendments
Browse files Browse the repository at this point in the history
  • Loading branch information
johnmadden86 committed Oct 21, 2019
1 parent 9942d93 commit d24917e
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 44 deletions.
9 changes: 4 additions & 5 deletions fpl/fpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,9 +297,9 @@ async def get_players(self, player_ids=None, include_summary=False, include_live
players = await asyncio.gather(*tasks)

if return_json:
return list(filter(lambda p: p["id"] in player_ids, players))
return [player for player in players if player["id"] in player_ids]

return {player.id: player for player in players}
return {player.id: player for player in players if player.id in player_ids}

async def get_fixture(self, fixture_id, return_json=False):
"""Returns the fixture with the given ``fixture_id``.
Expand Down Expand Up @@ -463,7 +463,7 @@ async def get_gameweek(self, gameweek_id, include_live=False, return_json=False)
# include live bonus points
if not static_gameweek['finished']:
fixtures = await self.get_fixtures_by_gameweek(gameweek_id)
fixtures_not_finished = filter(lambda f: not f.finished, fixtures.values())
fixtures_not_finished = [fixture for fixture in fixtures.values() if not fixture.finished]
bonus_for_gameweek = []
for fixture in fixtures_not_finished:
bonus = fixture.get_bonus(provisional=True)
Expand All @@ -475,8 +475,7 @@ async def get_gameweek(self, gameweek_id, include_live=False, return_json=False)
live_gameweek["elements"][player_id]["stats"]["total_points"] += bonus_points

# mark players that did not play
fixtures_started = filter(lambda f: f.started, fixtures.values())
fixtures_started = list(map(lambda f: f.id, fixtures_started))
fixtures_started = [fixture.id for fixture in fixtures.values() if fixture.started]
for element in live_gameweek["elements"].values():
player_id = element["id"]
no_minutes = element["stats"]["minutes"] == 0
Expand Down
73 changes: 38 additions & 35 deletions fpl/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def _set_captain(lineup, captain, captain_type, player_ids):


def _valid_formation(players):
positions = list(map(lambda x: x.element_type, players))
positions = [player.element_type for player in players]
g = positions.count(1)
d = positions.count(2)
m = positions.count(3)
Expand All @@ -115,6 +115,14 @@ def _valid_formation(players):
])


def _get_first_xi(picks, players):
return [players[pick["element"]].id for pick in picks if pick["position"] <= 11]


def _get_subs(picks, players):
return [players[pick["element"]].id for pick in picks if pick["position"] > 11]


class User:
"""A class representing a user of the Fantasy Premier League.
# >>> from fpl import FPL
Expand Down Expand Up @@ -234,13 +242,10 @@ async def get_formation(self, players):
"""
picks = await self.picks_for_current_gameweek
picks = picks["picks"]
first_xi = filter(lambda x: x['position'] <= 11, picks) # get starting 11
first_xi_ids = map(lambda x: x['element'], first_xi) # get ids of starting 11
# get positions of starting 11
first_xi_element_types = list(map(lambda x: getattr(players[x], "element_type"), first_xi_ids))
d = first_xi_element_types.count(2)
m = first_xi_element_types.count(3)
f = first_xi_element_types.count(4)
first_xi = [players[player_id].element_type for player_id in _get_first_xi(picks, players)]
d = first_xi.count(2)
m = first_xi.count(3)
f = first_xi.count(4)
return f"{d}-{m}-{f}"

async def get_live_score(self, players):
Expand All @@ -255,46 +260,44 @@ async def get_live_score(self, players):
points_hit = picks["entry_history"]["event_transfers_cost"]
picks = picks["picks"]

first_xi = filter(lambda x: x['position'] <= 11, picks)
first_xi = map(lambda x: x['element'], first_xi)
first_xi = set(first_xi)
subs = filter(lambda x: x['position'] > 11, picks)
subs = map(lambda x: x['element'], subs)
subs = list(subs)
subs_out = filter(lambda x: players[x].did_not_play, first_xi)
subs_out = map(lambda x: players[x].id, subs_out)
subs_out = list(subs_out)

# noinspection SpellCheckingInspection
if active_chip == "bboost":
first_xi = set(_get_first_xi(picks, players))
subs = _get_subs(picks, players)
subs_out = [player_id for player_id in first_xi if players[player_id].did_not_play]

if active_chip == "bboost": # count scores for all 15 players if bench boost chip is active
first_xi.update(subs)
else:
# perform auto-subs if applicable
for sub_out in subs_out:
i = 0
first_xi.remove(sub_out)
first_xi.add(subs[0])
valid_formation = _valid_formation(map(lambda x: players[x], first_xi))
first_xi.remove(sub_out) # remove first sub out
first_xi.add(subs[0]) # add first sub in
valid_formation = _valid_formation([players[player_id] for player_id in first_xi])
# check formation is valid
# if formation not valid, move on to the next sub
while not valid_formation and i <= 3:
i += 1
first_xi.remove(subs[i - 1])
first_xi.add(subs[i])
valid_formation = _valid_formation(map(lambda x: players[x], first_xi))
subs.pop(i)
first_xi.remove(subs[i - 1]) # remove previous player subbed in
first_xi.add(subs[i]) # add next sub in
# check formation
valid_formation = _valid_formation([players[player_id] for player_id in first_xi])
subs.pop(i) # when complete, remove the subbed in player from the list of subs

first_xi_live_scores = map(lambda x: getattr(players[x], "live_score"), first_xi)
first_xi_live_scores = [players[player_id].live_score for player_id in first_xi]

captain = next(pick["element"] for pick in picks if pick["is_captain"])
try:
vice_captain = next(
pick["element"] for pick in picks if pick["is_vice_captain"] and pick["multiplier"] == 1)
# only if multiplier == 1, i.e. vice-captain not already applied by FPL
except StopIteration:
vice_captain = None

captain_points = getattr(players[captain], "live_score")
captain_points = players[captain].live_score
if captain in subs_out and vice_captain:
captain_points = getattr(players[vice_captain], "live_score")
captain_points = players[vice_captain].live_score

if active_chip == "3xc":
if active_chip == "3xc": # for triple captain chip
captain_points *= 2

return sum(first_xi_live_scores) + captain_points - points_hit
Expand All @@ -307,8 +310,8 @@ async def get_live_total_points(self, players):
:rtype int
"""
history = await self.get_gameweek_history()
history = filter(lambda x: x["event"] < getattr(self, "current_event"), history)
history = map(lambda x: x["total_points"] - x["event_transfers cost"], history)
history = [x["total_points"] - x["event_transfers cost"] for x in history
if x["event"] < getattr(self, "current_event")]

live_score = + await self.get_live_score(players)

Expand Down Expand Up @@ -388,7 +391,7 @@ async def transfers_for_current_gameweek(self):
current_gameweek = getattr(self, "current_event")
picks = await self.picks_for_current_gameweek
transfers = await self.transfers
transfers = list(filter(lambda x: x["event"] == current_gameweek, transfers))
transfers = [transfer for transfer in transfers if transfer["event"] == current_gameweek]
return {
"transfers_made": picks["entry_history"]["event_transfers"],
"transfers_cost": picks["entry_history"]["event_transfers_cost"],
Expand Down Expand Up @@ -442,7 +445,7 @@ async def get_wildcards(self):
:rtype: list
"""
chips_played = await self.get_chips_history()
return list(filter(lambda x: x["name"] == "wildcard", chips_played))
return [chip for chip in chips_played if chip["name"] == "wildcard"]

async def get_watchlist(self):
"""Returns the user's watchlist. Requires the user to have logged in
Expand Down
12 changes: 8 additions & 4 deletions fpl/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,21 @@
headers = {"User-Agent": "https://github.com/amosbastian/fpl"}


async def fetch(session, url):
async def fetch(session, url, params=None):
if params is None:
params = {}
while True:
# noinspection PyBroadException
try:
async with session.get(url, headers=headers) as response:
async with session.get(url, headers=headers, params=params) as response:
assert response.status == 200
return await response.json()
except Exception:
pass


async def post(session, url, payload, headers):
async with session.post(url, data=payload, headers=headers) as response:
async def post(session, url, payload, headers_):
async with session.post(url, data=payload, headers=headers_) as response:
return await response.json()


Expand Down Expand Up @@ -151,6 +154,7 @@ def logged_in(session):
:return: True if user is logged in else False
:rtype: bool
"""
# noinspection PyTypeChecker
return "csrftoken" in session.cookie_jar.filter_cookies(
"https://users.premierleague.com/")

Expand Down

0 comments on commit d24917e

Please sign in to comment.