-
Notifications
You must be signed in to change notification settings - Fork 3
/
nba.py
executable file
·92 lines (80 loc) · 2.32 KB
/
nba.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/usr/bin/env python
import json
import url_opener
NBA_BLUE = "#3965A4"
def get_logo_url(team_code):
"""
>>> get_team_logo_url("GSW")
'http://z.cdn.turner.com/nba/nba/.element/img/4.0/global/logos/512x512/bg.white/png/GSW.png'
"""
return ('http://z.cdn.turner.com/nba/nba/.element/img/4.0/'
'global/logos/512x512/bg.white/png/%s.png' % team_code)
def get_stats(date):
opener = url_opener.create()
ref_url = 'http://stats.nba.com/scores/'
opener.addheaders = [('Referer', ref_url)]
url = ('http://stats.nba.com/stats/scoreboard/?GameDate='
'%(date)s&LeagueID=00&DayOffset=0' % {'date': date})
response = opener.open(url)
stats = json.load(response)
return stats
def get_scores_for_team(stats, team_code):
times = stats['resultSets'][0]['rowSet']
games = stats['resultSets'][1]['rowSet']
team_score = None
game_id = None
for game in games:
if get_team_code(game) == team_code:
game_id = get_game_id(game)
team_score = game
break
if game_id is None:
return None
opp_score = None
for game in games:
if get_team_code(game) != team_code and get_game_id(game) == game_id:
opp_score = game
break
period = None
for time in times:
if time[2] == game_id:
period = time
return (team_score, opp_score, period)
def get_team_code(score):
return score[4]
def get_game_id(score):
return score[2]
def get_points(score):
return score[21]
def get_team_name(score):
return score[5]
def get_period_time(period):
return period[10].strip()
def get_period_name(period):
return period[4]
def format_scores(scores):
team_score, opp_score, period = scores
team_pts = get_points(team_score)
opp_pts = get_points(opp_score)
if team_pts < opp_pts:
logo = get_logo_url(get_team_code(opp_score))
else:
logo = get_logo_url(get_team_code(team_score))
score = '%(team_name)s %(team_pts)s-%(opp_pts)s %(opp_name)s' % {
'team_name': get_team_name(team_score),
'opp_name': get_team_name(opp_score),
'team_pts': team_pts,
'opp_pts': opp_pts,
}
period_info = ' '.join((get_period_time(period), get_period_name(period)))
return {
"attachments": [
{
"title": score,
"text": period_info,
"thumb_url": logo,
"color": NBA_BLUE,
"fallback": " ".join((score, period_info)),
}
]
}