Skip to content

Commit

Permalink
feat: introduced scorestr
Browse files Browse the repository at this point in the history
  • Loading branch information
jbrauck-unchained committed Mar 27, 2024
1 parent 229db5a commit 97fb85a
Show file tree
Hide file tree
Showing 4 changed files with 160 additions and 1 deletion.
8 changes: 8 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from sports.cbb.fetch_ncaa_rss import main as fetch_ncaa_rss
from sports.nfl.fetch_pff_rss import main as fetch_pff_rss
from sports.mlb.fetch_foxmlb_rss import main as fetch_foxmlb_rss
from scorestr import main as scorstr
from apscheduler.schedulers.blocking import BlockingScheduler

logging.basicConfig(level=logging.INFO)
Expand All @@ -17,6 +18,8 @@ def fetch_all_feeds():
cbb_news = fetch_ncaa_rss()
pff_news = fetch_pff_rss()
foxmlb_news = fetch_foxmlb_rss()
sports_scores = scorstr()

if philly_news:
logging.info(f"PHILLY news posted: {philly_news}")
else:
Expand All @@ -34,6 +37,11 @@ def fetch_all_feeds():
else:
logging.info("Nothing new posted for FOX MLB.")

if sports_scores:
logging.info(f"Scores posted: {sports_scores}")
else:
logging.info("Nothing new posted for scores.")

logging.info("All feeds fetched.")


Expand Down
1 change: 0 additions & 1 deletion post_note.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from dotenv import load_dotenv
from nostr.event import Event
from nostr.relay_manager import RelayManager
from nostr.message_type import ClientMessageType
from nostr.key import PrivateKey

logging.basicConfig(level=logging.INFO)
Expand Down
126 changes: 126 additions & 0 deletions scorestr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import requests
from datetime import datetime
from datetime import time
from post_note import post_note
from get_notes import get_notes
from similarity_check import deduplicate_articles
import pytz
from season_checker import seasons
import logging

logging.basicConfig(level=logging.INFO)

sports_nsecs = {
"football/nfl": "PFFNFL",
"basketball/mens-college-basketball": "NCAAMBB",
"basketball/nba": "NBA",
"baseball/mlb": "FOXMLB"
}

def fetch_data_from_api(api_url):
try:
response = requests.get(api_url)
if response.status_code == 200:
return response.json()
else:
print(f"Failed to fetch data from API. Status code: {response.status_code}")
return None
except Exception as e:
print(f"An error occurred: {e}")
return None

def time_converter(input_time_string):
# Convert the input string to a datetime object
given_datetime = datetime.strptime(input_time_string, "%Y-%m-%dT%H:%MZ")

# Convert the datetime to Eastern Time
eastern = pytz.timezone('US/Eastern')
eastern_time = given_datetime.replace(tzinfo=pytz.utc).astimezone(eastern)

# Extract just the time part in standard time format (12-hour with AM/PM)
time_in_standard = eastern_time.strftime("%I:%M %p")

return time_in_standard

def todays_slate(data, current_date):
# String init
todays_slate = f"{current_date} games:\n"

for event in data['events']:
competitions = event.get('competitions')
name = event.get('name')
time = time_converter(event.get('date'))
broadcast = competitions.get('broadcasts').get('names')[0]
todays_slate += f"\n{name} at {time} on {broadcast}\n"

return todays_slate



def main():
in_season_sports = seasons()

# Get the current date
current_date = datetime.now().date().strftime("%Y-%m-%d")
current_time = datetime.now().time()

# Game slate initializers
slate_time_start = time(7, 30)
slate_time_end = time(8, 00)


for sport in in_season_sports:
api_url = f"https://site.api.espn.com/apis/site/v2/sports/{sport}/scoreboard"
prev_notes = get_notes(sports_nsecs[sport])

data = fetch_data_from_api(api_url)
if data:
# Data initialization
date = data['day'].get('date')


if slate_time_start <= current_time <= slate_time_end and date == current_date:
logging.info(f"Fetching game slate...")
slate_post = todays_slate(data, current_date)
is_duplicate = deduplicate_articles(slate_post, prev_notes)
if is_duplicate == False:
post_note(slate_post, sports_nsecs[sport])

for event in data['events']:
competitions = event.get('competitions')
for competition in competitions:
status = competition['status']
status_name = status.get('type').get('name')
status_detail = status.get('type').get('detail')
competitors = competition.get('competitors')
if status_name == 'STATUS_HALFTIME':
halftime_note = (f"{event['name']} HALFTIME score: {competitors[0]['team']['name']} {competitors[0]['score']} - {competitors[1]['team']['name']} {competitors[1]['score']}")
is_duplicate = deduplicate_articles(halftime_note, prev_notes)
if is_duplicate == False:
post_note(fulltime_note, sports_nsecs[sport])
else:
logging.info("Duplicate article found. Not posting to Nostr.")
elif status_name == 'STATUS_FINAL':
fulltime_note = (f"{event['name']} FINAL score: {competitors[0]['team']['name']} {competitors[0]['score']} - {competitors[1]['team']['name']} {competitors[1]['score']}")
is_duplicate = deduplicate_articles(fulltime_note, prev_notes)
if is_duplicate == False:
post_note(fulltime_note, sports_nsecs[sport])
else:
logging.info("Duplicate article found. Not posting to Nostr.")
elif status_name == 'STATUS_IN_PROGRESS' and status.get('period') == 8:
fulltime_note = (f"{event['name']} {status_detail} score: {competitors[0]['team']['name']} {competitors[0]['score']} - {competitors[1]['team']['name']} {competitors[1]['score']}")
is_duplicate = deduplicate_articles(fulltime_note, prev_notes)
if is_duplicate == False:
post_note(fulltime_note, sports_nsecs[sport])
else:
logging.info("Duplicate article found. Not posting to Nostr.")
else:
print(f"Game status: {status_name}")

for event in data['events']:
print(event['name'])
else:
print("No data fetched from API.")

if __name__ == "__main__":
main()
26 changes: 26 additions & 0 deletions season_checker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from datetime import datetime
import logging

logging.basicConfig(level=logging.INFO)

def check_sports_season(sports_seasons):
today = datetime.today()
in_season_sports = []

for sport, season in sports_seasons.items():
start_date, end_date = season
if start_date <= today <= end_date:
in_season_sports.append(sport)

return in_season_sports

def seasons():
sports_seasons = {
"football/nfl": (datetime(2023, 9, 8), datetime(2024, 2, 4)),
"basketball/mens-college-basketball": (datetime(2023, 10, 1), datetime(2024, 4, 8)),
"basketball/nba": (datetime(2023, 10, 1), datetime(2024, 6, 25)),
"baseball/mlb": (datetime(2023, 10, 1), datetime(2024, 4, 8)),
}
in_season_sports = check_sports_season(sports_seasons)
logging.info(f"Sports in season: {in_season_sports}")
return in_season_sports

0 comments on commit 97fb85a

Please sign in to comment.