Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Some fixes #17

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: detect-private-key
- id: check-toml
- id: end-of-file-fixer
- id: trailing-whitespace
- id: mixed-line-ending
- repo: https://github.com/asottile/add-trailing-comma
rev: v3.0.1
hooks:
- id: add-trailing-comma
- repo: https://github.com/asottile/pyupgrade
rev: v3.10.1
hooks:
- id: pyupgrade
args: [--py310-plus]
- repo: https://github.com/psf/black
rev: 23.7.0
hooks:
- id: black
language_version: python3.10
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
args: ["--profile", "black", "--filter-files"]
242 changes: 136 additions & 106 deletions playersPickedInLeague.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import requests
import argparse # noqa 401
import csv
import json
import unicodecsv as csv
import argparse
from tqdm import tqdm
import logging, sys
import logging
import os
import sys

import requests
from tqdm import tqdm

FPL_URL = "https://fantasy.premierleague.com/api/"
LOGIN_URL = "https://users.premierleague.com/accounts/login/"
Expand All @@ -14,62 +16,70 @@
TEAM_ENTRY_SUBURL = "entry/"
PLAYERS_INFO_SUBURL = "bootstrap-static/"
PLAYERS_INFO_FILENAME = "output/allPlayersInfo.json"
USERNAME = '[email protected]'
PASSWORD = 'FPLshow#123'

USER_SUMMARY_URL = FPL_URL + USER_SUMMARY_SUBURL
PLAYERS_INFO_URL = FPL_URL + PLAYERS_INFO_SUBURL
START_PAGE = 1

