import requests
import json
import time
from datetime import datetime
import sys
def fetch_live_scores():
"""
Fetches live sports events from TheSportsDB API.
Returns a list of live events or empty list if none.
"""
url = "http://www.thesportsdb.com/api/v1/json/1/eventslive.php"
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()
return data.get('events', [])
except requests.exceptions.RequestException as e:
print(f"Error fetching data: {e}", file=sys.stderr)
return []
except json.JSONDecodeError as e:
print(f"Error parsing JSON: {e}", file=sys.stderr)
return []
def display_scores(events):
"""
Displays the live scores in a formatted way.
"""
if not events:
print("No live events right now. Check back later!")
return
print(f"\n{'='*80}")
print(f"🔴 LIVE SPORTS SCORES (Updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')})")
print(f"{'='*80}\n")
for event in events:
home_team = event.get('strHomeTeam', 'N/A')
away_team = event.get('strAwayTeam', 'N/A')
league = event.get('strLeague', 'N/A')
sport = event.get('strSport', 'N/A')
home_score = event.get('intHomeScore')
away_score = event.get('intAwayScore')
match_time = event.get('strTime', 'N/A') # e.g., "45'" or "HT"
# Format scores
home_score_str = str(home_score) if home_score is not None else '-'
away_score_str = str(away_score) if away_score is not None else '-'
print(f"🏆 {league} ({sport})")
print(f" {away_team} {away_score_str} - {home_score_str} {home_team}")
print(f" ⏱️ {match_time}")
print()
print(f"{'='*80}")
def main():
print("🚀 Live Sports Scores Fetcher")
print("Press Ctrl+C to exit.\n")
while True:
try:
events = fetch_live_scores()
display_scores(events)
print("Refreshing in 30 seconds...\n")
time.sleep(30)
except KeyboardInterrupt:
print("\n👋 Goodbye!")
sys.exit(0)
except Exception as e:
print(f"Unexpected error: {e}", file=sys.stderr)
time.sleep(30)
if __name__ == "__main__":
main()
How to Run:
- Install dependencies (if not already installed):
pip install requests
- Run the script:
python live_scores.py
- The program will fetch live scores from TheSportsDB API (free, no API key needed), display them across various sports (soccer, basketball, etc.), and auto-refresh every 30 seconds. Press
Ctrl+C to exit.
Features:
- Multi-sport support: Soccer, NFL, NBA, etc. (whatever is live).
- Real-time updates: Shows current score, match time (e.g., "45'"), league.
- Error handling: Gracefully handles network issues or no live games.
- Clean CLI output: Formatted with emojis and timestamps for readability.
- Minimal dependencies: Only
requests.
Note: Live data depends on the API's availability. If no events are live, it will say so. For production, consider rate limits or a paid API for more reliability.