Skip to content

Commit 6d47683

Browse files
authored
Merge pull request #37 from AlecM33/wildcard
wildcard command
2 parents 0934df5 + ee65954 commit 6d47683

File tree

4 files changed

+119
-21
lines changed

4 files changed

+119
-21
lines changed

commands/wildcard.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
const interactionHandlers = require('../modules/interaction-handlers.js');
2+
const { SlashCommandBuilder } = require('@discordjs/builders');
3+
4+
module.exports = {
5+
data: new SlashCommandBuilder()
6+
.setName('wildcard')
7+
.setDescription('View the current wildcard standings.'),
8+
async execute (interaction) {
9+
try {
10+
await interactionHandlers.wildcardHandler(interaction);
11+
} catch (e) {
12+
console.error(e);
13+
if (interaction.deferred && !interaction.replied) {
14+
await interaction.followUp('There was an error processing this command. If it persists, please reach out to the developer.');
15+
} else if (!interaction.replied) {
16+
await interaction.reply('There was an error processing this command. If it persists, please reach out to the developer.');
17+
}
18+
}
19+
}
20+
};

modules/MLB-API-util.js

+8
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,11 @@ const endpoints = {
9999
},
100100
players: () => {
101101
return 'https://statsapi.mlb.com/api/v1/sports/1/players?fields=people,fullName,lastName,id,currentTeam,primaryPosition,name,code,abbreviation';
102+
},
103+
wildcard: () => {
104+
return 'https://bdfed.stitch.mlbinfra.com/bdfed/transform-mlb-standings?&splitPcts=false&numberPcts=false&standingsView=division&sortTemplate=3&season=' +
105+
(new Date().getFullYear()) + '&leagueIds=103,104&standingsTypes=wildCard&contextTeamId=&date=' +
106+
((new Date()).toISOString().split('T')[0]) + '&hydrateAlias=noSchedule&sortDivisions=201,202,200,204,205,203&sortLeagues=103,104,115,114&sortSports=1';
102107
}
103108
};
104109

@@ -254,5 +259,8 @@ module.exports = {
254259
},
255260
players: async () => {
256261
return (await fetch(endpoints.players())).json();
262+
},
263+
wildcard: async () => {
264+
return (await fetch(endpoints.wildcard())).json();
257265
}
258266
};

modules/command-util.js

+73-21
Original file line numberDiff line numberDiff line change
@@ -223,27 +223,7 @@ module.exports = {
223223
},
224224

