Browse Source

Catch http exception

cryobry 4 years ago
commit
ac32e8d9f5
2 changed files with 431 additions and 0 deletions
  1. 217 0
      nba_playoffs_game_updater.py
  2. 214 0
      nba_playoffs_game_updater2.py

+ 217 - 0
nba_playoffs_game_updater.py

@@ -0,0 +1,217 @@
+#!/usr/bin/env python3
+
+import gspread
+from oauth2client.service_account import ServiceAccountCredentials
+
+import sys
+import nba_py.player as player
+
+import datetime
+import time
+
+import timeout_decorator
+
+#_spreadsheetKey = "1wX5ilnky-YDfa2lTLcLYHpGq1UOLkUI5Ii9cIZeAZVI"
+_spreadsheetKey = "12Zv95ZMJ008KXC5ytVnBusjX9wUnpOg0TOLwmxMNOTQ"
+
+####### GET SHEETS AND NUM PARTICIPANTS #######
+
+def _getStatsSheet(_key):
+  scope = ['https://spreadsheets.google.com/feeds',
+           'https://www.googleapis.com/auth/drive']
+
+  _credentials = ServiceAccountCredentials.from_json_keyfile_name('NBA Playoffs Game-1f9a46f0715c.json', scope)
+
+  _gc = gspread.authorize(_credentials)
+
+  # open spreadsheet
+  _spreadsheet = _gc.open_by_key(_key)
+  # open worksheet
+  _statsSheet = _spreadsheet.get_worksheet(0)
+  _leaderSheet = _spreadsheet.get_worksheet(1)
+  
+  # count participants
+  _numParticipants = _leaderSheet.row_count - 1
+  # return stats worksheet
+  return _statsSheet, _numParticipants
+
+
+def _getPlayersCells(_statsSheet, _numParticipants):
+  
+  # get today
+  _today = datetime.date.today()
+  #_today = datetime.date(2018, 5, 2)
+  _urlDate = _today.strftime('%m/%d/%Y')
+
+  # count rows
+  _shtRows =  _statsSheet.row_count
+  
+  # set first date cell
+  _startRow = 4
+  
+  # get date cells
+  while _startRow <= _shtRows:
+    _dateCell = _statsSheet.cell(_startRow, 1, value_render_option='UNFORMATTED_VALUE')
+    _daysSince1900 = _dateCell.value
+    _date = datetime.date(1899, 12, 30) + datetime.timedelta(int(_daysSince1900))
+    
+    if _today == _date:
+      break
+    else:
+      _startRow += _numParticipants
+      
+  _lastRow = _startRow + _numParticipants - 1
+   
+  # get todays players
+   
+  _playersCells = _statsSheet.range(_startRow, 3, _lastRow, 3)
+   
+  # filter cells
+   
+  for _playerCell in _playersCells[:]:
+
+    while True:
+      try:
+        # remove empty cells
+        if _playerCell.value == "":
+          _playersCells.remove(_playerCell)
+          break
+          
+        # remove finished games
+        #_rowNumber = _playerCell.row
+        #_wlCell = _statsSheet.cell(_rowNumber, 11)
+        #if _wlCell.value != "":
+          #_playersCells.remove(_playerCell)
+          #break
+      except gspread.exceptions.APIError:
+        print("API overloaded, adding a 100 second delay...")
+        time.sleep(100)
+        continue
+      break
+
+  return _playersCells, _urlDate
+
+
+####### PARSE PLAYERS #######
+
+def _getPlayerFirstNameLastName(_player):
+  _firstNamelastName = _player.split()
+  _firstName = _firstNamelastName[0]
+  _firstName = _firstName.replace('.', '')
+  _lastName = _firstNamelastName[1]
+  return _firstName, _lastName
+
+@timeout_decorator.timeout(10)  
+def _getPlayerID(_firstName, _lastName):
+  _playerID = player.get_player(first_name=_firstName,last_name=_lastName)
+  return _playerID
+
+
+####### GET STATS #######
+@timeout_decorator.timeout(10)
+def _getPlayerStats(_playerID, _urlDate):
+
+  _playerStats = {}
+  _playerGameLogs = player.PlayerGameLogs(player_id=_playerID,
+                                          season_type='Playoffs',
+                                          date_from=_urlDate,
+                                          date_to=_urlDate)
+
+  for _playerGameLog in _playerGameLogs.info():
+    for _stat in _playerGameLog.keys():
+      _playerStats[_stat] = _playerGameLog[_stat]
+
+  return _playerStats
+
+
+####### UPDATE PLAYER STATS CELLS #######
+
+def _updatePlayerStatsCells(_statsSheet, _playerCell, _playerStats):
+
+  _rowNumber = _playerCell.row
+
+  for _stat in _playerStats:
+    if _stat == "PTS" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 4, _playerStats[_stat])
+    elif _stat == "REB" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 5, _playerStats[_stat])
+    elif _stat == "AST" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 6, _playerStats[_stat])
+    elif _stat == "STL" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 7, _playerStats[_stat])
+    elif _stat == "BLK" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 8, _playerStats[_stat])
+    elif _stat == "TOV" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 9, _playerStats[_stat])
+
+    if _stat == "WL" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 11, _playerStats[_stat])
+
+
+def _badName(_statsSheet, _playerCell):
+  _rowNumber = _playerCell.row
+  _statsSheet.update_cell(_rowNumber, 12, "Fix name, then delete this message!")
+
+###### EXECUTE ########
+
+while True:
+
+  try:
+    _statsSheet, _numParticipants = _getStatsSheet(_spreadsheetKey)
+    _playersCells, _urlDate = _getPlayersCells(_statsSheet, _numParticipants)
+  except gspread.exceptions.APIError:
+    print("API overloaded, adding a 100 second delay...")
+    time.sleep(100)
+    continue
+  except oauth2client.client.HttpAccessTokenRefreshError:
+    time.sleep(100)
+    continue
+
+  for _playerCell in _playersCells:
+    while True:
+    
+      try:
+        _playerName = _playerCell.value
+        print(_playerName)
+      except gspread.exceptions.APIError:
+        print("API overloaded, adding a 100 second delay...")
+        time.sleep(100)
+        continue
+        
+      try:
+        _firstName, _lastName = _getPlayerFirstNameLastName(_playerName)
+      except:
+        #_badName(_statsSheet, _playerCell)
+        break
+         
+      try:
+        print("Getting player ID...")
+        _playerID = _getPlayerID(_firstName, _lastName)
+      except timeout_decorator.TimeoutError:
+        print("NBA.com API not responding, retrying...")
+        continue
+      except:
+        #_badName(_statsSheet, _playerCell)
+        break
+          
+      try:
+        print("Getting player stats...")
+        _playerStats = _getPlayerStats(_playerID, _urlDate)
+      except timeout_decorator.TimeoutError:
+        print("NBA.com API not responding, retrying...")
+        continue
+        
+      try: 
+        print("Updating stats...")
+        _updatePlayerStatsCells(_statsSheet, _playerCell, _playerStats)
+      except gspread.exceptions.APIError:
+        print("API overloaded, adding a 100 second delay...")
+        time.sleep(100)
+        continue
+      
+      break # move to next player in player list
+      
+  print("Cooling down, safe to break!")
+  time.sleep(100)
+  continue # restart entire loop
+

