diff --git a/.vscode/settings.json b/.vscode/settings.json index 862f08758..3c3d7a00f 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -6,6 +6,7 @@ "ownedtanks", "Resvg", "searchplayers", + "SKLLD", "Smri", "strvk", "tankopedia", diff --git a/package.json b/package.json index 3ee9576c2..5b17c3ff9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blitzkrieg", - "version": "1.5.4", + "version": "1.6.0", "description": "", "main": "index.js", "type": "module", diff --git a/src/commands/debug.ts b/src/commands/debug.ts index e7630f90d..278060b45 100644 --- a/src/commands/debug.ts +++ b/src/commands/debug.ts @@ -46,7 +46,5 @@ export default { ), ], }); - - console.log("Displaying bot's debug information"); }, } satisfies CommandRegistry; diff --git a/src/commands/eligible.ts b/src/commands/eligible.ts new file mode 100644 index 000000000..f4091a0b3 --- /dev/null +++ b/src/commands/eligible.ts @@ -0,0 +1,175 @@ +import { SlashCommandBuilder } from 'discord.js'; +import getBlitzAccount from '../core/blitz/getBlitzAccount.js'; +import getWN8 from '../core/blitz/getWN8.js'; +import getWargamingResponse from '../core/blitz/getWargamingResponse.js'; +import sumStats from '../core/blitz/sumStats.js'; +import { tankopedia } from '../core/blitz/tankopedia.js'; +import getPeriodNow from '../core/blitzstars/getPeriodNow.js'; +import getPeriodicStart from '../core/blitzstars/getPeriodStart.js'; +import getTankStatsOverTime from '../core/blitzstars/getTankStatsOverTime.js'; +import { tankAverages } from '../core/blitzstars/tankAverages.js'; +import cleanTable, { TableInput } from '../core/interaction/cleanTable.js'; +import cmdName from '../core/interaction/cmdName.js'; +import negativeEmbed from '../core/interaction/negativeEmbed.js'; +import positiveEmbed from '../core/interaction/positiveEmbed.js'; +import addUsernameOption from '../core/options/addUsernameOption.js'; +import { args } from '../core/process/args.js'; +import { CommandRegistry } from '../events/interactionCreate.js'; +import { AccountInfo } from '../types/accountInfo.js'; + +export type SkilledClan = 'SKLLD' | 'SMRI'; + +export const SKILLED_CLANS: Record = { + SKLLD: 'Skilled', + SMRI: 'Samurai', +}; + +export default { + inProduction: true, + inDevelopment: false, + inPublic: false, + + command: new SlashCommandBuilder() + .setName(cmdName('eligible')) + .setDescription('Checks eligibility for any Skilled clan') + .addStringOption((option) => + option + .setName('clan') + .setDescription('The clan to check') + .setChoices( + { + name: SKILLED_CLANS.SKLLD, + value: 'SKLLD' satisfies SkilledClan, + }, + { name: SKILLED_CLANS.SMRI, value: 'SMRI' satisfies SkilledClan }, + ) + .setRequired(true), + ) + .addStringOption(addUsernameOption), + + async execute(interaction) { + const clan = interaction.options.getString('clan') as SkilledClan; + const { id, server } = await getBlitzAccount(interaction); + const accountInfo = await getWargamingResponse( + `https://api.wotblitz.${server}/wotb/account/info/?application_id=${args['wargaming-application-id']}&account_id=${id}`, + ); + const problems: TableInput = []; + const title = `${accountInfo[id].nickname}'s eligibility for ${SKILLED_CLANS[clan]}`; + let isEligible = false; + let body = ''; + + if (clan === 'SKLLD') { + const tankStatsOverTime = await getTankStatsOverTime( + interaction, + server, + id, + getPeriodicStart('30'), + getPeriodNow(), + ); + const entries = Object.entries(tankStatsOverTime); + const stats = sumStats(entries.map(([, stats]) => stats)); + const averageTier = + entries.reduce((accumulator, [tankIdString, stats]) => { + const tankId = parseInt(tankIdString); + const tankTier = tankopedia[tankId].tier; + + return accumulator + tankTier * stats.battles; + }, 0) / stats.battles; + const WN8 = + entries.reduce((accumulator, [tankIdString, stats]) => { + const tankId = parseInt(tankIdString); + + // edge case where new tanks don't have averages + if (tankAverages[tankId]) { + const tankWN8 = getWN8(tankAverages[tankId].all, stats); + + if (isNaN(tankWN8)) return accumulator; + return accumulator + tankWN8 * stats.battles; + } else return accumulator; + }, 0) / stats.battles; + const tier10Damage = + entries.reduce((accumulator, [tankIdString, stats]) => { + const tankId = parseInt(tankIdString); + + if (tankopedia[tankId]?.tier === 10) { + const tankStats = tankStatsOverTime[tankId]; + return accumulator + tankStats.damage_dealt; + } else return accumulator; + }, 0) / + entries.reduce((accumulator, [tankIdString, stats]) => { + const tankId = parseInt(tankIdString); + + if (tankopedia[tankId]?.tier === 10) { + const tankStats = tankStatsOverTime[tankId]; + return accumulator + tankStats.battles; + } else return accumulator; + }, 0); + + if (stats.battles < 126) { + problems.push(['Battles', `${stats.battles} (${stats.battles - 126})`]); + } + if (averageTier < 8) { + problems.push([ + 'Average tier', + `${averageTier.toFixed(2)} (${(averageTier - 8).toFixed(2)})`, + ]); + } + if (stats.wins / stats.battles < 0.6) { + problems.push([ + 'Winrate', + `${(100 * (stats.wins / stats.battles)).toFixed(2)}% (${( + 100 * + (stats.wins / stats.battles - 0.6) + ).toFixed(2)}%)`, + ]); + } + if (WN8 < 2450) { + problems.push(['WN8', `${WN8.toFixed(0)} (${WN8 - 2450})`]); + } + if (tier10Damage < 1250) { + problems.push([ + 'Tier 10 damage', + `${tier10Damage.toFixed(0)} (${tier10Damage - 1250})`, + ]); + } + + isEligible = problems.length === 0; + body = isEligible + ? 'Player is fully eligible.' + : `Player is not eligible. Shortcomings in 30-day statistics:\n\n${cleanTable( + problems, + )}`; + } else if (clan === 'SMRI') { + const stats = accountInfo[id].statistics.all; + + if (stats.battles < 1500) { + problems.push([ + 'Battles', + `${stats.battles} (${stats.battles - 1500})`, + ]); + } + if (stats.wins / stats.battles <= 0.53) { + problems.push([ + 'Winrate', + `${(100 * (stats.wins / stats.battles)).toFixed(2)}% (${( + 100 * + (stats.wins / stats.battles - 0.53) + ).toFixed(2)}%)`, + ]); + } + + isEligible = problems.length === 0; + body = isEligible + ? 'Player is fully eligible.' + : `Player is not eligible. Shortcomings in career statistics:\n\n${cleanTable( + problems, + )}`; + } + + await interaction.editReply({ + embeds: isEligible + ? [positiveEmbed(title, body)] + : [negativeEmbed(title, body)], + }); + }, +} satisfies CommandRegistry; diff --git a/src/commands/help.ts b/src/commands/help.ts index 6e50b7798..0b1511cb8 100644 --- a/src/commands/help.ts +++ b/src/commands/help.ts @@ -39,7 +39,5 @@ export default { ), ], }); - - console.log('Displaying help information'); }, } satisfies CommandRegistry; diff --git a/src/commands/inactive.ts b/src/commands/inactive.ts deleted file mode 100644 index 9fc91a20d..000000000 --- a/src/commands/inactive.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; -import markdownEscape from 'markdown-escape'; -import { NEGATIVE_COLOR, POSITIVE_COLOR } from '../constants/colors.js'; -import clanAutocomplete from '../core/autocomplete/clan.js'; -import getBlitzClan from '../core/blitz/getBlitzClan.js'; -import getWargamingResponse from '../core/blitz/getWargamingResponse.js'; -import cmdName from '../core/interaction/cmdName.js'; -import addClanChoices from '../core/options/addClanChoices.js'; -import { args } from '../core/process/args.js'; -import { CommandRegistry } from '../events/interactionCreate.js'; -import { AccountInfo } from '../types/accountInfo.js'; -import { ClanInfo } from '../types/clanInfo.js'; - -const DEFAULT_THRESHOLD = 7; - -export default { - inProduction: true, - inDevelopment: false, - inPublic: true, - - command: new SlashCommandBuilder() - .setName(cmdName('inactive')) - .setDescription('Lists all inactive players') - .addStringOption(addClanChoices) - .addNumberOption((option) => - option - .setName('threshold') - .setDescription( - `The number of days inactive (default: ${DEFAULT_THRESHOLD})`, - ) - .setMinValue(0), - ), - - async execute(interaction) { - const clanName = interaction.options.getString('clan')!; - const clan = await getBlitzClan(interaction, clanName); - const { server, id } = clan; - - const threshold = - interaction.options.getNumber('threshold')! ?? DEFAULT_THRESHOLD; - const time = new Date().getTime() / 1000; - const clanInfo = await getWargamingResponse( - `https://api.wotblitz.${server}/wotb/clans/info/?application_id=${args['wargaming-application-id']}&clan_id=${id}`, - ); - const memberIds = clanInfo[id].members_ids; - const accountInfo = await getWargamingResponse( - `https://api.wotblitz.${server}/wotb/account/info/?application_id=${ - args['wargaming-application-id'] - }&account_id=${memberIds.join(',')}`, - ); - const inactiveInfo = memberIds - .map((memberId) => { - const member = accountInfo[memberId]; - const inactiveDays = (time - member.last_battle_time) / 60 / 60 / 24; - - return [member.nickname, inactiveDays] as const; - }) - .filter(([, inactiveDays]) => inactiveDays >= threshold) - .sort((a, b) => b[1] - a[1]) - .map(([nickname, inactiveDays]) => { - const days = Math.floor(inactiveDays); - return `**${markdownEscape(nickname)}**: ${days} day${ - days === 1 ? '' : 's' - }`; - }); - const hasInactiveMembers = inactiveInfo.length > 0; - - await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setColor(hasInactiveMembers ? NEGATIVE_COLOR : POSITIVE_COLOR) - .setTitle( - hasInactiveMembers - ? `${markdownEscape(clanInfo[id].name)}'s inactive members` - : `No inactive members in ${markdownEscape(clanInfo[id].name)}`, - ) - .setDescription( - hasInactiveMembers - ? `Players that exceed the threshold of ${threshold} days:\n\n${inactiveInfo.join( - '\n', - )}` - : `No players exceed the threshold of ${threshold} days.`, - ), - ], - }); - - console.log( - `Displaying inactive members in ${clanInfo[id].name} for ${threshold} days`, - ); - }, - - autocomplete: clanAutocomplete, -} satisfies CommandRegistry; diff --git a/src/commands/inactive.tsx b/src/commands/inactive.tsx new file mode 100644 index 000000000..8d4541ee5 --- /dev/null +++ b/src/commands/inactive.tsx @@ -0,0 +1,92 @@ +import { SlashCommandBuilder } from 'discord.js'; +import GenericStats from '../components/GenericStats/index.js'; +import NoData, { NoDataType } from '../components/NoData.js'; +import PoweredByWargaming from '../components/PoweredByWargaming.js'; +import TitleBar from '../components/TitleBar.js'; +import Wrapper from '../components/Wrapper.js'; +import { BLITZ_SERVERS } from '../constants/servers.js'; +import clanAutocomplete from '../core/autocomplete/clan.js'; +import getBlitzClan from '../core/blitz/getBlitzClan.js'; +import getWargamingResponse from '../core/blitz/getWargamingResponse.js'; +import cmdName from '../core/interaction/cmdName.js'; +import addClanChoices from '../core/options/addClanChoices.js'; +import { args } from '../core/process/args.js'; +import render from '../core/ui/render.js'; +import { CommandRegistry } from '../events/interactionCreate.js'; +import { AccountInfo } from '../types/accountInfo.js'; +import { ClanInfo } from '../types/clanInfo.js'; + +const DEFAULT_THRESHOLD = 7; + +export default { + inProduction: true, + inDevelopment: false, + inPublic: true, + + command: new SlashCommandBuilder() + .setName(cmdName('inactive')) + .setDescription('Lists all inactive players') + .addStringOption(addClanChoices) + .addNumberOption((option) => + option + .setName('threshold') + .setDescription( + `The number of days inactive (default: ${DEFAULT_THRESHOLD})`, + ) + .setMinValue(0), + ), + + async execute(interaction) { + const clanName = interaction.options.getString('clan')!; + const { server, id } = await getBlitzClan(interaction, clanName); + const threshold = + interaction.options.getNumber('threshold')! ?? DEFAULT_THRESHOLD; + const time = new Date().getTime() / 1000; + const clanData = ( + await getWargamingResponse( + `https://api.wotblitz.${server}/wotb/clans/info/?application_id=${args['wargaming-application-id']}&clan_id=${id}`, + ) + )[id]; + const memberIds = clanData.members_ids; + const accounts = await getWargamingResponse( + `https://api.wotblitz.${server}/wotb/account/info/?application_id=${ + args['wargaming-application-id'] + }&account_id=${memberIds.join(',')}`, + ); + const inactive = memberIds + .map((memberId) => { + const member = accounts[memberId]; + const inactiveDays = (time - member.last_battle_time) / 60 / 60 / 24; + + return [member.nickname, inactiveDays] as [string, number]; + }) + .filter(([, inactiveDays]) => inactiveDays >= threshold) + .sort((a, b) => b[1] - a[1]) + .map( + ([name, days]) => [name, `${days.toFixed(0)} days`] as [string, string], + ); + const hasInactiveMembers = inactive.length > 0; + + const image = await render( + + + + {!hasInactiveMembers && } + {hasInactiveMembers && } + + + , + ); + + await interaction.editReply({ files: [image] }); + }, + + autocomplete: clanAutocomplete, +} satisfies CommandRegistry; diff --git a/src/commands/ownedtanks.ts b/src/commands/ownedtanks.tsx similarity index 50% rename from src/commands/ownedtanks.ts rename to src/commands/ownedtanks.tsx index 7e9e41ea5..5c98f039e 100644 --- a/src/commands/ownedtanks.ts +++ b/src/commands/ownedtanks.tsx @@ -1,17 +1,22 @@ import { SlashCommandBuilder } from 'discord.js'; -import markdownEscape from 'markdown-escape'; +import NoData, { NoDataType } from '../components/NoData.js'; +import PoweredByWargaming from '../components/PoweredByWargaming.js'; +import * as Tanks from '../components/Tanks/index.js'; +import TitleBar from '../components/TitleBar.js'; +import Wrapper from '../components/Wrapper.js'; +import { BLITZ_SERVERS } from '../constants/servers.js'; import usernameAutocomplete from '../core/autocomplete/username.js'; import getBlitzAccount from '../core/blitz/getBlitzAccount.js'; import getTankStats from '../core/blitz/getTankStats.js'; import getWargamingResponse from '../core/blitz/getWargamingResponse.js'; -import resolveTankName from '../core/blitz/resolveTankName.js'; -import { TANK_TYPE_EMOJIS, tankopedia } from '../core/blitz/tankopedia.js'; +import { TIER_ROMAN_NUMERALS, tankopedia } from '../core/blitz/tankopedia.js'; import cmdName from '../core/interaction/cmdName.js'; -import infoEmbed from '../core/interaction/infoEmbed.js'; import addUsernameOption from '../core/options/addUsernameOption.js'; import { args } from '../core/process/args.js'; +import render from '../core/ui/render.js'; import { CommandRegistry } from '../events/interactionCreate.js'; import { AccountInfo } from '../types/accountInfo.js'; +import { PlayerClanData } from '../types/playerClanData.js'; const COMP_TANKS = [ // light tanks @@ -36,7 +41,7 @@ const COMP_TANKS = [ export default { inProduction: true, - inDevelopment: false, + inDevelopment: true, inPublic: true, command: new SlashCommandBuilder() @@ -54,8 +59,7 @@ export default { async execute(interaction) { const tier = interaction.options.getInteger('tier')!; - const name = interaction.options.getString('username')!; - const account = await getBlitzAccount(interaction, name); + const account = await getBlitzAccount(interaction); const { id, server } = account; const accountInfo = await getWargamingResponse( `https://api.wotblitz.${server}/wotb/account/info/?application_id=${args['wargaming-application-id']}&account_id=${id}`, @@ -64,40 +68,48 @@ export default { const tanks = tankStats .map((tankData) => tankopedia[tankData.tank_id]) .filter((tank) => tank?.tier === tier); - - await interaction.editReply({ - embeds: [ - infoEmbed( - `${markdownEscape(accountInfo[id].nickname)}'s owned ${ - tier === null ? '' : `tier ${tier} ` - }tanks`, - `${ - tanks.length === 0 - ? `No tanks found in tier ${tier}` - : tanks - .map( - (tank) => - `${TANK_TYPE_EMOJIS[tank.type]} ${markdownEscape( - resolveTankName(tank.tank_id), - )} ${tank.is_premium ? '⭐' : ''}${ - COMP_TANKS.includes(tank.tank_id) ? 'šŸ†' : '' - }`, - ) - .join('\n') - }\n\n**Legend**\n⭐ = Premium/Collector\n${ - tier === 10 ? 'šŸ† = Comp Tank\n' : '' - }${TANK_TYPE_EMOJIS.heavyTank} = Heavy\n${ - TANK_TYPE_EMOJIS.mediumTank - } = Medium\n${TANK_TYPE_EMOJIS.lightTank} = Light\n${ - TANK_TYPE_EMOJIS['AT-SPG'] - } = Tank Destroyer`, - ), - ], - }); - - console.log( - `Displaying ${accountInfo[id].nickname}'s owned tanks in tier ${tier}`, + const clanData = await getWargamingResponse( + `https://api.wotblitz.${server}/wotb/clans/accountinfo/?application_id=${args['wargaming-application-id']}&account_id=${id}&extra=clan`, ); + + console.time('ownedtanks'); + const image = await render( + + {/* TODO: integrate some of these into title bar */} + + + {tanks.length === 0 && } + + {tanks.length > 0 && ( + + {tanks.map((tank) => ( + + ))} + + )} + + + , + ); + + await interaction.editReply({ files: [image] }); + console.timeEnd('ownedtanks'); }, autocomplete: usernameAutocomplete, diff --git a/src/commands/playerachievements.ts b/src/commands/playerachievements.ts index 59b3c0048..536e1bed9 100644 --- a/src/commands/playerachievements.ts +++ b/src/commands/playerachievements.ts @@ -36,8 +36,7 @@ export default { async execute(interaction) { const sortBy = (interaction.options.getString('sort') ?? 'name') as SortBy; - const name = interaction.options.getString('username')!; - const account = await getBlitzAccount(interaction, name); + const account = await getBlitzAccount(interaction); const { id, server } = account; const accounts = await getWargamingResponse( `https://api.wotblitz.${server}/wotb/account/info/?application_id=${args['wargaming-application-id']}&account_id=${id}`, @@ -76,8 +75,6 @@ export default { ), ], }); - - console.log(`Displaying player info for ${accounts[id].nickname}`); }, autocomplete: usernameAutocomplete, diff --git a/src/commands/playerinfo.ts b/src/commands/playerinfo.ts index bb0f5634d..82c83a05d 100644 --- a/src/commands/playerinfo.ts +++ b/src/commands/playerinfo.ts @@ -22,8 +22,7 @@ export default { .addStringOption(addUsernameOption), async execute(interaction) { - const name = interaction.options.getString('username')!; - const account = await getBlitzAccount(interaction, name); + const account = await getBlitzAccount(interaction); const { id, server } = account; const accounts = await getWargamingResponse( `https://api.wotblitz.${server}/wotb/account/info/?application_id=${args['wargaming-application-id']}&account_id=${id}`, @@ -60,8 +59,6 @@ export default { ), ], }); - - console.log(`Displaying player info for ${accountInfo.nickname}`); }, autocomplete: usernameAutocomplete, diff --git a/src/commands/searchclans.ts b/src/commands/searchclans.ts index a52e50ddf..db07881eb 100644 --- a/src/commands/searchclans.ts +++ b/src/commands/searchclans.ts @@ -50,7 +50,5 @@ export default { ), ], }); - - console.log(`Clan search results for "${clan}"`); }, } satisfies CommandRegistry; diff --git a/src/commands/searchplayers.ts b/src/commands/searchplayers.ts index 9ea41a53a..d0f731cd8 100644 --- a/src/commands/searchplayers.ts +++ b/src/commands/searchplayers.ts @@ -2,7 +2,7 @@ import { SlashCommandBuilder } from 'discord.js'; import markdownEscape from 'markdown-escape'; import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js'; import getWargamingResponse from '../core/blitz/getWargamingResponse.js'; -import { usernameRegex } from '../core/blitz/listAccountsPanServer.js'; +import { usernamePattern } from '../core/blitz/listAccountsPanServer.js'; import cmdName from '../core/interaction/cmdName.js'; import infoEmbed from '../core/interaction/infoEmbed.js'; import addServerChoices from '../core/options/addServerChoices.js'; @@ -21,7 +21,7 @@ export default { .setDescription('Search players in a Blitz server') .addStringOption(addServerChoices) .addStringOption((option) => - addUsernameOption(option).setAutocomplete(false), + addUsernameOption(option).setAutocomplete(false).setRequired(true), ) .addIntegerOption((option) => option @@ -36,7 +36,7 @@ export default { const name = interaction.options.getString('username')!; const limit = interaction.options.getInteger('limit') ?? 25; const trimmedSearch = name.trim(); - const players = usernameRegex.test(trimmedSearch) + const players = usernamePattern.test(trimmedSearch) ? await getWargamingResponse( `https://api.wotblitz.${server}/wotb/account/list/?application_id=${ args['wargaming-application-id'] @@ -58,7 +58,5 @@ export default { ), ], }); - - console.log(`Player search results for "${name}"`); }, } satisfies CommandRegistry; diff --git a/src/commands/searchtanks.ts b/src/commands/searchtanks.ts index f14361372..2d525cdc0 100644 --- a/src/commands/searchtanks.ts +++ b/src/commands/searchtanks.ts @@ -41,7 +41,5 @@ export default { ), ], }); - - console.log(`Tank search results for "${tank}"`); }, } satisfies CommandRegistry; diff --git a/src/commands/stats.tsx b/src/commands/stats.tsx index f24192947..81602e500 100644 --- a/src/commands/stats.tsx +++ b/src/commands/stats.tsx @@ -4,7 +4,7 @@ import { SlashCommandBuilder, } from 'discord.js'; import GenericAllStats from '../components/GenericAllStats.js'; -import NoBattlesInPeriod from '../components/NoBattlesInPeriod.js'; +import NoData, { NoDataType } from '../components/NoData.js'; import PoweredByBlitzStars from '../components/PoweredByBlitzStars.js'; import TitleBar from '../components/TitleBar.js'; import Wrapper from '../components/Wrapper.js'; @@ -51,9 +51,7 @@ export default { async execute(interaction) { const period = interaction.options.getString('period') as StatPeriod; - const username = interaction.options.getString('username')!; - const blitzAccount = await getBlitzAccount(interaction, username); - const { id, server } = blitzAccount; + const { id, server } = await getBlitzAccount(interaction); const accountInfo = await getWargamingResponse( `https://api.wotblitz.${server}/wotb/account/info/?application_id=${args['wargaming-application-id']}&account_id=${id}`, ); @@ -153,7 +151,7 @@ export default { } • ${new Date().toDateString()} • ${BLITZ_SERVERS[server]}`} /> - {stats.battles === 0 && } + {stats.battles === 0 && } {stats.battles > 0 && ( ( `https://api.wotblitz.${server}/wotb/account/info/?application_id=${args['wargaming-application-id']}&account_id=${id}`, @@ -93,7 +92,7 @@ export default { } • ${new Date().toDateString()} • ${BLITZ_SERVERS[server]}`} /> - {stats.battles === 0 && } + {stats.battles === 0 && } {stats.battles > 0 && ( { diff --git a/src/commands/today.tsx b/src/commands/today.tsx index c6f3e4d4d..5dff3675b 100644 --- a/src/commands/today.tsx +++ b/src/commands/today.tsx @@ -4,10 +4,10 @@ import { SlashCommandBuilder, } from 'discord.js'; import * as Breakdown from '../components/Breakdown/index.js'; -import NoBattlesInPeriod from '../components/NoBattlesInPeriod.js'; +import NoData, { NoDataType } from '../components/NoData.js'; import PoweredByBlitzStars from '../components/PoweredByBlitzStars.js'; import TitleBar from '../components/TitleBar.js'; -import Wrapper, { WrapperSize } from '../components/Wrapper.js'; +import Wrapper from '../components/Wrapper.js'; import { BLITZ_SERVERS } from '../constants/servers.js'; import usernameAutocomplete from '../core/autocomplete/username.js'; import getBlitzAccount from '../core/blitz/getBlitzAccount.js'; @@ -41,9 +41,7 @@ export default { .addStringOption(addUsernameOption), async execute(interaction) { - const username = interaction.options.getString('username')!; - const blitzAccount = await getBlitzAccount(interaction, username); - const { id, server } = blitzAccount; + const { id, server } = await getBlitzAccount(interaction); const tankStatsOverTime = await getTankStatsOverTime( interaction, server, @@ -162,7 +160,7 @@ export default { }); const image = await render( - + - {rows.length === 0 && } + {rows.length === 0 && } {rows.length > 0 && {rows}} , - WrapperSize.Roomy, ); const actionRow = new ActionRowBuilder().addComponents( @@ -195,8 +192,6 @@ export default { files: [image], components: [actionRow], }); - - console.log(`Showing daily breakdown for ${accountInfo[id].nickname}`); }, autocomplete: usernameAutocomplete, diff --git a/src/commands/verify.ts b/src/commands/verify.ts index 41c89157e..7ffa34a8b 100644 --- a/src/commands/verify.ts +++ b/src/commands/verify.ts @@ -20,11 +20,10 @@ export default { command: new SlashCommandBuilder() .setName(cmdName('verify')) .setDescription("Set's the user's username to their in-game name") - .addStringOption(addUsernameOption), + .addStringOption((option) => addUsernameOption(option).setRequired(true)), async execute(interaction) { - const name = interaction.options.getString('username')!; - const blitzAccount = await getBlitzAccount(interaction, name); + const blitzAccount = await getBlitzAccount(interaction); const { id, server } = blitzAccount; const accountInfo = await getWargamingResponse( `https://api.wotblitz.${server}/wotb/account/info/?application_id=${args['wargaming-application-id']}&account_id=${id}`, @@ -49,10 +48,6 @@ export default { ], }); - console.warn( - `${interaction.user.username} failed to verify because of no nickname permission.`, - ); - return; } @@ -84,10 +79,6 @@ export default { ], }); - console.warn( - `${interaction.user.username} failed to verify because of no manage roles permission.`, - ); - return; } @@ -107,10 +98,6 @@ export default { ), ], }); - - console.log( - `${interaction.user.username} verified as ${accountInfo[id].nickname}${clanTag}`, - ); } catch (error) { await interaction.editReply({ embeds: [ @@ -118,12 +105,10 @@ export default { .setColor(NEGATIVE_COLOR) .setTitle(`${interaction.user.username} failed to verify`) .setDescription( - "I can't change your nickname because you have higher permissions than me.", + "I can't change your nickname because you have higher permissions than me. Try setting your nickname to your Blitz username manually.", ), ], }); - - console.warn('Failed to verify because of higher permissions.'); } } } diff --git a/src/components/Breakdown/components/Row.tsx b/src/components/Breakdown/components/Row.tsx index 11eac9794..f5e6c8786 100644 --- a/src/components/Breakdown/components/Row.tsx +++ b/src/components/Breakdown/components/Row.tsx @@ -34,6 +34,7 @@ export function Row({ return (
+ )} + - - No battles played in this period - -
- ); -} diff --git a/src/components/NoData.tsx b/src/components/NoData.tsx new file mode 100644 index 000000000..003ed8040 --- /dev/null +++ b/src/components/NoData.tsx @@ -0,0 +1,33 @@ +import { theme } from '../stitches.config.js'; + +export enum NoDataType { + BattlesInPeriod, + PlayersInPeriod, + TanksFound, +} + +export interface NoDataProps { + type: NoDataType; +} + +const NO_DATA_MESSAGES: Record = { + [NoDataType.BattlesInPeriod]: 'No battles played in this period', + [NoDataType.PlayersInPeriod]: 'No players in this period', + [NoDataType.TanksFound]: 'No tanks found', +}; + +export default function NoData({ type }: NoDataProps) { + return ( +
+ + {NO_DATA_MESSAGES[type]} + +
+ ); +} diff --git a/src/components/PoweredByWargaming.tsx b/src/components/PoweredByWargaming.tsx new file mode 100644 index 000000000..e18ad7e7f --- /dev/null +++ b/src/components/PoweredByWargaming.tsx @@ -0,0 +1,15 @@ +import { theme } from '../stitches.config.js'; + +export default function PoweredByWargaming() { + return ( +
+ + + Powered by Wargaming + +
+ ); +} diff --git a/src/components/Tanks/components/Item.tsx b/src/components/Tanks/components/Item.tsx new file mode 100644 index 000000000..91f7061e4 --- /dev/null +++ b/src/components/Tanks/components/Item.tsx @@ -0,0 +1,35 @@ +import { TANK_ICONS, TankType } from '../../../core/blitz/tankopedia.js'; + +export interface ItemProps { + icon?: string; + type: TankType; + name: string; +} + +export function Item({ icon, type, name }: ItemProps) { + return ( +
+ {icon && } + +
+ + + {name} + +
+
+ ); +} diff --git a/src/components/Tanks/components/Root.tsx b/src/components/Tanks/components/Root.tsx new file mode 100644 index 000000000..1a23e18ea --- /dev/null +++ b/src/components/Tanks/components/Root.tsx @@ -0,0 +1,21 @@ +import { ReactNode } from 'react'; + +export interface RootProps { + children: ReactNode; +} + +export function Root({ children }: RootProps) { + return ( +
+ {children} +
+ ); +} diff --git a/src/components/Tanks/index.ts b/src/components/Tanks/index.ts new file mode 100644 index 000000000..9ac57386e --- /dev/null +++ b/src/components/Tanks/index.ts @@ -0,0 +1,2 @@ +export * from './components/Item.js'; +export * from './components/Root.js'; diff --git a/src/components/Wrapper.tsx b/src/components/Wrapper.tsx index 9689b4bd3..15d51f1c2 100644 --- a/src/components/Wrapper.tsx +++ b/src/components/Wrapper.tsx @@ -1,25 +1,11 @@ import { ReactNode } from 'react'; import { theme } from '../stitches.config.js'; -export enum WrapperSize { - Regular, - Roomy, -} - export interface WrapperProps { children: ReactNode; - size?: WrapperSize; } -export const WRAPPER_SIZE_WIDTHS: Record = { - [WrapperSize.Regular]: 640, - [WrapperSize.Roomy]: 800, -}; - -export default function Wrapper({ - children, - size = WrapperSize.Regular, -}: WrapperProps) { +export default function Wrapper({ children }: WrapperProps) { return (
, - username: string, ) { + const commandUsername = interaction.options.getString('username'); + const displayName = interaction.guild?.members.cache + .get(interaction.user.id) + ?.displayName.match(usernamePatternWithoutPosition)?.[0]; + const username = commandUsername ?? displayName; + + if (username === undefined) { + throw errorWithCause( + 'Username could not be inferred', + "You didn't provide me a username in the command nor was I able to infer your Blitz username from your Discord nickname. Try providing a username manually in the command or using the `/verify` command to set your Discord nickname to your Blitz username.", + ); + } + if (serverAndIdPattern.test(username)) { const [server, accountId] = username.split('/'); return { server: server as BlitzServer, id: Number(accountId) }; @@ -18,16 +32,10 @@ export default async function getBlitzAccount( if (accounts[0]) { return { server: accounts[0].server, id: accounts[0].account_id }; } else { - await interaction.editReply({ - embeds: [ - errorEmbed( - 'Could not find user', - `I couldn't find user \`${username}\`. Try selecting a username from the search result.`, - ), - ], - }); - - throw new Error(`Could not find user "${username}"`); + throw errorWithCause( + 'Could not find user', + `I couldn't find user \`${username}\`. Try providing a valid username manually or using the \`/verify\` command to set your Discord nickname to your Blitz username.`, + ); } } } diff --git a/src/core/blitz/getBlitzClan.ts b/src/core/blitz/getBlitzClan.ts index 343711c11..7d5c847c1 100644 --- a/src/core/blitz/getBlitzClan.ts +++ b/src/core/blitz/getBlitzClan.ts @@ -1,6 +1,6 @@ import { CacheType, ChatInputCommandInteraction } from 'discord.js'; import { BlitzServer } from '../../constants/servers.js'; -import errorEmbed from '../interaction/errorEmbed.js'; +import errorWithCause from '../process/errorWithCause.js'; import { serverAndIdPattern } from './getBlitzAccount.js'; import listClansPanServer from './listClansPanServer.js'; @@ -17,16 +17,10 @@ export default async function getBlitzClan( if (accounts[0]) { return { server: accounts[0].server, id: accounts[0].clan_id }; } else { - await interaction.editReply({ - embeds: [ - errorEmbed( - 'Could not find clan', - `I couldn't find clan \`${clan}\`. Try selecting a username from the search result.`, - ), - ], - }); - - throw new Error(`Could not find clan "${clan}"`); + throw errorWithCause( + 'Could not find clan', + `I couldn't find clan \`${clan}\`. Try selecting a username from the search result.`, + ); } } } diff --git a/src/core/blitz/getTankStats.ts b/src/core/blitz/getTankStats.ts index 6569c694c..5dac94cf3 100644 --- a/src/core/blitz/getTankStats.ts +++ b/src/core/blitz/getTankStats.ts @@ -1,8 +1,8 @@ import { CacheType, ChatInputCommandInteraction } from 'discord.js'; import { BLITZ_SERVERS, BlitzServer } from '../../constants/servers.js'; import { TanksStats } from '../../types/tanksStats.js'; -import errorEmbed from '../interaction/errorEmbed.js'; import { args } from '../process/args.js'; +import errorWithCause from '../process/errorWithCause.js'; import getWargamingResponse from './getWargamingResponse.js'; export default async function getTankStats( @@ -15,16 +15,10 @@ export default async function getTankStats( ); if (tankStats[id] === null) { - interaction.editReply({ - embeds: [ - errorEmbed( - 'No tank stats available', - `Wargaming says there is no tank stats for this account. This account may not have any battles/tanks or exist in the ${BLITZ_SERVERS[server]} server.`, - ), - ], - }); - - throw new Error(`No tank stats available for ${server}/${id}`); + throw errorWithCause( + 'No tank stats available', + `Wargaming says there is no tank stats for this account. This account may not have any battles/tanks or exist in the ${BLITZ_SERVERS[server]} server.`, + ); } return tankStats[id]; diff --git a/src/core/blitz/getWN8Percentile.ts b/src/core/blitz/getWN8Percentile.ts index 870bf83d4..e153cad4e 100644 --- a/src/core/blitz/getWN8Percentile.ts +++ b/src/core/blitz/getWN8Percentile.ts @@ -1,6 +1,6 @@ import { Percentile } from '../../constants/percentiles.js'; -const WN8_PERCENTILES: [number, Percentile][] = [ +export const WN8_PERCENTILES: [number, Percentile][] = [ [0, Percentile.VeryBad], [300, Percentile.Bad], [450, Percentile.BelowAverage], diff --git a/src/core/blitz/getWargamingResponse.ts b/src/core/blitz/getWargamingResponse.ts index 7a49afcef..59d30f9d5 100644 --- a/src/core/blitz/getWargamingResponse.ts +++ b/src/core/blitz/getWargamingResponse.ts @@ -1,4 +1,5 @@ import { WargamingResponse } from '../../types/wargamingResponse.js'; +import errorWithCause from '../process/errorWithCause.js'; export default async function getWargamingResponse( url: string, @@ -11,8 +12,9 @@ export default async function getWargamingResponse( if (parsed.status === 'ok') { return parsed.data; } else { - throw new Error( - `Wargaming response error status:"${parsed.status}" message: "${parsed.error.message}" url: "${url}"`, + throw errorWithCause( + `Wargaming response error status:"${parsed.status}"`, + `Message: "${parsed.error.message}"\nURL: "${url}"`, ); } } diff --git a/src/core/blitz/listAccountsPanServer.ts b/src/core/blitz/listAccountsPanServer.ts index 70643e540..13137e432 100644 --- a/src/core/blitz/listAccountsPanServer.ts +++ b/src/core/blitz/listAccountsPanServer.ts @@ -7,14 +7,15 @@ export type AccountListWithServer = (Account & { server: 'com' | 'eu' | 'asia'; })[]; -export const usernameRegex = /^[a-zA-Z0-9_]{3,24}$/; +export const usernamePattern = /^[a-zA-Z0-9_]{3,24}$/; +export const usernamePatternWithoutPosition = /[a-zA-Z0-9_]{3,24}/; export default async function listAccountsPanServer(search: string, limit = 9) { const trimmedSearch = search.trim(); const normalizedLimit = Math.round(limit / 3); const encodedSearch = encodeURIComponent(trimmedSearch); - if (usernameRegex.test(trimmedSearch)) { + if (usernamePattern.test(trimmedSearch)) { return ( await Promise.all([ getWargamingResponse( diff --git a/src/core/blitz/resolveTankId.ts b/src/core/blitz/resolveTankId.ts index 95507f5d9..e71e6ff8f 100644 --- a/src/core/blitz/resolveTankId.ts +++ b/src/core/blitz/resolveTankId.ts @@ -1,6 +1,6 @@ import { CacheType, ChatInputCommandInteraction } from 'discord.js'; import { go } from 'fuzzysort'; -import errorEmbed from '../interaction/errorEmbed.js'; +import errorWithCause from '../process/errorWithCause.js'; import { TANKS, tankopedia } from './tankopedia.js'; export default async function resolveTankId( @@ -13,16 +13,10 @@ export default async function resolveTankId( const searchResult = go(tank, TANKS, { keys: ['name'], limit: 1 }); if (searchResult.length === 0) { - await interaction.editReply({ - embeds: [ - errorEmbed( - 'Tank not found', - `Could not find tank by the name "${tank}".`, - ), - ], - }); - - throw new Error(`Tank not found by name "${tank}"`); + throw errorWithCause( + 'Tank not found', + `Could not find tank by the name "${tank}".`, + ); } else { return searchResult[0].obj.tank_id; } @@ -30,16 +24,10 @@ export default async function resolveTankId( if (tankopedia[number]) { return number; } else { - await interaction.editReply({ - embeds: [ - errorEmbed( - 'Tank not found', - `Could not find tank by the ID "${number}".`, - ), - ], - }); - - throw new Error(`Tank not found by ID "${number}"`); + throw errorWithCause( + 'Tank not found', + `Could not find tank by the ID "${number}".`, + ); } } } diff --git a/src/core/blitz/tankopedia.ts b/src/core/blitz/tankopedia.ts index 3889df0c3..8408d1559 100644 --- a/src/core/blitz/tankopedia.ts +++ b/src/core/blitz/tankopedia.ts @@ -1,37 +1,21 @@ import { WargamingResponse } from '../../types/wargamingResponse.js'; -/* -"1": { - "name": "T-34", - "nation": "ussr", - "is_premium": false, - "tier": 5, - "cost": { - "price_credit": 400000, - "price_gold": 0 - }, - "images": { - "preview": "/api/bs-cache/tank-icons/https%3A%2F%2Fglossary-eu-static.gcdn.co%2Ficons%2Fwotb%2Fcurrent%2Fuploaded%2Fvehicles%2Fhd_thumbnail%2FT-34.png", - "normal": "http://glossary-eu-static.gcdn.co/icons/wotb/current/uploaded/vehicles/hd/T-34.png" - }, - "tank_id": 1, - "type": "mediumTank", - "description": "The legend of the Soviet armored forces and the most widely-produced Soviet tank of World War II, with a total of 33,805 vehicles manufactured. Three variants of this model were produced at several Soviet factories from 1940 through 1944." - }, - */ +export type TankType = 'AT-SPG' | 'lightTank' | 'mediumTank' | 'heavyTank'; + +export interface TankopediaEntry { + name: string; + nation: string; + is_premium: boolean; + tier: number; + cost: { price_credit: number; price_gold: number }; + images: { preview: string; normal: string }; + tank_id: number; + type: TankType; + description: string; +} export interface Tankopedia { - [id: number]: { - name: string; - nation: string; - is_premium: boolean; - tier: number; - cost: { price_credit: number; price_gold: number }; - images: { preview: string; normal: string }; - tank_id: number; - type: string; - description: string; - }; + [id: number]: TankopediaEntry; } console.log('Caching tankopedia...'); @@ -42,30 +26,26 @@ export const tankopedia = ( ).data; console.log('Cached tankopedia'); -/** - * @deprecated - */ -export const TANK_TYPE_EMOJIS: Record = { - 'AT-SPG': 'šŸ”½', - heavyTank: 'šŸ‡­', - mediumTank: 'šŸ‡²', - lightTank: 'šŸ‡±', +export const TANK_ICONS: Record = { + 'AT-SPG': 'https://i.imgur.com/BIHSEH0.png', + lightTank: 'https://i.imgur.com/CSNha5V.png', + mediumTank: 'https://i.imgur.com/wvf3ltm.png', + heavyTank: 'https://i.imgur.com/ECeqlZa.png', +}; + +export const TIER_ROMAN_NUMERALS: Record = { + 1: 'I', + 2: 'II', + 3: 'III', + 4: 'IV', + 5: 'V', + 6: 'VI', + 7: 'VII', + 8: 'VIII', + 9: 'IX', + 10: 'X', }; export const TANK_IDS = Object.keys(tankopedia).map((id) => Number(id)); export const TANKS = TANK_IDS.map((id) => tankopedia[id]); export const TANK_NAMES = TANKS.map((tank) => tank.name); - -// console.log('Encoding tank images...'); -// await Promise.all( -// Object.entries(tankopedia).map(async ([, tank]) => { -// try { -// tank.images.normal = await URLToBase64(tank.images.normal); -// } catch (error) { -// console.warn( -// `Failed to encode tank image for ${tank.images.normal}: ${error}`, -// ); -// } -// }), -// ); -// console.log('Encoded tank images'); diff --git a/src/core/blitz/wargamingError.ts b/src/core/blitz/wargamingError.ts index a6daae8fb..e9e8258aa 100644 --- a/src/core/blitz/wargamingError.ts +++ b/src/core/blitz/wargamingError.ts @@ -22,5 +22,5 @@ export default async function wargamingError( }); console.log(`Wargaming returned an error`); - handleError(error, client, command); + handleError(error, command); } diff --git a/src/core/blitzstars/blitzStarsError.ts b/src/core/blitzstars/blitzStarsError.ts index 1278d3bf1..9f2b8443c 100644 --- a/src/core/blitzstars/blitzStarsError.ts +++ b/src/core/blitzstars/blitzStarsError.ts @@ -24,5 +24,5 @@ export default async function blitzStarsError( }); console.log(`BlitzStars returned an error`); - handleError(error, client, command); + handleError(error, command); } diff --git a/src/core/interaction/errorEmbed.ts b/src/core/interaction/negativeEmbed.ts similarity index 74% rename from src/core/interaction/errorEmbed.ts rename to src/core/interaction/negativeEmbed.ts index e4e6ed1e1..f01024c82 100644 --- a/src/core/interaction/errorEmbed.ts +++ b/src/core/interaction/negativeEmbed.ts @@ -1,7 +1,7 @@ import { EmbedBuilder } from 'discord.js'; import { NEGATIVE_COLOR } from '../../constants/colors.js'; -export default function errorEmbed(title: string, description: string) { +export default function negativeEmbed(title: string, description: string) { return new EmbedBuilder() .setColor(NEGATIVE_COLOR) .setTitle(title) diff --git a/src/core/interaction/noMember.ts b/src/core/interaction/noMember.ts index 9737ece2a..6b2071220 100644 --- a/src/core/interaction/noMember.ts +++ b/src/core/interaction/noMember.ts @@ -1,6 +1,6 @@ -import errorEmbed from './errorEmbed.js'; +import negativeEmbed from './negativeEmbed.js'; -export const noMember = errorEmbed( +export const noMember = negativeEmbed( 'User of command is not a member', 'Discord claims that the user of this command does not have an account... strange!', ); diff --git a/src/core/interaction/notTrackedByBlitzStars.ts b/src/core/interaction/notTrackedByBlitzStars.ts index 907f3342c..566551cf3 100644 --- a/src/core/interaction/notTrackedByBlitzStars.ts +++ b/src/core/interaction/notTrackedByBlitzStars.ts @@ -1,6 +1,6 @@ -import errorEmbed from './errorEmbed.js'; +import negativeEmbed from './negativeEmbed.js'; -export const notTrackedByBlitzStars = errorEmbed( +export const notTrackedByBlitzStars = negativeEmbed( 'No data to display', 'Player is not tracked by BlitzStars.', ); diff --git a/src/core/interaction/positiveEmbed.ts b/src/core/interaction/positiveEmbed.ts new file mode 100644 index 000000000..29a86adc5 --- /dev/null +++ b/src/core/interaction/positiveEmbed.ts @@ -0,0 +1,9 @@ +import { EmbedBuilder } from 'discord.js'; +import { POSITIVE_COLOR } from '../../constants/colors.js'; + +export default function positiveEmbed(title: string, description: string) { + return new EmbedBuilder() + .setColor(POSITIVE_COLOR) + .setTitle(title) + .setDescription(description); +} diff --git a/src/core/options/addUsernameOption.ts b/src/core/options/addUsernameOption.ts index 8c0a45911..d9f323d77 100644 --- a/src/core/options/addUsernameOption.ts +++ b/src/core/options/addUsernameOption.ts @@ -4,6 +4,5 @@ export default function addUsernameOption(option: SlashCommandStringOption) { return option .setName('username') .setDescription('The username you use in Blitz') - .setAutocomplete(true) - .setRequired(true); + .setAutocomplete(true); } diff --git a/src/core/process/args.ts b/src/core/process/args.ts index 3b44eb03d..1e3f490c1 100644 --- a/src/core/process/args.ts +++ b/src/core/process/args.ts @@ -1,4 +1,5 @@ import { argv } from 'process'; +import errorWithCause from './errorWithCause.js'; type ArgumentName = 'discord-token' | 'wargaming-application-id'; @@ -16,6 +17,9 @@ argv.forEach((arg) => { Object.keys(args).forEach((arg) => { if (args[arg as ArgumentName] === '') { - throw new Error(`Missing argument: ${arg}`); + throw errorWithCause( + `Missing argument: ${arg}`, + 'Missing required auth key.', + ); } }); diff --git a/src/core/process/errorWithCause.ts b/src/core/process/errorWithCause.ts new file mode 100644 index 000000000..0e2ef81c7 --- /dev/null +++ b/src/core/process/errorWithCause.ts @@ -0,0 +1,3 @@ +export default function errorWithCause(message: string, cause: string) { + return new Error(message, { cause }); +} diff --git a/src/core/ui/URLToBase64.ts b/src/core/ui/URLToBase64.ts deleted file mode 100644 index 31b7c9954..000000000 --- a/src/core/ui/URLToBase64.ts +++ /dev/null @@ -1,9 +0,0 @@ -export default async function URLToBase64(URL: string) { - const response = await fetch(URL); - const blob = await response.arrayBuffer(); - const base64 = `data:${response.headers.get( - 'content-type', - )};base64,${Buffer.from(blob).toString('base64')}`; - - return base64; -} diff --git a/src/core/ui/render.tsx b/src/core/ui/render.tsx index 6100c1793..10afb44ef 100644 --- a/src/core/ui/render.tsx +++ b/src/core/ui/render.tsx @@ -2,7 +2,6 @@ import { Resvg } from '@resvg/resvg-js'; import { readFile } from 'fs'; import { ReactNode } from 'react'; import satori from 'satori'; -import { WRAPPER_SIZE_WIDTHS, WrapperSize } from '../../components/Wrapper.js'; const FONT_NAME = 'Roboto'; const FONT_FILES = ['Roboto', 'Roboto-Bold', 'Roboto-Black']; @@ -21,12 +20,9 @@ const [robotoFlex, robotoFlexBold, robotoFlexBlack] = await Promise.all( ); console.log('Fonts imported'); -export default async function render( - element: ReactNode, - size: WrapperSize = WrapperSize.Regular, -) { +export default async function render(element: ReactNode) { const svg = await satori(element, { - width: WRAPPER_SIZE_WIDTHS[size], + width: 640, fonts: [ { data: robotoFlex, name: FONT_NAME, weight: 400 }, { data: robotoFlexBold, name: FONT_NAME, weight: 700 }, diff --git a/src/events/error.ts b/src/events/error.ts index bc99ced50..1f615cf63 100644 --- a/src/events/error.ts +++ b/src/events/error.ts @@ -1,4 +1,4 @@ -import { Client, EmbedBuilder, TextChannel } from 'discord.js'; +import { EmbedBuilder, TextChannel } from 'discord.js'; import discord from '../../discord.json' assert { type: 'json' }; import { NEGATIVE_COLOR } from '../constants/colors.js'; import isDev from '../core/process/isDev.js'; @@ -7,7 +7,7 @@ import { client } from '../index.js'; const PROCESS_ERROR_EVENTS = ['uncaughtException']; const CLIENT_ERROR_EVENTS = ['error']; -export function handleError(error: Error, client: Client, command: string) { +export function handleError(error: Error, command: string) { console.error(error); ( @@ -31,10 +31,10 @@ export function handleError(error: Error, client: Client, command: string) { export function registerErrorHandlers() { if (!isDev()) { PROCESS_ERROR_EVENTS.forEach((name) => - process.on(name, (error) => handleError(error, client, 'process error')), + process.on(name, (error) => handleError(error, 'process error')), ); CLIENT_ERROR_EVENTS.forEach((name) => - client.on(name, (error) => handleError(error, client, 'client error')), + client.on(name, (error) => handleError(error, 'client error')), ); } diff --git a/src/events/interactionCreate.ts b/src/events/interactionCreate.ts index b64e953ac..236a3ecf5 100644 --- a/src/events/interactionCreate.ts +++ b/src/events/interactionCreate.ts @@ -1,5 +1,8 @@ import { + ActionRowBuilder, AutocompleteInteraction, + ButtonBuilder, + ButtonStyle, CacheType, ChatInputCommandInteraction, Collection, @@ -11,9 +14,11 @@ import { } from 'discord.js'; import { readdirSync } from 'fs'; import discord from '../../discord.json' assert { type: 'json' }; +import negativeEmbed from '../core/interaction/negativeEmbed.js'; import { args } from '../core/process/args.js'; import getClientId from '../core/process/getClientId.js'; import isDev from '../core/process/isDev.js'; +import { handleError } from './error.js'; export interface CommandRegistry { inDevelopment: boolean; @@ -58,11 +63,19 @@ try { console.log(`Successfully refreshed ${publicData.length} public command(s).`); console.log(`Refreshing ${guildCommands.length} guild command(s).`); - const guildData = (await rest.put( - Routes.applicationGuildCommands(getClientId(), discord.sklld_guild_id), - { body: guildCommands }, - )) as RESTPostAPIChatInputApplicationCommandsJSONBody[]; - console.log(`Successfully refreshed ${guildData.length} guild command(s).`); + const guildData = [ + ...((await rest.put( + Routes.applicationGuildCommands(getClientId(), discord.sklld_guild_id), + { body: guildCommands }, + )) as RESTPostAPIChatInputApplicationCommandsJSONBody[]), + ...((await rest.put( + Routes.applicationGuildCommands(getClientId(), discord.tres_guild_id), + { body: guildCommands }, + )) as RESTPostAPIChatInputApplicationCommandsJSONBody[]), + ]; + console.log( + `Successfully refreshed ${guildData.length / 2} guild command(s).`, + ); } catch (error) { console.error(error); } @@ -93,6 +106,30 @@ export default async function interactionCreate( console.log(interaction.toString()); await interaction.deferReply(); - command.execute(interaction); + + try { + await command.execute(interaction); + } catch (error) { + const actionRow = new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setLabel('Get Help on Discord Server') + .setURL('https://discord.gg/nDt7AjGJQH') + .setStyle(ButtonStyle.Link), + ); + + await interaction.editReply({ + embeds: [ + negativeEmbed( + (error as Error).message, + `${ + (error as Error).cause ?? 'No further information is available.' + }`, + ), + ], + components: [actionRow], + }); + + handleError(error as Error, interaction.commandName); + } } }