225225
buildStandingsTable: async (standings, divisionName) => {
226-
const centralMap = standings.teamRecords.map(teamRecord => {
227-
return {
228-
name: teamRecord.team.name,
229-
wins: teamRecord.leagueRecord.wins,
230-
losses: teamRecord.leagueRecord.losses,
231-
pct: teamRecord.leagueRecord.pct,
232-
gamesBack: teamRecord.gamesBack,
233-
homeRecord: (() => {
234-
const home = teamRecord.records.splitRecords.find(record => record.type === 'home');
235-
return home.wins + '-' + home.losses;
236-
})(),
237-
awayRecord: (() => {
238-
const away = teamRecord.records.splitRecords.find(record => record.type === 'away');
239-
return away.wins + '-' + away.losses;
240-
})(),
241-
lastTen: (() => {
242-
const l10 = teamRecord.records.splitRecords.find(record => record.type === 'lastTen');
243-
return l10.wins + '-' + l10.losses;
244-
})()
245-
};
246-
});
226+
const centralMap = mapStandings(standings);
247227
const table = new AsciiTable(divisionName + '\n');
248228
table.setHeading('Team', 'W-L', 'GB', 'L10');
249229
centralMap.forEach((entry) => table.addRow(
@@ -256,6 +236,37 @@ module.exports = {
256236
return (await getScreenshotOfHTMLTables([table]));
257237
},
258238

239+
buildWildcardTable: async (divisionLeaders, wildcard, leagueName) => {
240+
const divisionLeadersMap = mapStandings(divisionLeaders);
241+
const wildcardMap = mapStandings(wildcard, true);
242+
const table = new AsciiTable(leagueName + ' Wild Card \n');
243+
table.setHeading('Team', 'W-L', 'WCGB', 'L10', 'STRK');
244+
divisionLeadersMap.forEach((entry) => table.addRow(
245+
entry.name,
246+
entry.wins + '-' + entry.losses,
247+
'-',
248+
entry.lastTen,
249+
entry.streak
250+
));
251+
let wildCardDivided = false;
252+
table.addRow('', '', '', '', '');
253+
wildcardMap.forEach((entry) => {
254+
if (!wildCardDivided && entry.gamesBack !== '-' && !entry.gamesBack.includes('+')) {
255+
wildCardDivided = true;
256+
table.addRow('', '', '', '', '');
257+
}
258+
table.addRow(
259+
entry.name,
260+
entry.wins + '-' + entry.losses,
261+
entry.gamesBack,
262+
entry.lastTen,
263+
entry.streak
264+
);
265+
});
266+
table.removeBorder();
267+
return (await getScreenshotOfHTMLTables([table]));
268+
},
269+
259270
getStatcastData: (savantText) => {
260271
const statcast = /statcast: \[(?<statcast>.+)],/.exec(savantText)?.groups.statcast;
261272
const metricSummaries = /metricSummaryStats: {(?<metricSummaries>.+)},/.exec(savantText)?.groups.metricSummaries;
@@ -858,6 +869,37 @@ module.exports = {
858869
}
859870
};
860871

872+
function mapStandings (standings, wildcard = false) {
873+
return standings.teamRecords.map(teamRecord => {
874+
return {
875+
name: teamRecord.team.name + (standings.standingsType === 'divisionLeaders' ? ' - ' + getDivisionAbbreviation(teamRecord.team.division.name) : ''),
876+
wins: (teamRecord.leagueRecord?.wins === undefined ? teamRecord.wins : teamRecord.leagueRecord.wins),
877+
losses: (teamRecord.leagueRecord?.losses === undefined ? teamRecord.losses : teamRecord.leagueRecord.losses),
878+
pct: (teamRecord.leagueRecord?.pct === undefined ? teamRecord.pct : teamRecord.leagueRecord.pct),
879+
gamesBack: (wildcard ? teamRecord.wildCardGamesBack : teamRecord.gamesBack),
880+
homeRecord: (teamRecord.record_home
881+
? teamRecord.record_home
882+
: (() => {
883+
const home = teamRecord.records.splitRecords.find(record => record.type === 'home');
884+
return home.wins + '-' + home.losses;
885+
})()),
886+
awayRecord: (teamRecord.record_away
887+
? teamRecord.record_away
888+
: (() => {
889+
const away = teamRecord.records.splitRecords.find(record => record.type === 'away');
890+
return away.wins + '-' + away.losses;
891+
})()),
892+
lastTen: (teamRecord.record_lastTen
893+
? teamRecord.record_lastTen
894+
: (() => {
895+
const l10 = teamRecord.records.splitRecords.find(record => record.type === 'lastTen');
896+
return l10.wins + '-' + l10.losses;
897+
})()),
898+
streak: teamRecord.streak
899+
};
900+
});
901+
}
902+
861903
function getPitchCollections (dom) {
862904
const pitches = [];
863905
const percentages = [];
@@ -1119,3 +1161,13 @@ function calculateRoundedPercentileFromNormalDistribution (metric, value, mean,
11191161
(shouldInvert ? (1.00 - ztable((value - mean) / standardDeviation)) : ztable((value - mean) / standardDeviation)) * 100
11201162
);
11211163
}
1164+
1165+
function getDivisionAbbreviation (division) {
1166+
if (division.toLowerCase().includes('east')) {
1167+
return 'E';
1168+
} else if (division.toLowerCase().includes('west')) {
1169+
return 'W';
1170+
} else {
1171+
return 'C';
1172+
}
1173+
}

modules/interaction-handlers.js

+18
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,22 @@ module.exports = {
116116
});
117117
},
118118

119+
wildcardHandler: async (interaction) => {
120+
await interaction.deferReply();
121+
console.info(`WILDCARD command invoked by guild: ${interaction.guildId}`);
122+
const team = await mlbAPIUtil.team(process.env.TEAM_ID);
123+
const leagueId = team.teams[0].league.id;
124+
const leagueName = team.teams[0].league.name;
125+
const wildcard = (await mlbAPIUtil.wildcard()).records
126+
.find(record => record.standingsType === 'wildCard' && record.league === leagueId);
127+
const divisionLeaders = (await mlbAPIUtil.wildcard()).records
128+
.find(record => record.standingsType === 'divisionLeaders' && record.league === leagueId);
129+
await interaction.followUp({
130+
ephemeral: false,
131+
files: [new AttachmentBuilder((await commandUtil.buildWildcardTable(divisionLeaders, wildcard, leagueName)), { name: 'wildcard.png' })]
132+
});
133+
},
134+
119135
subscribeGamedayHandler: async (interaction) => {
120136
console.info(`SUBSCRIBE GAMEDAY command invoked by guild: ${interaction.guildId}`);
121137
if (!interaction.member.roles.cache.some(role => globals.ADMIN_ROLES.includes(role.name))) {
@@ -442,6 +458,7 @@ module.exports = {
442458
},
443459

444460
batterSavantHandler: async (interaction) => {
461+
console.info(`BATTER SAVANT command invoked by guild: ${interaction.guildId}`);
445462
await interaction.deferReply();
446463
const playerName = interaction.options.getString('player')?.trim();
447464
const playerResult = await commandUtil.getPlayerFromUserInputOrLiveFeed(playerName, interaction, 'Batter');
@@ -474,6 +491,7 @@ module.exports = {
474491
},
475492

476493
pitcherSavantHandler: async (interaction) => {
494+
console.info(`PITCHER SAVANT command invoked by guild: ${interaction.guildId}`);
477495
await interaction.deferReply();
478496
const playerName = interaction.options.getString('player')?.trim();
479497
const playerResult = await commandUtil.getPlayerFromUserInputOrLiveFeed(playerName, interaction, 'Pitcher');

0 commit comments

Comments
 (0)