Advertisement
Guest User

AutoUpdater

a guest
Sep 21st, 2017
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.38 KB | None | 0 0
  1. import praw
  2. import pytz
  3. import json
  4. import getpass
  5. import requests
  6. import HTMLParser
  7. from time import sleep
  8. from datetime import datetime
  9.  
  10. class Auto_Updater_Bot(object):
  11. def __init__(self):
  12. self.ruser = raw_input('Username: ')
  13. self.rpass = getpass.getpass(prompt='Password (will not be visible): ')
  14. self.userAgent = 'Updating GDTs for /r/hockey'
  15.  
  16. self.teams = {'MIN': ['/r/wildhockey', 'Minnesota', 'Wild'], 'TOR': ['/r/leafs', 'Toronto', 'Leafs'], 'WSH': ['/r/caps', 'Washington', 'Capitals'], 'BOS': ['/r/bostonbruins', 'Boston', 'Bruins'], 'DET': ['/r/detroitredwings', 'Detroit', 'Red Wings'], 'NYI': ['/r/newyorkislanders', 'New York', 'Islanders'], 'FLA': ['/r/floridapanthers', 'Florida', 'Panthers'], 'COL': ['/r/coloradoavalanche', 'Colorado', 'Avalanche'], 'NSH': ['/r/predators', 'Nashville', 'Predators'], 'CHI': ['/r/hawks', 'Chicago', 'Blackhawks'], 'NJD': ['/r/devils', 'New Jersey', 'Devils'], 'DAL': ['/r/dallasstars', 'Dallas', 'Stars'], 'CGY': ['/r/calgaryflames', 'Calgary', 'Flames'], 'NYR': ['/r/rangers', 'New York', 'Rangers'], 'CAR': ['/r/canes', 'Carolina', 'Hurricanes'], 'WPG': ['/r/winnipegjets', 'Winnipeg', 'Jets'], 'BUF': ['/r/sabres', 'Buffalo', 'Sabres'], 'VAN': ['/r/canucks', 'Vancouver', 'Canucks'], 'STL': ['/r/stlouisblues', 'St Louis', 'Blues'], 'SJS': ['/r/sanjosesharks', 'San Jose', 'Sharks'], 'MTL': ['/r/habs', 'Montreal', 'Canadiens'], 'PHI': ['/r/flyers', 'Philadelphia', 'Flyers'], 'ANA': ['/r/anaheimducks', 'Anaheim', 'Ducks'], 'LAK': ['/r/losangeleskings', 'Los Angeles', 'Kings'], 'CBJ': ['/r/bluejackets', 'Columbus', 'Blue Jackets'], 'PIT': ['/r/penguins', 'Pittsburgh', 'Penguins'], 'EDM': ['/r/edmontonoilers', 'Edmonton', 'Oilers'], 'TBL': ['/r/tampabaylightning', 'Tampa Bay', 'Lightning'], 'ARI': ['/r/coyotes', 'Arizona', 'Coyotes'], 'OTT': ['/r/ottawasenators', 'Ottawa', 'Senators']}
  17. self.convert = {'San Jose Sharks': 'SJS', 'Detroit Red Wings': 'DET', 'Arizona Coyotes': 'ARI', 'Carolina Hurricanes': 'CAR', 'Toronto Maple Leafs': 'TOR', 'Boston Bruins': 'BOS', 'Florida Panthers': 'FLA', 'Columbus Blue Jackets': 'CBJ', 'Anaheim Ducks': 'ANA', 'Buffalo Sabres': 'BUF', 'Montreal Canadiens': 'MTL', 'Edmonton Oilers': 'EDM', 'Pittsburgh Penguins': 'PIT', 'New York Rangers': 'NYR', 'Washington Capitals': 'WSH', 'St Louis Blues': 'STL', 'Colorado Avalanche': 'COL', 'Minnesota Wild': 'MIN', 'Dallas Stars': 'DAL', 'Winnipeg Jets': 'WPG', 'New Jersey Devils': 'NJD', 'Tampa Bay Lightning': 'TBL', 'Los Angeles Kings': 'LAK', 'Calgary Flames': 'CGY', 'Chicago Blackhawks': 'CHI', 'New York Islanders': 'NYI', 'Nashville Predators': 'NSH', 'Ottawa Senators': 'OTT', 'Vancouver Canucks': 'VAN', 'Philadelphia Flyers': 'PHI'}
  18.  
  19. self.utc = pytz.timezone('UTC')
  20. self.pacific = pytz.timezone('US/Pacific')
  21.  
  22. self.gameThread = {}
  23. self.final = False
  24.  
  25. def scrape_games(self):
  26. today = datetime.now(self.pacific).strftime('%Y-%m-%d')
  27. url = 'https://statsapi.web.nhl.com/api/v1/schedule?startDate='+today+'&endDate='+today+'&expand=schedule.teams,schedule.linescore'
  28. w = requests.get(url)
  29. data = json.loads(w.content)['dates'][0]['games']
  30. w.close()
  31.  
  32. games = {}
  33. z = 1
  34. for x in data[:]:
  35. games[z] = {'a':x['teams']['away']['team']['abbreviation'],'h':x['teams']['home']['team']['abbreviation'],'id':x['gamePk']}
  36. if x['linescore']['currentPeriod'] == 0:
  37. games[z]['time'] = 'Pre-game'
  38. elif x['linescore']['currentPeriodTimeRemaining'] == 'FINAL':
  39. games[z]['time'] = 'Finished'
  40. else:
  41. games[z]['time'] = x['linescore']['currentPeriodOrdinal']+' '+x['linescore']['currentPeriodTimeRemaining']
  42. z += 1
  43.  
  44. for x in sorted(games.keys()):
  45. print '{0}. {1} at {2} - {3}'.format(x,games[x]['a'],games[x]['h'],games[x]['time'])
  46.  
  47. response = raw_input('Please enter the number of the game you need: ')
  48. valid = False
  49. while not valid:
  50. try:
  51. self.gameThread = games[int(response)]
  52. except Exception as e:
  53. response = raw_input('Invalid input, please enter the number of the game you need: ')
  54. else:
  55. valid = True
  56.  
  57. def find_gdt(self,game):
  58. search = raw_input('Have you already posted the GDT? (y/n) ')
  59. if search.lower() == 'y':
  60. user = r.get_redditor(self.ruser)
  61. posts = [x for x in user.get_submitted(limit=100)]
  62.  
  63. game_check = {}
  64. for x in posts[:]:
  65. made = self.utc.localize(datetime.utcfromtimestamp(x.created_utc)).astimezone(self.pacific)
  66. if (made.strftime('%d%m%Y') == datetime.now(self.pacific).strftime('%d%m%Y')) and (x.subreddit.display_name.lower() == 'hockey'):
  67. team_lst = [self.teams[self.gameThread['a']][1],self.teams[self.gameThread['a']][2],self.teams[self.gameThread['h']][1],self.teams[self.gameThread['h']][2]]
  68. check = sum(bool(y) for y in [team_lst[0].lower() in x.title.lower(), team_lst[1].lower() in x.title.lower(), team_lst[2].lower() in x.title.lower(), team_lst[3].lower() in x.title.lower()])
  69. if check > 0:
  70. game_check[x] = check
  71. print game_check
  72. game_check_sorted = sorted(game_check.items(), key=lambda x:x[1], reverse=True)
  73. if len(game_check_sorted) == 0:
  74. search = 'n'
  75. print 'GDT not found.'
  76. print search
  77. else:
  78. self.gameThread['thread'] = game_check_sorted[0][0]
  79. print 'GDT found: '+self.gameThread['thread'].title
  80. if search.lower() == 'n':
  81. thread = raw_input('GDT URL? ')
  82. self.gameThread['thread'] = r.get_submission(thread)
  83.  
  84. def update_gdt(self, game):
  85. url = 'https://statsapi.web.nhl.com/api/v1/game/'+str(self.gameThread['id'])+'/feed/live'
  86. w = requests.get(url)
  87. data = json.loads(w.content)
  88. w.close()
  89.  
  90. period = data['liveData']['linescore']['currentPeriod']
  91. if period == 0:
  92. print 'No updates'
  93. time = 'Pre-game'
  94. else:
  95. time = data['liveData']['linescore']['currentPeriodTimeRemaining']
  96. ordinal = data['liveData']['linescore']['currentPeriodOrdinal']
  97. if ordinal+' '+time == self.gameThread['time']:
  98. print 'No updates'
  99. else:
  100. self.gameThread['time'] = ordinal+' '+time
  101. #Time Table
  102. print 'Creating time table...'
  103. if time == 'FINAL':
  104. timeTable = '|Time Clock|\n|:--:|\n|FINAL|\n\n'
  105. else:
  106. timeTable = '|Time Clock|\n|:--:|\n|{0} - {1}|\n\n'.format(ordinal, time)
  107.  
  108. homeTeam = self.teams[data['gameData']['teams']['home']['abbreviation']][0]
  109. awayTeam = self.teams[data['gameData']['teams']['away']['abbreviation']][0]
  110. #Boxscore
  111. print 'Creating boxscore...'
  112. boxscore = '|Teams|1st|2nd|3rd|\n|:--:|:--:|:--:|:--:|\n'
  113.  
  114. if data['gameData']['game']['type'] == 'R':
  115. if period == 4:
  116. boxscore += 'OT|Total|\n|:--:|:--:|:--:|:--:|:--:|:--:|\n'
  117. elif period == 5:
  118. boxscore += 'OT|SO|Total|\n|:--:|:--:|:--:|:--:|:--:|:--:|:--:|\n'
  119. else:
  120. boxscore += 'Total|\n|:--:|:--:|:--:|:--:|:--:|\n'
  121. elif data['gameData']['game']['type'] == 'P':
  122. for x in range(0,(period-3)):
  123. boxscore += 'OT{0}|'.format(x+1)
  124. boxscore += 'Total|\n|:--:|:--:|:--:|:--:|'
  125. for x in range(0,period-3):
  126. boxscore += ':--:|'
  127. boxscore += ':--:|\n'
  128.  
  129. homeTotal = data['liveData']['linescore']['teams']['home']['goals']
  130. awayTotal = data['liveData']['linescore']['teams']['away']['goals']
  131.  
  132. scoreDict = {}
  133.  
  134. OT = 1
  135. for x in data['liveData']['linescore']['periods']:
  136. score = [x['away']['goals'],x['home']['goals']]
  137. if (data['gameData']['game']['type'] == 'P') and ('OT' in x['ordinalNum']) and (period > 4):
  138. scoreDict['OT'+str(OT)] = score
  139. OT += 1
  140. else:
  141. scoreDict[x['ordinalNum']] = score
  142.  
  143. if period == 1:
  144. scoreDict['2nd'] = ['--','--']
  145. scoreDict['3rd'] = ['--','--']
  146. elif period == 2:
  147. scoreDict['3rd'] = ['--','--']
  148.  
  149. if data['liveData']['linescore']['hasShootout']:
  150. awaySO = data['liveData']['linescore']['shootoutInfo']['away']['scores']
  151. homeSO = data['liveData']['linescore']['shootoutInfo']['home']['scores']
  152. if awaySO > homeSO:
  153. scoreDict['SO'] = [1, 0]
  154. else:
  155. scoreDict['SO'] = [0, 1]
  156.  
  157. boxscore += '|[]({0})|'.format(awayTeam)
  158. for x in sorted(scoreDict.keys()):
  159. boxscore += '{0}|'.format(scoreDict[x][0])
  160.  
  161. boxscore += '{0}|\n|[]({1})|'.format(awayTotal,homeTeam)
  162. for x in sorted(scoreDict.keys()):
  163. boxscore += '{0}|'.format(scoreDict[x][1])
  164.  
  165. boxscore += '{0}|\n\n'.format(homeTotal)
  166. #Team Stats
  167. print 'Creating team stats...'
  168. homeStats = data['liveData']['boxscore']['teams']['home']['teamStats']['teamSkaterStats']
  169. awayStats = data['liveData']['boxscore']['teams']['away']['teamStats']['teamSkaterStats']
  170.  
  171. teamStats = '|Team|Shots|Hits|Blocked|FO Wins|Giveaways|Takeaways|Power Plays|\n|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|\n'
  172. teamStats += '|[]({0})|{1}|{2}|{3}|{4}%|{5}|{6}|{7}/{8}|\n'.format(awayTeam,awayStats['shots'],awayStats['hits'],awayStats['blocked'],awayStats['faceOffWinPercentage'],awayStats['giveaways'],awayStats['takeaways'],str(int(awayStats['powerPlayGoals'])),str(int(awayStats['powerPlayOpportunities'])))
  173. teamStats += '|[]({0})|{1}|{2}|{3}|{4}%|{5}|{6}|{7}/{8}|\n\n'.format(homeTeam,homeStats['shots'],homeStats['hits'],homeStats['blocked'],homeStats['faceOffWinPercentage'],homeStats['giveaways'],homeStats['takeaways'],str(int(homeStats['powerPlayGoals'])),str(int(homeStats['powerPlayOpportunities'])))
  174. #Goals
  175. print 'Creating goal table...'
  176. allPlays = data['liveData']['plays']['allPlays']
  177. scoringPlays = data['liveData']['plays']['scoringPlays']
  178.  
  179. goalDict = {'1st':[],'2nd':[],'3rd':[],'OT':[]}
  180.  
  181. if (data['gameData']['game']['type'] == 'R') and (period == 5):
  182. goalDict['SO'] = []
  183. if (data['gameData']['game']['type'] == 'P') and (period > 4):
  184. del goalDict['OT']
  185. for x in range(0,(period-4)):
  186. goalDict['OT'+str(x+1)] = []
  187.  
  188. OT = 1
  189. for x in scoringPlays:
  190. goal = allPlays[x]
  191. if (data['gameData']['game']['type'] == 'P') and ('OT' in goal['about']['ordinalNum']) and (period > 4):
  192. goalDict['OT'+str(OT)].append([goal['about']['periodTime'],self.teams[self.convert[goal['team']['name'].replace(u'\xe9','e').replace('.','')]][0],goal['result']['strength']['name'],goal['result']['description'].replace(u'\xe9','e')])
  193. OT += 1
  194. else:
  195. goalDict[goal['about']['ordinalNum']].append([goal['about']['periodTime'],self.teams[self.convert[goal['team']['name'].replace(u'\xe9','e').replace('.','')]][0],goal['result']['strength']['name'],goal['result']['description'].replace(u'\xe9','e')])
  196.  
  197. goalTable = '|Period|Time|Team|Strength|Description|\n|:--:|:--:|:--:|:--:|:--:|\n'
  198. #Reverse for GDT and forward for PGT
  199. for x in sorted(goalDict.keys(),reverse=True):
  200. for y in goalDict[x][::-1]:
  201. if x == 'SO':
  202. goalTable += '|{0}|{1}|[]({2})|---|{3}|\n'.format(x,y[0],y[1],y[3])
  203. else:
  204. goalTable += '|{0}|{1}|[]({2})|{3}|{4}|\n'.format(x,y[0],y[1],y[2],y[3])
  205.  
  206. goalTable += '\n\n'
  207. #Penalties
  208. print 'Creating penalty table...'
  209. penaltyPlays = data['liveData']['plays']['penaltyPlays']
  210.  
  211. penaltyDict = {'1st':[],'2nd':[],'3rd':[],'OT':[]}
  212.  
  213. if (data['gameData']['game']['type'] == 'P') and (period > 4):
  214. del penaltyDict['OT']
  215. for x in range(0,(period-4)):
  216. penaltyDict['OT'+str(x+1)] = []
  217.  
  218. OT = 1
  219. for x in penaltyPlays:
  220. penalty = allPlays[x]
  221. if (data['gameData']['game']['type'] == 'P') and ('OT' in penalty['about']['ordinalNum']) and (period > 4):
  222. penaltyDict['OT'+str(OT)].append([penalty['about']['periodTime'],self.teams[self.convert[penalty['team']['name'].replace(u'\xe9','e').replace('.','')]][0],penalty['result']['penaltySeverity'],penalty['result']['penaltyMinutes'],penalty['result']['description'].replace(u'\xe9','e')])
  223. else:
  224. penaltyDict[penalty['about']['ordinalNum']].append([penalty['about']['periodTime'],self.teams[self.convert[penalty['team']['name'].replace(u'\xe9','e').replace('.','')]][0],penalty['result']['penaltySeverity'],penalty['result']['penaltyMinutes'],penalty['result']['description'].replace(u'\xe9','e')])
  225.  
  226. penaltyTable = '|Period|Time|Team|Type|Min|Description|\n|:--:|:--:|:-:|:--:|:--:|:--:|\n'
  227. #Reverse for GDT and forward for PGT
  228. for x in sorted(penaltyDict.keys(),reverse=True):
  229. for y in penaltyDict[x][::-1]:
  230. penaltyTable += '|{0}|{1}|[]({2})|{3}|{4}|{5}|\n'.format(x,y[0],y[1],y[2],y[3],y[4])
  231.  
  232. penaltyTable += '\n\n'
  233.  
  234. tables = '***\n\n'+timeTable+boxscore+goalTable+penaltyTable+'***'
  235.  
  236. now = datetime.now()
  237. print now.strftime('%I:%M%p')+' - Updating thread...'
  238. h = HTMLParser.HTMLParser()
  239. op = self.gameThread['thread'].selftext.split('***')
  240. self.gameThread['thread'] = self.gameThread['thread'].edit(h.unescape(op[0]+tables+op[2]))
  241.  
  242. if time == 'FINAL':
  243. self.final = True
  244. close = raw_input('Game over, hit enter/return to exit.')
  245. else:
  246. print 'Sleeping...\n\n'
  247. sleep(60)
  248.  
  249. def run(self):
  250. try:
  251. self.scrape_games()
  252. self.find_gdt(self.gameThread)
  253. while not self.final:
  254. self.update_gdt(self.gameThread)
  255. except Exception as e:
  256. print e
  257.  
  258. AUB = Auto_Updater_Bot()
  259.  
  260. r = praw.Reddit(AUB.userAgent)
  261. r.login(AUB.ruser,AUB.rpass,disable_warning=True)
  262.  
  263. AUB.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement