-
Notifications
You must be signed in to change notification settings - Fork 0
/
nba.coffee
378 lines (314 loc) · 9.32 KB
/
nba.coffee
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# Description:
# A hubot script for NBA stats
#
# Dependencies:
#
# Configuration:
#
# Commands:
# hubot nba player <player name> - view individual stats
# hubot nba team <team name> - view team stats
# hubot nba roster <team name> - view list team's players
# hubot nba coaches <team name> - view list team's coaches
# hubot nba scores - view the scores and schedules of today's games
# hubot nba standings - view Eastern and Western conference standings
# hubot nba hustle - view hustle stat leaders
#
# Author:
# brandly
#
nba = require 'nba'
request = require 'superagent'
_ = require 'lodash'
Case = require 'case'
module.exports = (robot) ->
robot.respond /nba player (.*)/, (res) ->
name = res.match[1]
PlayerID = nba.playerIdFromName name
if not PlayerID?
res.reply "Couldn't find player with name \"#{name}\""
return
getPlayerSummary PlayerID, (error, summary) ->
res.reply error or summary
robot.respond /nba team (.*)/, (res) ->
name = res.match[1]
TeamId = nba.teamIdFromName name
if not TeamId?
res.reply "Couldn't find team with name \"#{name}\""
return
nba.stats.teamStats({ TeamId }).then (data) ->
if not data.length
res.reply "Couldn't find stats for team \"#{TeamId}\""
return
info = data[0]
res.reply """
#{info.teamName} (#{info.w}-#{info.l})
#{info.pts}pts, #{info.ast}ast, #{info.reb}reb
"""
, (reason) ->
res.reply """
Error getting team stats
#{JSON.stringify reason, null, 2}
"""
robot.respond /nba roster (.*)/, (res) ->
name = res.match[1]
TeamID = nba.teamIdFromName name
if not TeamID?
res.reply "Couldn't find team with name \"#{name}\""
return
nba.stats.commonTeamRoster({ TeamID }).then ({ commonTeamRoster }) ->
listings = commonTeamRoster.map (player) ->
heightSplits = player.height.split '-'
height = "#{heightSplits[0]}'#{heightSplits[1]}\""
"""
##{player.num} #{player.player} (#{player.position})
#{height} #{player.weight}lbs
#{player.age} years old (#{player.birthDate})
#{player.school or ''}
""".trim()
res.reply listings.join('\n\n')
, (reason) ->
res.reply """
Error getting team roster
#{JSON.stringify reason, null, 2}
"""
robot.respond /nba coaches (.*)/, (res) ->
name = res.match[1]
TeamID = nba.teamIdFromName name
if not TeamID?
res.reply "Couldn't find team with name \"#{name}\""
return
nba.stats.commonTeamRoster({ TeamID }).then ({ coaches }) ->
listings = coaches.map (coach) ->
"""
#{coach.coachName}, #{coach.coachType}
#{coach.school or ''}
""".trim()
res.reply listings.join('\n\n')
, (reason) ->
res.reply """
Error getting team coaches
#{JSON.stringify reason, null, 2}
"""
robot.respond /nba scores/, (res) ->
getContext = (game) ->
if game.hasBegun
return "#{game.away.score} - #{game.home.score}"
else if game.series
return game.series
else
return "First matchup"
getTeamNames = (game) ->
{ away, home } = game
if game.isOver
homeTeamWon = home.score > away.score
if homeTeamWon
"#{away.name} at *#{home.name}*"
else
"*#{away.name}* at #{home.name}"
else
"#{away.name} at #{home.name}"
getScores (err, scores) ->
response = scores.map (game) ->
"""
#{getTeamNames(game)}
#{game.status} | #{getContext(game)}
"""
res.reply response.join('\n\n')
robot.respond /nba standing(s?)/, (res) ->
displayTeam = (t) ->
behind = if t.gamesBehind is '-' then '' else "(#{t.gamesBehind}GB)"
"""
##{t.seed} #{t.name} #{behind}
#{t.wins}W - #{t.losses}L (#{t.winPercent})
"""
getConferenceStandings (err, conferences) ->
response = conferences.map (conference) ->
"""
#{conference.name}
#{conference.teams.map(displayTeam).join('\n\n')}
"""
res.reply response.join('\n\n\n')
robot.respond /nba hustle/, (res) ->
hustleLeaders (error, stats) ->
if error?
res.reply """
Error getting hustle leaders
#{JSON.stringify error, null, 2}
"""
return
commonKeys = [
'playerId'
'playerName'
'teamId'
'teamAbbreviation'
'age'
'rank'
]
statLeaderLists = stats.map (stat) ->
listings = stat.leaders.map (leader) ->
countKey = Object.keys(leader).find (key) ->
!_.includes(commonKeys, key)
{
playerName,
teamAbbreviation
} = leader
"""
#{playerName} (#{teamAbbreviation}) #{leader[countKey]}
"""
"""
> #{stat.name}
#{listings.join '\n'}
"""
res.reply(statLeaderLists.join '\n\n')
displayAverages = (avg) ->
toTable [
"#{avg.gp} GP"
"#{avg.min} MIN"
"#{avg.pts} PTS"
"#{avg.fgm} FGM"
"#{avg.fga} FGA"
"#{avg.fgPct} FG%"
"#{avg.fG3M} 3PM"
"#{avg.fG3A} 3PA"
"#{avg.fg3Pct} 3P%"
"#{avg.ftm} FTM"
"#{avg.fta} FTA"
"#{avg.ftPct} FT%"
"#{avg.oreb} OREB"
"#{avg.dreb} DREB"
"#{avg.reb} REB"
"#{avg.ast} AST"
"#{avg.stl} STL"
"#{avg.blk} BLK"
]
toTable = (stats) ->
columnCount = 2
rowsPerColumn = stats.length / columnCount
listOfColumns = _.range(columnCount).map (index) ->
stats.slice(index * rowsPerColumn, (index + 1) * rowsPerColumn)
paddedColumns = listOfColumns.map padColumn
joinedRows = _.range(paddedColumns[0].length).map (rowIndex) ->
_.range(columnCount)
.map (columnIndex) ->
paddedColumns[columnIndex][rowIndex]
.join ' | '
"```#{joinedRows.join '\n'}```"
padColumn = (column) ->
widestColumn = Math.max.apply(Math, column.map (item) -> item.length)
column.map (item) ->
while item.length < widestColumn
index = item.indexOf(' ')
item = item.slice(0, index) + ' ' + item.slice(index, item.length)
item
currentScoresUrl = [
'http://data.nba.com',
'/data/5s/v2015/json/mobile_teams/nba'
'/2022/scores/00_todays_scores.json'
].join ''
requestCurrentScores = (cb) ->
request
.get(currentScoresUrl)
.end (err, res) ->
cb err, JSON.parse(res.text)
getScores = (cb) ->
requestCurrentScores (err, data) ->
return cb(err, null) if err?
formattedScores = data.gs.g.map (game) ->
{
hasBegun: !!game.cl
isOver: game.stt is 'Final'
status: buildStatus(game)
away: buildTeam(game.v)
home: buildTeam(game.h)
series: game.lm.seri
}
cb null, formattedScores
buildTeam = (team) ->
{
id: team.tid,
city: team.tc,
name: team.tn,
abbrev: team.ta,
score: team.s
}
buildStatus = (game) ->
if game.stt is 'Final'
return 'Final'
else if not game.cl? or game.cl is '00:00.0'
return game.stt
else
return "#{game.cl} - #{game.stt}"
conferenceStandingsUrl = [
'http://cdn.espn.go.com'
'/core/nba/standings?xhr=1&device=desktop'
].join ''
requestConferenceStandings = (cb) ->
request
.get(conferenceStandingsUrl)
.end (err, res) ->
cb err, JSON.parse(res.text)
getConferenceStandings = (cb) ->
requestConferenceStandings (err, data) ->
return cb(err, null) if err?
conferences = data.content.standings.groups.map buildConference
cb null, conferences
buildConference = (data) ->
{
name: data.name,
teams: data.standings.entries.map buildTeamStanding
}
buildTeamStanding = (data) ->
getStat = (stats, name) ->
matches = stats.filter (stat) -> stat.name is name
return matches[0].displayValue
{ team, stats } = data
return {
name: team.name,
city: team.location,
seed: team.seed,
abbrev: team.abbreviation,
wins: getStat(stats, 'wins'),
losses: getStat(stats, 'losses'),
winPercent: getStat(stats, 'winPercent'),
gamesBehind: getStat(stats, 'gamesBehind')
}
getPlayerProfile = (opts) ->
nba.stats.playerProfile(opts)
.then (profile) ->
regularSeason = profile.seasonTotalsRegularSeason
averages = regularSeason[regularSeason.length - 1]
return {
averages
}
getPlayerSummary = (PlayerID, callback) ->
Promise.all([
nba.stats.playerInfo({ PlayerID }),
getPlayerProfile({ PlayerID })
]).then ([playerInfo, playerProfile]) ->
info = playerInfo.commonPlayerInfo[0]
{ averages } = playerProfile
callback null, """
#{info.displayFirstLast}, #{info.teamName} #{info.position}
#{info.height} #{info.weight}lbs
Season averages
#{displayAverages(averages)}
http://stats.nba.com/player/#!/#{PlayerID}/career/
"""
, (reason) ->
callback """
Error getting player stats
#{JSON.stringify reason, null, 2}
"""
hustleLeaders = (callback) ->
nba.stats.playerHustleLeaders().then (val) ->
stats = val.resultSets.map (set) ->
name: Case.title(set.name).replace 'Player ', ''
leaders: set.rowSet.map (row) ->
_.zip(set.headers, row)
.reduce (store, val) ->
store[Case.camel val[0]] = val[1]
return store
, {}
callback null, stats
, (error) -> callback(error)