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)
f.close()
last_updates['stocks']['force'] = True
#last_updates['weather']['force'] = True
last_updates['sports_l']['force'] = True
f = open('csv/last_updates.json', 'w')
json.dump(last_updates, f)
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.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):
url = 'https://bm7p954xoh.execute-api.us-east-2.amazonaws.com/default/ScriptsAPI/sports?{}='.format(time)
if time == 'past':
f = open('csv/past_games.json')
elif time == 'upcoming':
f = open('csv/upcoming_games.json')
elif time == 'livescore':
f = open('csv/live_games.json')
try:
all_settings = json.load(f)
f.close()
leagues = all_settings['leagues'].keys()
leagues_info = {}
for league in leagues:
if league == 'PREMIERLEAGUE':
url += 'PREMIERLEAGUE,'
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():
events = []
for d in all_data[league]:
event = {}
event['date'] = d['dateEvent']
if time == 'livescore':
try:
leagues_info = {}
for league in all_settings['leagues']:
events = []
if league == 'NFL':
subprocess.run(["sudo", "pkill", "-f", "live_nfl.py"], shell=False)
nfl = subprocess.Popen(["python3", "live_nfl.py"], shell=False)
events.append('Filled')
leagues_info[league.upper()] = events
if league == 'NBA':
subprocess.run(["sudo", "pkill", "-f", "live_nba.py"], shell=False)
nba = subprocess.Popen(["python3", "live_nba.py"], shell=False)
events.append('Filled')
leagues_info[league.upper()] = events
if league == 'NHL':
subprocess.run(["sudo", "pkill", "-f", "live_nhl.py"], shell=False)
nhl = subprocess.Popen(["python3", "live_nhl.py"], shell=False)
events.append('Filled')
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':
event['progess'] = d['strProgress']
event['status'] = d['strStatus']
if league == 'PREMIERLEAGUE':
url += 'PREMIERLEAGUE,'
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']
event['time'] = d['strTime']
event['home_team'] = d['strHomeTeam']
event['away_team'] = d['strAwayTeam']
if time != 'upcoming':
event['away_score'] = d['intAwayScore']
event['home_score'] = d['intHomeScore']
events.append(event)
leagues_info[league.upper()] = events
all_settings['leagues'] = leagues_info
if time == 'live':
event['progess'] = d['strProgress']
event['status'] = d['strStatus']
else:
if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU'):
event['date'] = d['dateEvent']
event['event'] = d['strEvent'].replace("\u2019","'")
event['venue'] = d['strVenue'].replace("\u2019","'")
event['city'] = d['strCity'].replace("\u2019","'")
event['country'] = d['strCountry']
event['season'] = d['strSeason']
else:
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+' )
json.dump(all_settings, f)
f.close()
rank = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9', 'n10', 'T1', 'T2', 'T3', 'T4', 'T5',
'T6', 'T7', 'T8', 'T9', 'T10']
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:
pass
#logf = open('log.txt', "a")
@ -819,7 +926,11 @@ def updateAll(api_key, weather_key, logf):
if weather_key:
updateWeather(weather_key, logf)
past_espn_time = True
past_pl_time = True
if __name__ == '__main__':
logf = open("log.txt", "a")
@ -1059,16 +1170,36 @@ if __name__ == '__main__':
# sports live
sports_time = datetime.strptime(last_updates['sports_l']['time'], "%d/%m/%Y %H:%M:%S")
NY_time = datetime.now(NY_zone).replace(tzinfo=None)
diff = (NY_time - sports_time).total_seconds()/60 #minutes
if last_updates['sports_l']['force'] or diff >= update_frequencies['sports']:# or msg == 'S':
espn_time = "17:00Z"
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")
#updateSports(api_key)
last_updates['sports_l']['time'] = sports_time
last_updates['sports_l']['force'] = False
past_espn_time = False
update_process = Process(target = updateLeagueEvents, args = (api_key, 'livescore',logf))
update_process.start()
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_time = datetime.strptime(last_updates['sports_p']['time'], "%d/%m/%Y %H:%M:%S")
NY_time = datetime.now(NY_zone).replace(tzinfo=None)