payload = {
'login':USERNAME,
'password':PASSWORD,
'redirect_uri': 'https://fantasy.premierleague.com/',
'app':'plfpl-web'
PAYLOAD = {
"login": os.environ.get("USERNAME", "[email protected]"),
"password": os.environ.get("PASSWORD", "FPLshow#123"),
"redirect_uri": "https://fantasy.premierleague.com/",
"app": "plfpl-web",
}
s = requests.session()
s.post(LOGIN_URL, data=payload)
session = requests.session()
session.post(LOGIN_URL, data=PAYLOAD)


# Download all player data: https://fantasy.premierleague.com/api/bootstrap-static
def getPlayersInfo():
r = s.get(PLAYERS_INFO_URL)
jsonResponse = r.json()
with open(PLAYERS_INFO_FILENAME, 'w') as outfile:
json.dump(jsonResponse, outfile)
# Download all player data: https://fantasy.premierleague.com/api/bootstrap-static
result = session.get(PLAYERS_INFO_URL)
with open(PLAYERS_INFO_FILENAME, "w") as outfile:
json.dump(result.json(), outfile)


# Get users in league:
# https://fantasy.premierleague.com/api/leagues-classic/43919/standings/?page_new_entries=1&page_standings=2&phase=1
def getUserEntryIds(league_id, ls_page, league_Standing_Url):
def getUserEntryIds(league_id, page_count, league_standing_url):
# Get users in league:
# https://fantasy.premierleague.com/api/leagues-classic/43919/standings/?page_new_entries=1&page_standings=2&phase=1
entries = []
while(True):
league_url = league_Standing_Url + str(league_id) + "/standings/" + "?page_new_entries=1&page_standings=" + str(ls_page) + "&phase=1"
r = s.get(league_url)
jsonResponse = r.json()
managers = jsonResponse["standings"]["results"]
while True:
league_url = (
league_standing_url
+ str(league_id)
+ "/standings/"
+ "?page_new_entries=1&page_standings="
+ str(page_count)
+ "&phase=1"
)
result = session.get(league_url)
managers = result.json()["standings"]["results"]
if not managers:
print "Total managers :",len(entries)
print("Total managers :", len(entries))
break

for player in managers:
entries.append(player["entry"])
ls_page+=1

page_count += 1

return entries


# team picked by user. example: https://fantasy.premierleague.com/api/entry/2677936/event/1/picks with 2677936 being entry_id of the player
def getplayersPickedForEntryId(entry_id, GWNumber):
# team picked by user. example: https://fantasy.premierleague.com/api/entry/2677936/event/1/picks with 2677936 being entry_id of the player # noqa 501
eventSubUrl = "event/" + str(GWNumber) + "/picks/"
playerTeamUrlForSpecificGW = FPL_URL + TEAM_ENTRY_SUBURL + str(entry_id) + "/" + eventSubUrl
r = s.get(playerTeamUrlForSpecificGW)
jsonResponse = r.json()
playerTeamUrlForSpecificGW = (
FPL_URL + TEAM_ENTRY_SUBURL + str(entry_id) + "/" + eventSubUrl
)

result = session.get(playerTeamUrlForSpecificGW).json()
try:
picks = jsonResponse["picks"]
except:
if jsonResponse["detail"]:
print "entry_id "+str(entry_id)+" doesn't have info for this gameweek"
picks = result["picks"]
except Exception as e:
if result["detail"]:
print("entry_id " + str(entry_id) + " doesn't have info for this gameweek")
return None, None

elements = []
captainId = 1
for pick in picks:
Expand All @@ -79,83 +89,103 @@ def getplayersPickedForEntryId(entry_id, GWNumber):

return elements, captainId

# read player info from the json file that we downlaoded

def getAllPlayersDetailedJson():
# read player info from the json file that we downloaded
with open(PLAYERS_INFO_FILENAME) as json_data:
d = json.load(json_data)
return d
return json.load(json_data)


# writes the results to csv file
def writeToFile(countOfplayersPicked, fileName):
with open(fileName, 'w') as out:
# writes the results to csv file
with open(fileName, "w") as out:
csv_out = csv.writer(out)
csv_out.writerow(['name', 'num'])
csv_out.writerow(["name", "num"])
for row in countOfplayersPicked:
csv_out.writerow(row)

# Main Script

parser = argparse.ArgumentParser(description='Get players picked in your league in a certain GameWeek')
parser.add_argument('-l','--league', help='league entry id', required=True)
parser.add_argument('-g','--gameweek', help='gameweek number', required=True)
parser.add_argument('-t', '--type', help='league type')
parser.add_argument('-d', '--debug', help='deubg mode on')
args = vars(parser.parse_args())

if args['debug']:
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

getPlayersInfo()
playerElementIdToNameMap = {}
allPlayers = getAllPlayersDetailedJson()
for element in allPlayers["elements"]:
playerElementIdToNameMap[element["id"]] = element["web_name"]#.encode('ascii', 'ignore')

countOfplayersPicked = {}
countOfCaptainsPicked = {}
totalNumberOfPlayersCount = 0
pageCount = START_PAGE
GWNumber = args['gameweek']
leagueIdSelected = args['league']

if args['type'] == "h2h":
leagueStandingUrl = FPL_URL + LEAGUE_H2H_STANDING_SUBURL
print("h2h league mode")
else:
leagueStandingUrl = FPL_URL + LEAGUE_CLASSIC_STANDING_SUBURL
print("classic league mode")


try:
entries = getUserEntryIds(leagueIdSelected, pageCount, leagueStandingUrl)
except Exception, err:
print "Error occured in getting entries/managers in the league."
print err
raise

for entry in tqdm(entries):
try:
elements, captainId = getplayersPickedForEntryId(entry, GWNumber)
except Exception, err:
print "Error occured in getting palyers and captain of the entry/manager"
print err
raise
if not elements:
continue
for element in elements:
name = playerElementIdToNameMap[element]
if name in countOfplayersPicked:
countOfplayersPicked[name] += 1
else:
countOfplayersPicked[name] = 1

captainName = playerElementIdToNameMap[captainId]
if captainName in countOfCaptainsPicked:
countOfCaptainsPicked[captainName] += 1
def main():
# Main Script
parser = argparse.ArgumentParser(
description="Get players picked in your league in a certain GameWeek",
)
parser.add_argument("-l", "--league", help="league entry id", required=True)
parser.add_argument("-g", "--gameweek", help="gameweek number", required=True)
parser.add_argument("-t", "--type", help="league type")
parser.add_argument("-d", "--debug", help="deubg mode on")
args = vars(parser.parse_args())

if args["debug"]:
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

getPlayersInfo()
playerElementIdToNameMap = {}
allPlayers = getAllPlayersDetailedJson()
for element in allPlayers["elements"]:
playerElementIdToNameMap[element["id"]] = element["web_name"]

countOfplayersPicked = {}
countOfCaptainsPicked = {}
GWNumber = args["gameweek"]
leagueIdSelected = args["league"]

if args["type"] == "h2h":
leagueStandingUrl = FPL_URL + LEAGUE_H2H_STANDING_SUBURL
print("h2h league mode")
else:
countOfCaptainsPicked[captainName] = 1
leagueStandingUrl = FPL_URL + LEAGUE_CLASSIC_STANDING_SUBURL
print("classic league mode")

listOfcountOfplayersPicked = sorted(countOfplayersPicked.items(), key=lambda x: x[1], reverse=True)
writeToFile(listOfcountOfplayersPicked, "output/GW"+str(GWNumber)+" Players "+str(leagueIdSelected)+".csv")
listOfCountOfCaptainsPicked = sorted(countOfCaptainsPicked.items(), key=lambda x: x[1], reverse=True)
writeToFile(listOfCountOfCaptainsPicked, "output/GW"+str(GWNumber)+" Captains "+str(leagueIdSelected)+".csv")
try:
entries = getUserEntryIds(leagueIdSelected, START_PAGE, leagueStandingUrl)
except Exception as e:
print("Error occured in getting entries/managers in the league.")
print(e)
raise

for entry in tqdm(entries):
try:
elements, captainId = getplayersPickedForEntryId(entry, GWNumber)
except Exception as e:
print("Error occured in getting palyers and captain of the entry/manager")
print(e)
raise
if not elements:
continue
for element in elements:
name = playerElementIdToNameMap[element]
if name in countOfplayersPicked:
countOfplayersPicked[name] += 1
else:
countOfplayersPicked[name] = 1

captainName = playerElementIdToNameMap[captainId]
if captainName in countOfCaptainsPicked:
countOfCaptainsPicked[captainName] += 1
else:
countOfCaptainsPicked[captainName] = 1

listOfcountOfplayersPicked = sorted(
countOfplayersPicked.items(),
key=lambda x: x[1],
reverse=True,
)
writeToFile(
listOfcountOfplayersPicked,
f"output/GW{GWNumber}Players{leagueIdSelected}.csv",
)

listOfCountOfCaptainsPicked = sorted(
countOfCaptainsPicked.items(),
key=lambda x: x[1],
reverse=True,
)
writeToFile(
listOfCountOfCaptainsPicked,
f"output/GW{GWNumber}Captains{leagueIdSelected}.csv",
)


if __name__ == "__main__":
main()
Loading