feat: new stats renderer

This commit is contained in:
TresAbhi committed 2023-05-24 02:01:22 +00:00
1 parent a0290bb59f
commit 94481e81bb
14 files changed
+333 -126

No files matched your search

+89 -97
View File
@@ -1,25 +1,35 @@
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import markdownEscape from 'markdown-escape';
import { INFO_COLOR } from '../constants/colors.js';
import { SlashCommandBuilder } from 'discord.js';
import escapeHTML from 'escape-html';
import GenericStats from '../components/GenericStats/index.js';
import Screenshot from '../components/Screenshot.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 getWargamingResponse from '../core/blitz/getWargamingResponse.js';
import blitzStarsLinks from '../core/blitzstars/blitzStarsLinks.js';
import getBlitzStarsAccount from '../core/blitzstars/getBlitzStarsAccount.js';
import poweredByBlitzStars from '../core/blitzstars/poweredByBlitzStars.js';
import cleanTable from '../core/interaction/cleanTable.js';
import cmdName from '../core/interaction/cmdName.js';
import addUsernameOption from '../core/options/addUsernameOption.js';
import { args } from '../core/process/args.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { browser } from '../index.js';
import { AccountInfo, AllStats } from '../types/accountInfo.js';
import { PlayerClanData } from '../types/playerClanData.js';
import { BlitzStartsComputedPeriodicStatistics } from '../types/statistics.js';
type Period = 'today' | '30' | '90' | 'career';
const periodNames: Record<Period, string> = {
today: "Today's statistics",
30: '30-day statistics',
90: '90-day statistics',
career: 'Career statistics',
};
export default {
inProduction: true,
inDevelopment: false,
inDevelopment: true,
inPublic: true,
command: new SlashCommandBuilder()
@@ -50,6 +60,10 @@ export default {
`https://api.wotblitz.${server}/wotb/account/info/?application_id=${args['wargaming-application-id']}&account_id=${id}`,
);
if (!accountInfo) return;
const clanData = await getWargamingResponse<PlayerClanData>(
`https://api.wotblitz.${server}/wotb/clans/accountinfo/?application_id=${args['wargaming-application-id']}&account_id=${id}&extra=clan`,
);
if (!clanData) return;
const blitzStarsAccount = await getBlitzStarsAccount(interaction, id);
if (!blitzStarsAccount) return;
@@ -97,98 +111,76 @@ export default {
? blitzStarsAccount.statistics
: blitzStarsAccount[`period${period}d`];
}
if (!stats!) return;
if (!stats) return;
await interaction.editReply({
embeds: [
poweredByBlitzStars(
new EmbedBuilder()
.setColor(INFO_COLOR)
.setTitle(
`${markdownEscape(blitzStarsAccount.nickname)}'s ${
period === 'career'
? period
: `${period === 'today' ? 'today' : `${period} day`}`
} stats`,
)
.setDescription(
stats.all.battles > 0
? `${
period === 'today'
? '**⚠ "Today" stats are in development. Some stats are not available/wrong.**\n\n'
: ''
}${cleanTable([
[
'Winrate',
`${(100 * (stats.all.wins / stats.all.battles)).toFixed(
2,
)}%`,
],
[
'Survival',
`${(
100 *
(stats.all.survived_battles / stats.all.battles)
).toFixed(2)}%`,
],
[
'Accuracy',
`${((stats.all.hits / stats.all.shots) * 100).toFixed(
2,
)}%`,
],
['WN8', stats.wn8.toFixed(0)],
['WN7', stats.wn7.toFixed(0)],
[],
['Battles', stats.all.battles],
['Wins', stats.all.wins],
['Losses', stats.all.losses],
['Average tier', stats.avg_tier.toFixed(2)],
[],
[
'Shots per battle',
(stats.all.shots / stats.all.battles).toFixed(2),
],
[
'Hits per battle',
(stats.all.hits / stats.all.battles).toFixed(2),
],
[
'Damage per battle',
(stats.all.damage_dealt / stats.all.battles).toFixed(0),
],
[
'Kills per battle',
(stats.all.frags / stats.all.battles).toFixed(2),
],
[
'Spots per battle',
(stats.all.spotted / stats.all.battles).toFixed(2),
],
[
'XP per battle',
(stats.all.xp / stats.all.battles).toFixed(0),
],
[],
[
'Damage ratio',
(
stats.all.damage_dealt / stats.all.damage_received
).toFixed(2),
],
[
'Kills to death ratio',
(
stats.all.frags /
(stats.all.battles - stats.all.survived_battles)
).toFixed(2),
],
])}\n\n${blitzStarsLinks(server, blitzStarsAccount.nickname)}`
: 'No battles played in this period.',
),
const page = await browser.newPage();
await page.setViewportSize({ width: 640, height: 1 });
await page.setContent(
Screenshot(
Wrapper(
TitleBar(
escapeHTML(blitzStarsAccount.nickname),
clanData[id]?.clan
? `https://wotblitz-gc.gcdn.co/icons/clanEmblems1x/clan-icon-v2-${clanData[id]?.clan?.emblem_set_id}.png`
: 'https://i.imgur.com/uq6pKbh.png',
clanData[id]?.clan ? `[${clanData[id]?.clan?.tag}]` : '',
`${periodNames[period]} • ${new Date().toDateString()} • ${
BLITZ_SERVERS[server]
}`,
),
GenericStats([
[
'Winrate',
`${(100 * (stats.all.wins / stats.all.battles)).toFixed(2)}%`,
],
['WN8', stats.wn8.toFixed(0)],
[
'Survival',
`${(
100 *
(stats.all.survived_battles / stats.all.battles)
).toFixed(2)}%`,
],
[
'Accuracy',
`${((stats.all.hits / stats.all.shots) * 100).toFixed(2)}%`,
],
['Battles', stats.all.battles],
['Wins', stats.all.wins],
['Losses', stats.all.losses],
[
'Average damage',
(stats.all.damage_dealt / stats.all.battles).toFixed(0),
],
['Average XP', (stats.all.xp / stats.all.battles).toFixed(0)],
['Average shots', (stats.all.shots / stats.all.battles).toFixed(2)],
['Average hits', (stats.all.hits / stats.all.battles).toFixed(2)],
['Average kills', (stats.all.frags / stats.all.battles).toFixed(2)],
[
'Average spots',
(stats.all.spotted / stats.all.battles).toFixed(2),
],
['Average tier', stats.avg_tier.toFixed(2)],
[
'Damage ratio',
(stats.all.damage_dealt / stats.all.damage_received).toFixed(2),
],
[
'Kills to death ratio',
(
stats.all.frags /
(stats.all.battles - stats.all.survived_battles)
).toFixed(2),
],
]),
),
],
});
),
);
const screenshot = await page
.locator('#screenshot')
.screenshot({ omitBackground: true, scale: 'css' });
await page.close();
await interaction.editReply({ files: [screenshot] });
console.log(`Showing stats for ${blitzStarsAccount.nickname}`);
},
-22
View File
@@ -1,22 +0,0 @@
import { SlashCommandBuilder } from 'discord.js';
import usernameAutocomplete from '../core/autocomplete/username.js';
import cmdName from '../core/interaction/cmdName.js';
import addUsernameOption from '../core/options/addUsernameOption.js';
import { CommandRegistry } from '../events/interactionCreate.js';
export default {
inProduction: false,
inDevelopment: true,
inPublic: true,
command: new SlashCommandBuilder()
.setName(cmdName('today'))
.setDescription('A brief summary of your performance today')
.addStringOption(addUsernameOption),
async execute(interaction) {
interaction.editReply("let's do this!");
},
autocomplete: usernameAutocomplete,
} satisfies CommandRegistry;
+5
View File
@@ -0,0 +1,5 @@
export type ChildrenArgument = string | string[];
export default function Children(children: string[]) {
return children.join('\n');
}
@@ -0,0 +1,19 @@
import { Stat } from '../index.js';
import GenericStatsRow from './GenericStatsRow.js';
export default function GenericStatsColumn(stats: Stat[]) {
return `
<style>
.generic-stats-column {
flex: 1;
display: flex;
flex-direction: column;
gap: 8px;
}
</style>
<div class="generic-stats-column">
${stats.map((stat) => GenericStatsRow(stat)).join('\n')}
</div>
`;
}
@@ -0,0 +1,29 @@
import { Stat } from '../index.js';
export default function GenericStatsRow(stat: Stat) {
return `
<style>
.generic-stats-row {
display: flex;
justify-content: space-between;
align-items: center;
}
.generic-stats-label {
color: #A0A0A0;
font-size: 16px;
}
.generic-stats-value {
color: white;
font-weight: bold;
font-size: 16px;
}
</style>
<div class="generic-stats-row">
<span class="generic-stats-label">${stat[0]}</span>
<span class="generic-stats-value">${stat[1]}</span>
</div>
`;
}
+27
View File
@@ -0,0 +1,27 @@
import GenericStatsColumn from './components/GenericStatsColumn.js';
export type Stat = [string, string | number];
export default function GenericStats(stats: Stat[], columnCount = 2) {
const itemsPerRow = Math.ceil(stats.length / columnCount);
const columns: Stat[][] = [];
stats.forEach((stat, index) => {
const column = Math.floor(index / itemsPerRow);
if (!columns[column]) columns[column] = [];
columns[column].push(stat);
});
return `
<style>
.generic-stats {
display: flex;
gap: 32px;
}
</style>
<div class="generic-stats">
${columns.map((column) => GenericStatsColumn(column)).join('\n')}
</div>
`;
}
+26
View File
@@ -0,0 +1,26 @@
import Children from './Children.js';
export default function Screenshot(...children: string[]) {
return `
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:[email protected]');
@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:[email protected]');
body {
margin: 0;
}
* {
font-family: 'Roboto Flex', sans-serif;
}
#screenshot {
display: flex;
}
</style>
<div id="screenshot">
${Children(children)}
</div>
`;
}
+69
View File
@@ -0,0 +1,69 @@
export default function TitleBar(
name: string,
image: string,
nameDiscriminator = '',
description = '',
) {
return `
<style>
.title-bar {
display: flex;
justify-content: space-between;
align-items: center;
}
.title-bar-info {
display: flex;
gap: 8px;
}
.title-bar-avatar {
width: 64px;
height: 64px;
}
.title-bar-text {
display: flex;
flex-direction: column;
gap: 4px;
}
.title-bar-name {
font-size: 32px;
color: white;
font-weight: 900;
}
.title-bar-discriminator {
color: #A0A0A0;
}
.title-bar-description {
color: #A0A0A0;
font-size: 16px;
}
.title-bar-blitzkrieg {
width: 64px;
height: 64px;
}
</style>
<div class="title-bar">
<div class="title-bar-info">
<img class="title-bar-avatar" src="${image}" />
<div class="title-bar-text">
<span class="title-bar-name">
${name}
<span class="title-bar-discriminator">${nameDiscriminator}</span>
</span>
<span class="title-bar-description">${description}</span>
</div>
</div>
<img class="title-bar-blitzkrieg" src="https://i.imgur.com/35phKIu.png" />
</div>
`;
}
+21
View File
@@ -0,0 +1,21 @@
import Children from './Children.js';
export default function Wrapper(...children: string[]) {
return `
<style>
#wrapper {
display: flex;
flex-direction: column;
padding: 16px;
gap: 32px;
width: 640px;
background: black;
color: white;
}
</style>
<div id="wrapper">
${Children(children)}
</div>
`;
}
+3 -6
View File
@@ -1,3 +1,4 @@
import { chromium } from '@playwright/test';
import { Client, GatewayIntentBits } from 'discord.js';
import { args } from './core/process/args.js';
import { registerErrorHandlers } from './events/error.js';
@@ -5,16 +6,12 @@ import guildMemberAdd from './events/guildMemberAdd.js';
import interactionCreate from './events/interactionCreate.js';
import ready from './events/ready.js';
// sudo apt-get install libatk-bridge2.0-0
// node node_modules/puppeteer/install.js
registerErrorHandlers();
export const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers],
});
// export const browser = await launch({ headless: 'new' });
// export const page = await browser.newPage();
registerErrorHandlers();
export const browser = await chromium.launch();
client
.on('ready', ready)