+ 214 - 0
nba_playoffs_game_updater2.py

@@ -0,0 +1,214 @@
+#!/usr/bin/env python3
+
+import gspread
+from oauth2client.service_account import ServiceAccountCredentials
+
+import sys
+import nba_py.player as player
+
+import datetime
+import time
+
+import timeout_decorator
+
+#_spreadsheetKey = "1wX5ilnky-YDfa2lTLcLYHpGq1UOLkUI5Ii9cIZeAZVI"
+_spreadsheetKey = "12Zv95ZMJ008KXC5ytVnBusjX9wUnpOg0TOLwmxMNOTQ"
+
+####### GET SHEETS AND NUM PARTICIPANTS #######
+
+def _getStatsSheet(_key):
+  scope = ['https://spreadsheets.google.com/feeds',
+           'https://www.googleapis.com/auth/drive']
+
+  _credentials = ServiceAccountCredentials.from_json_keyfile_name('NBA Playoffs Game-1f9a46f0715c.json', scope)
+
+  _gc = gspread.authorize(_credentials)
+
+  # open spreadsheet
+  _spreadsheet = _gc.open_by_key(_key)
+  # open worksheet
+  _statsSheet = _spreadsheet.get_worksheet(0)
+  _leaderSheet = _spreadsheet.get_worksheet(1)
+  
+  # count participants
+  _numParticipants = _leaderSheet.row_count - 1
+  # return stats worksheet
+  return _statsSheet, _numParticipants
+
+
+def _getPlayersCells(_statsSheet, _numParticipants):
+  
+  # get today
+  _today = datetime.date.today()
+  #_today = datetime.date(2018, 5, 2)
+  _urlDate = _today.strftime('%m/%d/%Y')
+
+  # count rows
+  _shtRows =  _statsSheet.row_count
+  
+  # set first date cell
+  _startRow = 4
+  
+  # get date cells
+  while _startRow <= _shtRows:
+    _dateCell = _statsSheet.cell(_startRow, 1, value_render_option='UNFORMATTED_VALUE')
+    _daysSince1900 = _dateCell.value
+    _date = datetime.date(1899, 12, 30) + datetime.timedelta(int(_daysSince1900))
+    
+    if _today == _date:
+      break
+    else:
+      _startRow += _numParticipants
+      
+  _lastRow = _startRow + _numParticipants - 1
+   
+  # get todays players
+   
+  _playersCells = _statsSheet.range(_startRow, 3, _lastRow, 3)
+   
+  # filter cells
+   
+  for _playerCell in _playersCells[:]:
+
+    while True:
+      try:
+        # remove empty cells
+        if _playerCell.value == "":
+          _playersCells.remove(_playerCell)
+          break
+          
+        # remove finished games
+        #_rowNumber = _playerCell.row
+        #_wlCell = _statsSheet.cell(_rowNumber, 11)
+        #if _wlCell.value != "":
+          #_playersCells.remove(_playerCell)
+          #break
+      except gspread.exceptions.APIError:
+        print("API overloaded, adding a 100 second delay...")
+        time.sleep(100)
+        continue
+      break
+
+  return _playersCells, _urlDate
+
+
+####### PARSE PLAYERS #######
+
+def _getPlayerFirstNameLastName(_player):
+  _firstNamelastName = _player.split()
+  _firstName = _firstNamelastName[0]
+  _firstName = _firstName.replace('.', '')
+  _lastName = _firstNamelastName[1]
+  return _firstName, _lastName
+
+@timeout_decorator.timeout(10)  
+def _getPlayerID(_firstName, _lastName):
+  _playerID = player.get_player(first_name=_firstName,last_name=_lastName)
+  return _playerID
+
+
+####### GET STATS #######
+@timeout_decorator.timeout(10)
+def _getPlayerStats(_playerID, _urlDate):
+
+  _playerStats = {}
+  _playerGameLogs = player.PlayerGameLogs(player_id=_playerID,
+                                          season_type='Playoffs',
+                                          date_from=_urlDate,
+                                          date_to=_urlDate)
+
+  for _playerGameLog in _playerGameLogs.info():
+    for _stat in _playerGameLog.keys():
+      _playerStats[_stat] = _playerGameLog[_stat]
+
+  return _playerStats
+
+
+####### UPDATE PLAYER STATS CELLS #######
+
+def _updatePlayerStatsCells(_statsSheet, _playerCell, _playerStats):
+
+  _rowNumber = _playerCell.row
+
+  for _stat in _playerStats:
+    if _stat == "PTS" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 4, _playerStats[_stat])
+    elif _stat == "REB" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 5, _playerStats[_stat])
+    elif _stat == "AST" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 6, _playerStats[_stat])
+    elif _stat == "STL" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 7, _playerStats[_stat])
+    elif _stat == "BLK" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 8, _playerStats[_stat])
+    elif _stat == "TOV" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 9, _playerStats[_stat])
+
+    if _stat == "WL" and _playerStats[_stat] != "":
+      _statsSheet.update_cell(_rowNumber, 11, _playerStats[_stat])
+
+
+def _badName(_statsSheet, _playerCell):
+  _rowNumber = _playerCell.row
+  _statsSheet.update_cell(_rowNumber, 12, "Fix name, then delete this message!")
+
+###### EXECUTE ########
+
+while True:
+
+  try:
+    _statsSheet, _numParticipants = _getStatsSheet(_spreadsheetKey)
+    _playersCells, _urlDate = _getPlayersCells(_statsSheet, _numParticipants)
+  except gspread.exceptions.APIError:
+    print("API overloaded, adding a 100 second delay...")
+    time.sleep(100)
+    continue
+
+  for _playerCell in _playersCells:
+    while True:
+    
+      try:
+        _playerName = _playerCell.value
+        print(_playerName)
+      except gspread.exceptions.APIError:
+        print("API overloaded, adding a 100 second delay...")
+        time.sleep(100)
+        continue
+        
+      try:
+        _firstName, _lastName = _getPlayerFirstNameLastName(_playerName)
+      except:
+        #_badName(_statsSheet, _playerCell)
+        break
+         
+      try:
+        print("Getting player ID...")
+        _playerID = _getPlayerID(_firstName, _lastName)
+      except timeout_decorator.TimeoutError:
+        print("NBA.com API not responding, retrying...")
+        continue
+      except:
+        #_badName(_statsSheet, _playerCell)
+        break
+          
+      try:
+        print("Getting player stats...")
+        _playerStats = _getPlayerStats(_playerID, _urlDate)
+      except timeout_decorator.TimeoutError:
+        print("NBA.com API not responding, retrying...")
+        continue
+        
+      try: 
+        print("Updating stats...")
+        _updatePlayerStatsCells(_statsSheet, _playerCell, _playerStats)
+      except gspread.exceptions.APIError:
+        print("API overloaded, adding a 100 second delay...")
+        time.sleep(100)
+        continue
+      
+      break # move to next player in player list
+      
+  print("Cooling down, safe to break!")
+  time.sleep(100)
+  continue # restart entire loop
+