2025-12-08 16:31:30 +03:00

318 lines
8.4 KiB
TypeScript

/**
* ESPN API Integration
* Uses ESPN's hidden API endpoints for sports data
* No API key required!
*/
import axios from 'axios'
const ESPN_BASE = 'http://site.api.espn.com/apis/site/v2/sports'
export type ESPNSport =
| 'football/nfl'
| 'football/college-football'
| 'basketball/nba'
| 'basketball/wnba'
| 'basketball/mens-college-basketball'
| 'basketball/womens-college-basketball'
| 'baseball/mlb'
| 'baseball/college-baseball'
| 'hockey/nhl'
| 'soccer'
export interface ESPNConfig {
sport: ESPNSport
league?: string // For soccer (e.g., 'eng.1' for EPL, 'usa.1' for MLS)
gameId?: string
date?: string // YYYYMMDD format
teamId?: string
homeTeam?: string
awayTeam?: string
comparisonType?: 'home_wins' | 'away_wins' | 'draw' | 'over_under' | 'exact_score'
targetScore?: number // For over/under
}
export interface ESPNGame {
id: string
name: string
shortName: string
date: string
status: {
type: {
completed: boolean
description: string
}
}
competitions: Array<{
competitors: Array<{
id: string
team: {
id: string
name: string
abbreviation: string
displayName: string
}
score: string
homeAway: 'home' | 'away'
winner: boolean
}>
}>
}
/**
* Get scoreboard for a sport/date
*/
export async function getESPNScoreboard(
sport: ESPNSport,
date?: string,
league?: string
): Promise<ESPNGame[]> {
try {
const sportPath = league ? `${sport}/${league}` : sport
const url = `${ESPN_BASE}/${sportPath}/scoreboard`
const params: any = {}
if (date) params.dates = date
const response = await axios.get(url, { params })
return response.data.events || []
} catch (error) {
console.error('Failed to get ESPN scoreboard:', error)
return []
}
}
/**
* Get specific game details
*/
export async function getESPNGame(
sport: ESPNSport,
gameId: string,
league?: string
): Promise<ESPNGame | null> {
try {
const sportPath = league ? `${sport}/${league}` : sport
const url = `${ESPN_BASE}/${sportPath}/summary`
const response = await axios.get(url, {
params: { event: gameId }
})
return response.data.header || null
} catch (error) {
console.error(`Failed to get ESPN game ${gameId}:`, error)
return null
}
}
/**
* Find game by team names
*/
export async function findESPNGame(
sport: ESPNSport,
homeTeam: string,
awayTeam: string,
date?: string,
league?: string
): Promise<ESPNGame | null> {
const games = await getESPNScoreboard(sport, date, league)
const normalizeTeam = (name: string) => name.toLowerCase().replace(/[^a-z]/g, '')
const homeNorm = normalizeTeam(homeTeam)
const awayNorm = normalizeTeam(awayTeam)
for (const game of games) {
const competitors = game.competitions[0]?.competitors
if (!competitors) continue
const home = competitors.find(c => c.homeAway === 'home')
const away = competitors.find(c => c.homeAway === 'away')
if (home && away) {
const homeMatch = normalizeTeam(home.team.displayName)
const awayMatch = normalizeTeam(away.team.displayName)
if (homeMatch.includes(homeNorm) && awayMatch.includes(awayNorm)) {
return game
}
}
}
return null
}
/**
* Verify poll result using ESPN data
*/
export async function verifyESPNPoll(
config: ESPNConfig,
pollEndTime: number
): Promise<{ correct: boolean; optionIndex: number; proof: any }> {
try {
let game: ESPNGame | null = null
// Get game data
if (config.gameId) {
game = await getESPNGame(config.sport, config.gameId, config.league)
} else if (config.homeTeam && config.awayTeam) {
game = await findESPNGame(
config.sport,
config.homeTeam,
config.awayTeam,
config.date,
config.league
)
} else {
throw new Error('Either gameId or team names required')
}
if (!game) {
throw new Error('Game not found')
}
// Check if game is completed
if (!game.status.type.completed) {
throw new Error('Game not completed yet')
}
const competitors = game.competitions[0]?.competitors
if (!competitors || competitors.length !== 2) {
throw new Error('Invalid game data')
}
const home = competitors.find(c => c.homeAway === 'home')!
const away = competitors.find(c => c.homeAway === 'away')!
const homeScore = parseInt(home.score)
const awayScore = parseInt(away.score)
let correctOptionIndex = -1
// Determine correct option based on comparison type
switch (config.comparisonType) {
case 'home_wins':
correctOptionIndex = homeScore > awayScore ? 0 : homeScore < awayScore ? 1 : 2
break
case 'away_wins':
correctOptionIndex = awayScore > homeScore ? 0 : awayScore < homeScore ? 1 : 2
break
case 'draw':
correctOptionIndex = homeScore === awayScore ? 0 : 1
break
case 'over_under':
if (config.targetScore !== undefined) {
const totalScore = homeScore + awayScore
correctOptionIndex = totalScore > config.targetScore ? 0 : 1
}
break
case 'exact_score':
// Would need to compare against specific score options
break
default:
// Default: home wins = 0, away wins = 1, draw = 2
if (homeScore > awayScore) {
correctOptionIndex = 0
} else if (awayScore > homeScore) {
correctOptionIndex = 1
} else {
correctOptionIndex = 2
}
}
return {
correct: correctOptionIndex >= 0,
optionIndex: correctOptionIndex,
proof: {
source: 'espn',
sport: config.sport,
gameId: game.id,
gameName: game.name,
homeTeam: home.team.displayName,
awayTeam: away.team.displayName,
homeScore,
awayScore,
winner: home.winner ? 'home' : away.winner ? 'away' : 'draw',
timestamp: Date.now(),
},
}
} catch (error) {
console.error('ESPN verification failed:', error)
throw error
}
}
/**
* Common sports and leagues
*/
export const ESPN_SPORTS = {
NFL: { sport: 'football/nfl' as ESPNSport, name: 'NFL' },
COLLEGE_FOOTBALL: { sport: 'football/college-football' as ESPNSport, name: 'College Football' },
NBA: { sport: 'basketball/nba' as ESPNSport, name: 'NBA' },
WNBA: { sport: 'basketball/wnba' as ESPNSport, name: 'WNBA' },
MENS_COLLEGE_BASKETBALL: { sport: 'basketball/mens-college-basketball' as ESPNSport, name: "Men's College Basketball" },
WOMENS_COLLEGE_BASKETBALL: { sport: 'basketball/womens-college-basketball' as ESPNSport, name: "Women's College Basketball" },
MLB: { sport: 'baseball/mlb' as ESPNSport, name: 'MLB' },
COLLEGE_BASEBALL: { sport: 'baseball/college-baseball' as ESPNSport, name: 'College Baseball' },
NHL: { sport: 'hockey/nhl' as ESPNSport, name: 'NHL' },
}
export const ESPN_SOCCER_LEAGUES = {
EPL: { league: 'eng.1', name: 'English Premier League' },
LA_LIGA: { league: 'esp.1', name: 'La Liga' },
BUNDESLIGA: { league: 'ger.1', name: 'Bundesliga' },
SERIE_A: { league: 'ita.1', name: 'Serie A' },
LIGUE_1: { league: 'fra.1', name: 'Ligue 1' },
MLS: { league: 'usa.1', name: 'MLS' },
CHAMPIONS_LEAGUE: { league: 'uefa.champions', name: 'UEFA Champions League' },
WORLD_CUP: { league: 'fifa.world', name: 'FIFA World Cup' },
}
/**
* Example poll configurations
*/
export const EXAMPLE_ESPN_POLLS = {
nflGame: {
question: 'Chiefs vs 49ers - Who wins?',
sport: 'football/nfl' as ESPNSport,
homeTeam: 'Kansas City Chiefs',
awayTeam: 'San Francisco 49ers',
comparisonType: 'home_wins' as const,
options: [
{ text: 'Chiefs Win', emoji: '馃張' },
{ text: '49ers Win', emoji: '馃敶' },
{ text: 'Draw', emoji: '馃' },
],
},
nbaOverUnder: {
question: 'Lakers vs Warriors - Over/Under 220 points?',
sport: 'basketball/nba' as ESPNSport,
homeTeam: 'Los Angeles Lakers',
awayTeam: 'Golden State Warriors',
comparisonType: 'over_under' as const,
targetScore: 220,
options: [
{ text: 'Over 220', emoji: '猬嗭笍' },
{ text: 'Under 220', emoji: '猬囷笍' },
],
},
soccerMatch: {
question: 'Man City vs Liverpool - Winner?',
sport: 'soccer' as ESPNSport,
league: 'eng.1', // EPL
homeTeam: 'Manchester City',
awayTeam: 'Liverpool',
options: [
{ text: 'Man City', emoji: '馃數' },
{ text: 'Liverpool', emoji: '馃敶' },
{ text: 'Draw', emoji: '馃' },
],
},
}