added live sports

This commit is contained in:
Justin 2023-01-09 17:59:07 +08:00 committed by GitHub
parent 00d79c73c9
commit dae81b2626
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -26,7 +26,7 @@ try:
last_updates = json.load(f) last_updates = json.load(f)
f.close() f.close()
last_updates['stocks']['force'] = True last_updates['stocks']['force'] = True
#last_updates['weather']['force'] = True last_updates['sports_l']['force'] = True
f = open('csv/last_updates.json', 'w') f = open('csv/last_updates.json', 'w')
json.dump(last_updates, f) json.dump(last_updates, f)
f.close() f.close()
@ -673,72 +673,179 @@ def updateLeagueTables(api_key, logf):
#logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) #logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])))
#logf.close() #logf.close()
def updatePLtime():
f = open('csv/live_games.json')
try:
all_settings = json.load(f)
f.close()
try:
for league in all_settings['leagues']:
if league == 'PREMIERLEAGUE':
subprocess.run(["sudo", "pkill", "-f", "live_pl.py"], shell=False)
premierleague = subprocess.Popen(["python3", "live_pl.py"], shell=False)
except:
pass
except:
pass
def updateLeagueEvents(api_key, time, logf): def updateLeagueEvents(api_key, time, logf):
url = 'https://bm7p954xoh.execute-api.us-east-2.amazonaws.com/default/ScriptsAPI/sports?{}='.format(time) url = 'https://bm7p954xoh.execute-api.us-east-2.amazonaws.com/default/ScriptsAPI/sports?{}='.format(time)
if time == 'past': if time == 'past':
f = open('csv/past_games.json') f = open('csv/past_games.json')
elif time == 'upcoming': elif time == 'upcoming':
f = open('csv/upcoming_games.json') f = open('csv/upcoming_games.json')
elif time == 'livescore': elif time == 'livescore':
f = open('csv/live_games.json') f = open('csv/live_games.json')
try: try:
all_settings = json.load(f) all_settings = json.load(f)
f.close() f.close()
leagues = all_settings['leagues'].keys()
leagues_info = {} if time == 'livescore':
try:
for league in leagues: leagues_info = {}
for league in all_settings['leagues']:
if league == 'PREMIERLEAGUE': events = []
url += 'PREMIERLEAGUE,' if league == 'NFL':
else: subprocess.run(["sudo", "pkill", "-f", "live_nfl.py"], shell=False)
url += league + ',' nfl = subprocess.Popen(["python3", "live_nfl.py"], shell=False)
url = url[:-1] # remove last comma events.append('Filled')
url += '&apiKey=' + api_key leagues_info[league.upper()] = events
if league == 'NBA':
r = requests.get(url) subprocess.run(["sudo", "pkill", "-f", "live_nba.py"], shell=False)
nba = subprocess.Popen(["python3", "live_nba.py"], shell=False)
all_data = r.json() events.append('Filled')
leagues_info[league.upper()] = events
for league in all_data.keys(): if league == 'NHL':
events = [] subprocess.run(["sudo", "pkill", "-f", "live_nhl.py"], shell=False)
for d in all_data[league]: nhl = subprocess.Popen(["python3", "live_nhl.py"], shell=False)
event = {} events.append('Filled')
event['date'] = d['dateEvent'] leagues_info[league.upper()] = events
if league == 'MLB':
subprocess.run(["sudo", "pkill", "-f", "live_mlb.py"], shell=False)
mlb = subprocess.Popen(["python3", "live_mlb.py"], shell=False)
events.append('Filled')
leagues_info[league.upper()] = events
if league == 'PREMIERLEAGUE':
subprocess.run(["sudo", "pkill", "-f", "live_pl.py"], shell=False)
premierleague = subprocess.Popen(["python3", "live_pl.py"], shell=False)
events.append('Filled')
leagues_info[league.upper()] = events
if league == 'MLS':
subprocess.run(["sudo", "pkill", "-f", "live_mls.py"], shell=False)
mls = subprocess.Popen(["python3", "live_mls.py"], shell=False)
events.append('Filled')
leagues_info[league.upper()] = events
all_settings['leagues'] = leagues_info
f = open( "csv/live_games.json", 'w+' )
json.dump(all_settings, f)
f.close()
except:
pass
else:
leagues = all_settings['leagues'].keys()
leagues_info = {}
for league in leagues:
if time == 'live': if league == 'PREMIERLEAGUE':
url += 'PREMIERLEAGUE,'
event['progess'] = d['strProgress']
event['status'] = d['strStatus']
else: else:
url += league + ','
url = url[:-1] # remove last comma
url += '&apiKey=' + api_key
r = requests.get(url)
all_data = r.json()
for league in all_data.keys():
ten_or_fifteen = slice(None)
events = []
if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU'):
ten_or_fifteen = slice(5)
else:
ten_or_fifteen = slice(None)
for d in all_data[league][ten_or_fifteen]:
event = {}
event['date'] = d['dateEvent']
event['round'] = d['intRound'] if time == 'live':
event['time'] = d['strTime'] event['progess'] = d['strProgress']
event['home_team'] = d['strHomeTeam'] event['status'] = d['strStatus']
else:
event['away_team'] = d['strAwayTeam'] if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU'):
event['date'] = d['dateEvent']
if time != 'upcoming': event['event'] = d['strEvent'].replace("\u2019","'")
event['away_score'] = d['intAwayScore'] event['venue'] = d['strVenue'].replace("\u2019","'")
event['home_score'] = d['intHomeScore'] event['city'] = d['strCity'].replace("\u2019","'")
event['country'] = d['strCountry']
events.append(event) event['season'] = d['strSeason']
leagues_info[league.upper()] = events else:
all_settings['leagues'] = leagues_info event['round'] = d['intRound']
event['time'] = d['strTime']
event['home_team'] = d['strHomeTeam']
event['away_team'] = d['strAwayTeam']
if time != 'upcoming':
if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU'):
event['golf_standings'] = d['strResult']
f = open( "csv/{}_games.json".format(time), 'w+' ) rank = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9', 'n10', 'T1', 'T2', 'T3', 'T4', 'T5',
json.dump(all_settings, f) 'T6', 'T7', 'T8', 'T9', 'T10']
f.close()
def convert(string):
string = repr(string).replace('/', '')
li = list(string.split('\\'))
return li
str3 = convert(event['golf_standings'])
players = []
for each in str3:
each = each.replace('nT', 'T', 1)
if each[:2] in rank:
try:
first_space = each.find(' ', 1)
second_space = each.find(' ', 4)
first_name = each[first_space:second_space].lstrip()
initial = first_name[0] + '.'
each = each.replace(first_name,initial)
except:
pass
interator = each.find('-')
if interator < 0:
interator = 0
interator2 = each[interator:interator + 3]
result = each.split(interator2, 1)[0] + interator2
players.append(result.rstrip())
event['golf_standings'] = players
else:
event['away_score'] = d['intAwayScore']
event['home_score'] = d['intHomeScore']
events.append(event)
leagues_info[league.upper()] = events
all_settings['leagues'] = leagues_info
f = open( "csv/{}_games.json".format(time), 'w+' )
json.dump(all_settings, f)
f.close()
except: except:
pass pass
#logf = open('log.txt', "a") #logf = open('log.txt', "a")
@ -819,7 +926,11 @@ def updateAll(api_key, weather_key, logf):
if weather_key: if weather_key:
updateWeather(weather_key, logf) updateWeather(weather_key, logf)
past_espn_time = True
past_pl_time = True
if __name__ == '__main__': if __name__ == '__main__':
logf = open("log.txt", "a") logf = open("log.txt", "a")
@ -1059,16 +1170,36 @@ if __name__ == '__main__':
# sports live # sports live
sports_time = datetime.strptime(last_updates['sports_l']['time'], "%d/%m/%Y %H:%M:%S") sports_time = datetime.strptime(last_updates['sports_l']['time'], "%d/%m/%Y %H:%M:%S")
NY_time = datetime.now(NY_zone).replace(tzinfo=None) NY_time = datetime.now(NY_zone).replace(tzinfo=None)
diff = (NY_time - sports_time).total_seconds()/60 #minutes espn_time = "17:00Z"
if last_updates['sports_l']['force'] or diff >= update_frequencies['sports']:# or msg == 'S': espn_time_est = "12:00"
# if datetime.now(pytz.utc).strftime("%H:%MZ") < espn_time:
if datetime.now(pytz.timezone('America/New_York')).strftime("%H:%M") < espn_time_est:
past_espn_time = True
if last_updates['sports_l']['force'] or (datetime.now(pytz.timezone('America/New_York')).strftime("%H:%M") >= espn_time_est and past_espn_time):# or msg == 'S':
# if last_updates['sports_l']['force'] or (datetime.now(pytz.utc).strftime("%H:%MZ") >= espn_time and past_espn_time):# or msg == 'S':
sports_time = NY_time.strftime("%d/%m/%Y %H:%M:%S") sports_time = NY_time.strftime("%d/%m/%Y %H:%M:%S")
#updateSports(api_key)
last_updates['sports_l']['time'] = sports_time last_updates['sports_l']['time'] = sports_time
last_updates['sports_l']['force'] = False last_updates['sports_l']['force'] = False
past_espn_time = False
update_process = Process(target = updateLeagueEvents, args = (api_key, 'livescore',logf)) update_process = Process(target = updateLeagueEvents, args = (api_key, 'livescore',logf))
update_process.start() update_process.start()
update_processes.append(update_process) update_processes.append(update_process)
#sports live (premier league)
pl_time = "12:00Z"
NY_time = datetime.now(NY_zone).replace(tzinfo=None)
sports_time = datetime.strptime(last_updates['sports_l']['time'], "%d/%m/%Y %H:%M:%S")
if datetime.now(pytz.utc).strftime("%H:%MZ") < pl_time:
past_pl_time = True
if datetime.now(pytz.utc).strftime("%H:%MZ") >= pl_time and past_pl_time:# or msg == 'S':
sports_time = NY_time.strftime("%d/%m/%Y %H:%M:%S")
past_pl_time = False
last_updates['sports_l']['time'] = sports_time
last_updates['sports_l']['force'] = False
update_process = Process(target = updatePLtime)
update_process.start()
update_processes.append(update_process)
# sports past # sports past
sports_time = datetime.strptime(last_updates['sports_p']['time'], "%d/%m/%Y %H:%M:%S") sports_time = datetime.strptime(last_updates['sports_p']['time'], "%d/%m/%Y %H:%M:%S")
NY_time = datetime.now(NY_zone).replace(tzinfo=None) NY_time = datetime.now(NY_zone).replace(tzinfo=None)