nba_playoffs_game_updater.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. #!/usr/bin/env python3
  2. import gspread
  3. import json
  4. import random
  5. from os import sys
  6. from oauth2client.service_account import ServiceAccountCredentials
  7. import datetime
  8. import time
  9. from nba_api.stats.static import players
  10. from nba_api.stats.endpoints import playergamelog
  11. import timeout_decorator
  12. import urllib
  13. try:
  14. from nba_api.library.debug.debug import DEBUG_STORAGE
  15. except ImportError:
  16. DEBUG_STORAGE = False
  17. #spreadsheet_key = '1QBQvGSMesox1gwjpaoK-0-p3n-c4I_L73PWCggjdayM' # 2019 Official
  18. #spreadsheet_key = '14pHOScaGXvN83iCca6_5p6QoViYvo223cIJD9nnl7TI' # 2019 Test
  19. #spreadsheet_key = '1n2qAxDhy3B-a20cn92H340GoPeKQE8fpztPlzKpGw80' # 2020 Test
  20. #spreadsheet_key = '1ajlHmH-dUzwkVfD-4NgpkK8ni3I3UuUFcdefF_DUOyg' # 2020 Official
  21. #spreadsheet_key = '1FgoBfPw4Vhi89rcYgxnAxLTeJ84GLXD1r39K0DXqxq4' # 2021 Official
  22. spreadsheet_key = '1Gt4J1nNOv1E3-gikopSJQCD7nAqx7DEYxUqsZNac9_Y' # 2022 Official
  23. json_keyfile = 'NBA Playoffs Game-1f9a46f0715c.json'
  24. day = 'today' # today, else:
  25. #day = datetime.date(2020, 8, 17) # set date manually
  26. nba_cooldown = random.gammavariate(alpha=9, beta=0.4) # don't hammer the NBA API
  27. stats=['PTS', 'REB', 'AST', 'STL', 'BLK', 'TOV', 'WL'] # stats appear in this order
  28. STATS_HEADERS = {
  29. 'Host': 'stats.nba.com',
  30. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0',
  31. 'Accept': 'application/json, text/plain, */*',
  32. 'Accept-Language': 'en-US,en;q=0.5',
  33. 'Accept-Encoding': 'gzip, deflate, br',
  34. 'x-nba-stats-origin': 'stats',
  35. 'x-nba-stats-token': 'true',
  36. 'Connection': 'keep-alive',
  37. 'Referer': 'https://stats.nba.com/',
  38. 'Pragma': 'no-cache',
  39. 'Cache-Control': 'no-cache',
  40. }
  41. proxy_url="https://raw.githubusercontent.com/clarketm/proxy-list/master/proxy-list-raw.txt"
  42. # proxies = [
  43. # "206.127.88.18:80",
  44. # "47.112.104.235:80",
  45. # "60.169.201.13:53315",
  46. # "14.207.10.155:8080",
  47. # "113.100.209.10:3128",
  48. # "113.100.209.145:3128",
  49. # "69.162.65.42:5836",
  50. # "46.18.210.88:5836",
  51. # "203.150.160.95:8080",
  52. # "117.252.68.173:8080",
  53. # "113.100.209.140:3128",
  54. # "218.66.253.146:8800",
  55. # "186.159.5.161:8080",
  56. # "181.224.161.132:999",
  57. # "103.28.90.154:5836",
  58. # "113.100.209.116:3128",
  59. # "45.231.29.45:8080",
  60. # "202.169.255.3:8181",
  61. # "103.52.144.242:8080",
  62. # "181.78.12.164:999",
  63. # "117.67.77.188:4216",
  64. # "183.89.63.159:8080",
  65. # "88.150.220.130:3128",
  66. # "168.195.204.168:8080",
  67. # "116.0.2.162:52076",
  68. # "58.52.115.99:4216",
  69. # "182.23.52.114:6060",
  70. # "116.0.3.238:8080",
  71. # "175.6.66.48:3128",
  72. # "180.183.246.110:8080",
  73. # "220.249.149.69:9999",
  74. # "103.221.254.102:48146",
  75. # "110.77.242.14:8080",
  76. # "198.98.59.87:8080",
  77. # "209.91.216.168:8080",
  78. # "177.8.170.62:8080",
  79. # "218.66.253.144:10200",
  80. # "113.161.58.255:8080",
  81. # "180.244.73.12:8080",
  82. # "190.2.210.98:8080",
  83. # "82.114.71.98:8080",
  84. # "190.103.28.161:999",
  85. # "181.119.69.89:3128",
  86. # "190.120.249.246:999",
  87. # "82.114.115.194:1256",
  88. # "218.66.253.146:10084",
  89. # "103.146.68.255:8080",
  90. # ]
  91. proxies = []
  92. ###############################################################################
  93. def buildProxyList(proxies=[], raw_text_url="https://raw.githubusercontent.com/clarketm/proxy-list/master/proxy-list-raw.txt"):
  94. good_proxy_list = []
  95. proxy_list = []
  96. r = urllib.request.urlopen(raw_text_url)
  97. for line in r:
  98. line = line.decode("utf-8")
  99. line = line.strip()
  100. proxy_list.append(line)
  101. random.shuffle(proxy_list)
  102. proxy_list = proxies + proxy_list
  103. return proxy_list, good_proxy_list
  104. """
  105. Returns a worksheet instance
  106. """
  107. def getWorksheet(spreadsheet_key, json_keyfile):
  108. try:
  109. scope = ['https://spreadsheets.google.com/feeds',
  110. 'https://www.googleapis.com/auth/drive']
  111. credentials = ServiceAccountCredentials.from_json_keyfile_name(json_keyfile, scope)
  112. gc = gspread.authorize(credentials)
  113. spreadsheet = gc.open_by_key(spreadsheet_key)
  114. worksheet = spreadsheet.get_worksheet(0)
  115. except Exception as e:
  116. f"Exception: {str(e)}"
  117. f"Could not retrieve worksheet!"
  118. f"Check your API key, credentials, or network!"
  119. raise(e)
  120. return worksheet
  121. """
  122. Returns a list of lists containing the values of all cells in the worksheet by row
  123. """
  124. def getAllValues(worksheet):
  125. return worksheet.get_all_values()
  126. """
  127. Create various date variables based on "today's" day
  128. """
  129. def setDates(day):
  130. if day == 'today':
  131. # in case games go past midnight
  132. date = datetime.datetime.now() - datetime.timedelta(hours=3)
  133. date = date.date()
  134. else:
  135. date = day
  136. url_date = date.strftime('%m/%d/%Y')
  137. year = date.year
  138. season = f"{format(str(year - 1))}-{str(year)[2:]}"
  139. return url_date, season, date
  140. """
  141. Determines the number of players in the pool
  142. """
  143. def getNumberOfParticipants(all_values):
  144. count=0
  145. for row_num, row in enumerate(all_values):
  146. if row[0] != "" and row_num >= 3 and count == 0:
  147. start=row_num
  148. count+=1
  149. elif row[0] != "" and row_num >= 3 and count == 1:
  150. end=row_num
  151. break
  152. num_participants = end - start
  153. return num_participants
  154. """
  155. Determines the active day's first and last rows
  156. """
  157. def getFirstRowLastRow(all_values, num_participants, current_date):
  158. first_row = None
  159. last_row = None
  160. for row_num, row in enumerate(all_values, start=1):
  161. date=row[0]
  162. if date != "" and row_num >= 4:
  163. day = datetime.datetime.strptime('{} {}'.format(date,
  164. str(current_date.year)),
  165. '%A, %B %d %Y')
  166. if day.date() == current_date:
  167. first_row = row_num
  168. last_row = first_row + num_participants - 1
  169. break
  170. return first_row, last_row
  171. """
  172. Rudimentary way to reduce player name errors
  173. """
  174. def cleanFirstNameLastName(player):
  175. first_name_last_name = player.split()
  176. first_name = first_name_last_name[0]
  177. first_name = first_name.replace('.', '')
  178. # New nickname for T.J. Warren should be "The Outlier"
  179. if first_name == "TJ":
  180. first_name = "T.J."
  181. elif first_name == "Donavan":
  182. first_name = "Donovan"
  183. last_name = first_name_last_name[1]
  184. player_clean = first_name + ' ' + last_name
  185. return player_clean
  186. """
  187. Create a unique list of players that have been selected today
  188. Also, append misspelled players to batch_update_list to autofix on next push if we can
  189. """
  190. def cleanPlayers(all_values, first_row, last_row, batch_update_list):
  191. players_unique = []
  192. for row_num, row in enumerate(all_values, start=1):
  193. if first_row <= row_num <= last_row:
  194. player = row[2]
  195. if player[-7:] != "-FIX!!!" and player != "":
  196. if len(players.find_players_by_full_name(player)) > 0:
  197. players_unique.append(player)
  198. else:
  199. player_clean = cleanFirstNameLastName(player)
  200. if len(players.find_players_by_full_name(player_clean)) > 0:
  201. all_values[row_num - 1][2] = player_clean
  202. batch_update_list.append({'range': f'{indexToLetter(2)}{row_num}', 'values': [[player_clean]]})
  203. players_unique.append(player_clean)
  204. else:
  205. print("Player:", player, "not found, please fix name!")
  206. players_unique = list(dict.fromkeys(players_unique))
  207. return players_unique, batch_update_list, all_values
  208. """
  209. Pull player's gamelog from stats.nba.com based on the url_date and player_id
  210. """
  211. #@timeout_decorator.timeout(30)
  212. def getStats(players_unique, url_date, season, proxy_list=[], good_proxy_list=[]):
  213. stats_dict = {}
  214. for player in players_unique:
  215. player_info = players.find_players_by_full_name(player)
  216. player_id = player_info[0].get('id')
  217. print('Retrieving stats for: ' + player)
  218. while True:
  219. # Move working proxies to the front of the list
  220. if len(good_proxy_list) > 0:
  221. proxy_list = good_proxy_list + proxy_list
  222. # Remove duplicate proxies
  223. proxy_list = list(dict.fromkeys(proxy_list))
  224. # Use the first proxy in the list
  225. request_proxy = proxy_list[0]
  226. try:
  227. print('Proxy:', 'http://' + request_proxy)
  228. player_game_log = playergamelog.PlayerGameLog( player_id=player_id,
  229. proxy='http://' + request_proxy,
  230. season=season,
  231. timeout=10,
  232. league_id_nullable='00',
  233. season_type_all_star='Playoffs',
  234. date_from_nullable=url_date,
  235. date_to_nullable=url_date,
  236. )
  237. print('Success!')
  238. if request_proxy not in good_proxy_list:
  239. good_proxy_list.append(request_proxy)
  240. player_game_log_dict = player_game_log.get_dict()
  241. if DEBUG_STORAGE is False:
  242. time.sleep(nba_cooldown)
  243. break
  244. except OSError as e:
  245. print(e)
  246. if request_proxy in good_proxy_list:
  247. good_proxy_list.remove(request_proxy)
  248. else:
  249. print('Proxy refused, removing', request_proxy)
  250. proxy_list.remove(request_proxy)
  251. continue
  252. except Exception as e:
  253. print(e)
  254. print('Could not connect to the NBA API, sleeping for 30 seconds')
  255. time.sleep(30)
  256. player_game_log_results = player_game_log_dict.get('resultSets')[0]
  257. player_game_log_headers = player_game_log_results.get('headers')
  258. # if player has no stats for this day, list will be empty
  259. if len(player_game_log_results.get('rowSet')) < 1:
  260. player_stats_dict = None
  261. else:
  262. player_game_log_stats = player_game_log_results.get('rowSet')[0]
  263. player_stats_dict = dict(zip(player_game_log_headers, player_game_log_stats))
  264. stats_dict[player] = player_stats_dict
  265. return stats_dict, good_proxy_list
  266. """
  267. Append stat cells that have changes to batch_update_list
  268. Also append player cells that need fixing to batch_update_list
  269. """
  270. def cellsToUpdate(all_values, first_row, last_row, stats_dict, stats, batch_update_list):
  271. for row_num, row in enumerate(all_values, start=1):
  272. if first_row <= row_num <= last_row:
  273. player_name = row[2]
  274. if player_name[-7:] != "-FIX!!!" and player_name in stats_dict.keys():
  275. if stats_dict[player_name] is not None:
  276. player_stats = stats_dict[player_name]
  277. if player_stats == "Fix!":
  278. batch_update_list.append({'range': f'{indexToLetter(2)}{row_num}', 'values': [[f'{player_name}-FIX!!!']]})
  279. continue
  280. for col_num, stat in enumerate(stats, start=3):
  281. pass
  282. #print(player_name, player_stats[stat])
  283. #print(player_name, f'{indexToLetter(col_num)}{row_num}', str(row[col_num]), f',', player_stats[stat])
  284. if str(player_stats[stat]) != str(row[col_num]) and player_stats[stat] is not None:
  285. #print('Update:', row_num, col_num, player_name, f'{indexToLetter(col_num)}{row_num}', str(row[col_num]), player_stats[stat])
  286. batch_update_list.append({'range': f'{indexToLetter(col_num)}{row_num}', 'values': [[f'{player_stats[stat]}']]}.copy())
  287. return batch_update_list
  288. """
  289. Convert zero-indexed column number to the appropriate column letter (A=0, B=1, C=2...)
  290. """
  291. def indexToLetter(index):
  292. return chr(ord('@')+int(index)+1)
  293. """
  294. Push changes to Google Sheet
  295. """
  296. def batchUpdate(batch_update_list):
  297. if len(batch_update_list) > 1:
  298. worksheet.batch_update(batch_update_list, value_input_option="USER_ENTERED")
  299. else:
  300. print('No update needed, sleeping for 1 minute')
  301. time.sleep(60)
  302. if __name__ == "__main__":
  303. # Use a combination of our good proxies with some fetched from the internet for variation
  304. proxy_list, good_proxy_list = buildProxyList(proxies=proxies, raw_text_url=proxy_url)
  305. while True:
  306. try:
  307. batch_update_list = []
  308. worksheet = getWorksheet(spreadsheet_key, json_keyfile)
  309. url_date, season, date = setDates(day)
  310. print("Date: " + str(date))
  311. all_values = getAllValues(worksheet)
  312. num_participants = getNumberOfParticipants(all_values)
  313. first_row, last_row = getFirstRowLastRow(all_values, num_participants, date)
  314. if first_row is None:
  315. print("No games today! Pausing for 1000 seconds...")
  316. time.sleep(1000)
  317. continue
  318. players_unique, batch_update_list, all_values = cleanPlayers(all_values, first_row, last_row, batch_update_list)
  319. stats_dict, good_proxy_list = getStats(players_unique, url_date, season, proxy_list=proxy_list, good_proxy_list=good_proxy_list)
  320. batch_update_list = cellsToUpdate(all_values, first_row, last_row, stats_dict, stats, batch_update_list)
  321. if len(batch_update_list) > 1:
  322. print(batch_update_list)
  323. batchUpdate(batch_update_list)
  324. except Exception as e:
  325. print(e)
  326. print('Sleeping for 10 seconds')
  327. time.sleep(10)
  328. continue