feat: heavy usage of await

This commit is contained in:
TresAbhi committed 2023-05-08 01:45:59 +00:00
1 parent 18360dfe8f
commit 91af52b4b8
14 files changed
+163 -260

No files matched your search

+2 -2
View File
@@ -77,6 +77,7 @@ export default async function interactionCreate(
} }
try { try {
await interaction.deferReply();
command.execute(interaction); command.execute(interaction);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
@@ -86,9 +87,8 @@ export default async function interactionCreate(
ephemeral: true, ephemeral: true,
}); });
} else { } else {
await interaction.reply({ await interaction.editReply({
content: 'There was an error while executing this command!', content: 'There was an error while executing this command!',
ephemeral: true,
}); });
} }
} }
+2 -2
View File
@@ -11,7 +11,7 @@ const executionStart = new Date().getTime();
export default { export default {
inProduction: true, inProduction: true,
inDevelopment: false, inDevelopment: true,
inPublic: true, inPublic: true,
command: new SlashCommandBuilder() command: new SlashCommandBuilder()
@@ -22,7 +22,7 @@ export default {
const currentTime = new Date().getTime(); const currentTime = new Date().getTime();
const uptime = currentTime - executionStart; const uptime = currentTime - executionStart;
await interaction.reply({ await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setTitle(`${client.user?.username} debug information`) .setTitle(`${client.user?.username} debug information`)
+40 -39
View File
@@ -43,66 +43,72 @@ export default {
if (!extractedUser) return; if (!extractedUser) return;
const { name, server } = extractedUser; const { name, server } = extractedUser;
const command = `eligible ${server} ${name} ${clan}`;
getBlitzAccount(interaction, command, name, server, async (account) => { const blitzAccount = await getBlitzAccount(interaction, name, server);
getBlitzStarsAccount( if (!blitzAccount) return;
const blitzStarsAccount = await getBlitzStarsAccount(
interaction, interaction,
command, blitzAccount.account_id,
account.account_id,
name, name,
async (data) => { );
if (!blitzStarsAccount) return;
const issues: string[] = []; const issues: string[] = [];
if (clan === 'sklld') { if (clan === 'sklld') {
if (data.period30d.all.battles < 150) { if (blitzStarsAccount.period30d.all.battles < 150) {
issues.push( issues.push(
`**Battles**: ${data.period30d.all.battles} (${ `**Battles**: ${blitzStarsAccount.period30d.all.battles} (${
data.period30d.all.battles - 150 blitzStarsAccount.period30d.all.battles - 150
})`, })`,
); );
} }
if (data.period30d.avg_tier < 8) { if (blitzStarsAccount.period30d.avg_tier < 8) {
issues.push( issues.push(
`**Tier**: ${data.period30d.avg_tier.toFixed(2)} (${( `**Tier**: ${blitzStarsAccount.period30d.avg_tier.toFixed(2)} (${(
data.period30d.avg_tier - 8 blitzStarsAccount.period30d.avg_tier - 8
).toFixed(2)})`, ).toFixed(2)})`,
); );
} }
if (data.period30d.special.winrate < 60) { if (blitzStarsAccount.period30d.special.winrate < 60) {
issues.push( issues.push(
`**Winrate**: ${data.period30d.special.winrate.toFixed(2)}% (${( `**Winrate**: ${blitzStarsAccount.period30d.special.winrate.toFixed(
data.period30d.special.winrate - 60 2,
).toFixed(2)}%)`, )}% (${(blitzStarsAccount.period30d.special.winrate - 60).toFixed(
2,
)}%)`,
); );
} }
if (data.period30d.wn8 < 2100) { if (blitzStarsAccount.period30d.wn8 < 2100) {
issues.push( issues.push(
`**WN8**: ${data.period30d.wn8.toFixed(0)} (${( `**WN8**: ${blitzStarsAccount.period30d.wn8.toFixed(0)} (${(
data.period30d.wn8 - 2100 blitzStarsAccount.period30d.wn8 - 2100
).toFixed(0)})`, ).toFixed(0)})`,
); );
} }
if (data.period30d.special.dpb < 2400) { if (blitzStarsAccount.period30d.special.dpb < 2400) {
issues.push( issues.push(
`**Damage per battle**: ${data.period30d.special.dpb.toFixed( `**Damage per battle**: ${blitzStarsAccount.period30d.special.dpb.toFixed(
0, 0,
)} (${(data.period30d.special.dpb - 2400).toFixed(0)})`, )} (${(blitzStarsAccount.period30d.special.dpb - 2400).toFixed(0)})`,
); );
} }
} else { } else {
if (data.statistics.all.battles < 1500) { if (blitzStarsAccount.statistics.all.battles < 1500) {
issues.push( issues.push(
`**Battles**: ${data.statistics.all.battles} (${ `**Battles**: ${blitzStarsAccount.statistics.all.battles} (${
data.statistics.all.battles - 1500 blitzStarsAccount.statistics.all.battles - 1500
})`, })`,
); );
} }
if (data.statistics.special.winrate < 53) { if (blitzStarsAccount.statistics.special.winrate < 53) {
issues.push( issues.push(
`**Winrate**: ${data.statistics.special.winrate.toFixed( `**Winrate**: ${blitzStarsAccount.statistics.special.winrate.toFixed(
2, 2,
)}% (${(data.statistics.special.winrate - 53).toFixed(2)}%)`, )}% (${(blitzStarsAccount.statistics.special.winrate - 53).toFixed(
2,
)}%)`,
); );
} }
} }
@@ -114,7 +120,7 @@ export default {
poweredByBlitzStars( poweredByBlitzStars(
new EmbedBuilder() new EmbedBuilder()
.setTitle( .setTitle(
`${markdownEscape(data.nickname)} is ${ `${markdownEscape(blitzStarsAccount.nickname)} is ${
eligible ? '' : 'not ' eligible ? '' : 'not '
}eligible for ${CLANS[clan].name}`, }eligible for ${CLANS[clan].name}`,
) )
@@ -123,26 +129,21 @@ export default {
`${ `${
eligible eligible
? `${markdownEscape( ? `${markdownEscape(
data.nickname, blitzStarsAccount.nickname,
)} meets all the requirements set for ${ )} meets all the requirements set for ${CLANS[clan].name}.`
CLANS[clan].name
}.`
: `${markdownEscape( : `${markdownEscape(
data.nickname, blitzStarsAccount.nickname,
)}'s shortcomings for ${CLANS[clan].name} (${ )}'s shortcomings for ${CLANS[clan].name} (${
clan === 'sklld' ? '30 days stats' : 'career stats' clan === 'sklld' ? '30 days stats' : 'career stats'
}):\n\n${issues.join('\n')}` }):\n\n${issues.join('\n')}`
}\n\n${blitzLinks(data)}`, }\n\n${blitzLinks(blitzStarsAccount)}`,
), ),
), ),
], ],
}); });
console.log( console.log(
`Showing ${data.nickname}'s eligibility for ${CLANS[clan].name}`, `Showing ${blitzStarsAccount.nickname}'s eligibility for ${CLANS[clan].name}`,
); );
}, },
);
});
},
} satisfies CommandRegistry; } satisfies CommandRegistry;
+2 -2
View File
@@ -10,7 +10,7 @@ import { client } from '../index.js';
export default { export default {
inProduction: true, inProduction: true,
inDevelopment: false, inDevelopment: true,
inPublic: true, inPublic: true,
command: new SlashCommandBuilder() command: new SlashCommandBuilder()
@@ -18,7 +18,7 @@ export default {
.setDescription('All the help you need about the bot'), .setDescription('All the help you need about the bot'),
async execute(interaction) { async execute(interaction) {
await interaction.reply({ await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setTitle(`${client.user?.username} help`) .setTitle(`${client.user?.username} help`)
+16 -24
View File
@@ -3,8 +3,9 @@ import markdownEscape from 'markdown-escape';
import { CommandRegistry } from '../behaviors/interactionCreate.js'; import { CommandRegistry } from '../behaviors/interactionCreate.js';
import { NEGATIVE_COLOR, POSITIVE_COLOR } from '../constants/colors.js'; import { NEGATIVE_COLOR, POSITIVE_COLOR } from '../constants/colors.js';
import { BlitzServer } from '../constants/servers.js'; import { BlitzServer } from '../constants/servers.js';
import { ClanInfo } from '../types/clanInfo.js';
import { AccountInfo } from '../types/accountInfo.js'; import { AccountInfo } from '../types/accountInfo.js';
import { ClanInfo } from '../types/clanInfo.js';
import { Clan } from '../types/clanList.js';
import addServerChoices from '../utilities/addServerChoices.js'; import addServerChoices from '../utilities/addServerChoices.js';
import { args } from '../utilities/args.js'; import { args } from '../utilities/args.js';
import getClan from '../utilities/getClan.js'; import getClan from '../utilities/getClan.js';
@@ -14,13 +15,13 @@ const DEFAULT_THRESHOLD = 7;
export default { export default {
inProduction: true, inProduction: true,
inDevelopment: false, inDevelopment: true,
inPublic: true, inPublic: true,
command: new SlashCommandBuilder() command: new SlashCommandBuilder()
.setName('inactive') .setName('inactive')
.setDescription('Lists all inactive players') .setDescription('Lists all inactive players')
.addStringOption(addServerChoices) .addStringOption((option) => addServerChoices(option).setRequired(true))
.addStringOption((option) => .addStringOption((option) =>
option option
.setName('name') .setName('name')
@@ -39,32 +40,30 @@ export default {
async execute(interaction) { async execute(interaction) {
const name = interaction.options.getString('name')!; const name = interaction.options.getString('name')!;
const server = interaction.options.getString('server') as BlitzServer; const server = interaction.options.getString('server') as BlitzServer;
const command = `inactive ${server} ${name}`;
getClan(interaction, command, name, server, async (clan) => { const clan = (await getClan(interaction, name, server)) as Clan;
if (!clan) return;
const threshold = const threshold =
interaction.options.getNumber('threshold')! ?? DEFAULT_THRESHOLD; interaction.options.getNumber('threshold')! ?? DEFAULT_THRESHOLD;
const time = new Date().getTime() / 1000; const time = new Date().getTime() / 1000;
getWargamingResponse<ClanInfo>( const clanInfo = await getWargamingResponse<ClanInfo>(
`https://api.wotblitz.${server}/wotb/clans/info/?application_id=${args['wargaming-application-id']}&clan_id=${clan.clan_id}`, `https://api.wotblitz.${server}/wotb/clans/info/?application_id=${args['wargaming-application-id']}&clan_id=${clan.clan_id}`,
interaction, );
command,
async (clanInfo) => {
const memberIds = clanInfo[clan.clan_id].members_ids; const memberIds = clanInfo[clan.clan_id].members_ids;
getWargamingResponse<AccountInfo>( const accountInfo = await getWargamingResponse<AccountInfo>(
`https://api.wotblitz.${server}/wotb/account/info/?application_id=${ `https://api.wotblitz.${server}/wotb/account/info/?application_id=${
args['wargaming-application-id'] args['wargaming-application-id']
}&account_id=${memberIds.join(',')}`, }&account_id=${memberIds.join(',')}`,
interaction, );
command,
async (playerPersonalData) => {
const inactiveInfo = memberIds const inactiveInfo = memberIds
.map((memberId) => { .map((memberId) => {
const member = playerPersonalData[memberId]; const member = accountInfo[memberId];
const inactiveDays = const inactiveDays = (time - member.last_battle_time) / 60 / 60 / 24;
(time - member.last_battle_time) / 60 / 60 / 24;
return [member.nickname, inactiveDays] as const; return [member.nickname, inactiveDays] as const;
}) })
@@ -81,9 +80,7 @@ export default {
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setColor( .setColor(hasInactiveMembers ? NEGATIVE_COLOR : POSITIVE_COLOR)
hasInactiveMembers ? NEGATIVE_COLOR : POSITIVE_COLOR,
)
.setTitle( .setTitle(
hasInactiveMembers hasInactiveMembers
? `${markdownEscape(clan.name)}'s inactive members` ? `${markdownEscape(clan.name)}'s inactive members`
@@ -103,9 +100,4 @@ export default {
`Displaying inactive members in ${clan.name} for ${threshold} days`, `Displaying inactive members in ${clan.name} for ${threshold} days`,
); );
}, },
);
},
);
});
},
} satisfies CommandRegistry; } satisfies CommandRegistry;
+8 -12
View File
@@ -9,15 +9,15 @@ import { args } from '../utilities/args.js';
import getWargamingResponse from '../utilities/getWargamingResponse.js'; import getWargamingResponse from '../utilities/getWargamingResponse.js';
export default { export default {
inDevelopment: false, inDevelopment: true,
inProduction: true, inProduction: true,
inPublic: true, inPublic: true,
command: new SlashCommandBuilder() command: new SlashCommandBuilder()
.setName('searchplayers') .setName('searchplayers')
.setDescription('Search players in a Blitz server') .setDescription('Search players in a Blitz server')
.addStringOption(addServerChoices) .addStringOption((option) => addServerChoices(option).setRequired(true))
.addStringOption(addIGNOption) .addStringOption((option) => addIGNOption(option).setRequired(true))
.addIntegerOption((option) => .addIntegerOption((option) =>
option option
.setName('limit') .setName('limit')
@@ -26,18 +26,16 @@ export default {
.setMaxValue(100), .setMaxValue(100),
), ),
execute(interaction) { async execute(interaction) {
const server = interaction.options.getString('server')!; const server = interaction.options.getString('server')!;
const name = interaction.options.getString('name')!; const name = interaction.options.getString('name')!;
const limit = interaction.options.getInteger('limit') ?? 25; const limit = interaction.options.getInteger('limit') ?? 25;
const command = `searchplayers ${server} ${name} ${limit}`;
getWargamingResponse<Players>( const players = await getWargamingResponse<Players>(
`https://api.wotblitz.${server}/wotb/account/list/?application_id=${args['wargaming-application-id']}&search=${name}&limit=${limit}`, `https://api.wotblitz.${server}/wotb/account/list/?application_id=${args['wargaming-application-id']}&search=${name}&limit=${limit}`,
interaction, );
command,
(players) => { await interaction.editReply({
interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setColor(SKILLED_COLOR) .setColor(SKILLED_COLOR)
@@ -54,6 +52,4 @@ export default {
], ],
}); });
}, },
);
},
} satisfies CommandRegistry; } satisfies CommandRegistry;
+22 -51
View File
@@ -3,7 +3,7 @@ import markdownEscape from 'markdown-escape';
import { CommandRegistry } from '../behaviors/interactionCreate.js'; import { CommandRegistry } from '../behaviors/interactionCreate.js';
import { SKILLED_COLOR } from '../constants/colors.js'; import { SKILLED_COLOR } from '../constants/colors.js';
import { AccountInfo, AllStats } from '../types/accountInfo.js'; import { AccountInfo, AllStats } from '../types/accountInfo.js';
import { PeriodStatistics } from '../types/statistics.js'; import { PeriodStatistics, PlayerStatistics } from '../types/statistics.js';
import addIGNOption from '../utilities/addIGNOption.js'; import addIGNOption from '../utilities/addIGNOption.js';
import addServerChoices from '../utilities/addServerChoices.js'; import addServerChoices from '../utilities/addServerChoices.js';
import { args } from '../utilities/args.js'; import { args } from '../utilities/args.js';
@@ -18,7 +18,7 @@ type Period = 'today' | '30' | '90' | 'career';
export default { export default {
inProduction: true, inProduction: true,
inDevelopment: false, inDevelopment: true,
inPublic: true, inPublic: true,
command: new SlashCommandBuilder() command: new SlashCommandBuilder()
@@ -48,18 +48,16 @@ export default {
const { name, server } = extractedUser; const { name, server } = extractedUser;
const command = `stats ${server} ${name} ${period}`; const command = `stats ${server} ${name} ${period}`;
getBlitzAccount( const blitzAccount = await getBlitzAccount(interaction, name, server);
if (!blitzAccount) return;
const blitzStarsAccount = (await getBlitzStarsAccount(
interaction, interaction,
command,
name,
server,
async (blitzAccount) => {
getBlitzStarsAccount(
interaction,
command,
blitzAccount.account_id, blitzAccount.account_id,
name, name,
async (blitzStarsAccount) => { )) as PlayerStatistics;
if (!blitzStarsAccount) return;
async function reply(stats: PeriodStatistics) { async function reply(stats: PeriodStatistics) {
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
@@ -74,20 +72,14 @@ export default {
.setDescription( .setDescription(
`${ `${
period === 'today' period === 'today'
? '**⚠ Some stats are not available**\n\n' ? '**⚠ "Today" stats are in development. Some stats are not available/wrong.**\n\n'
: '' : ''
}${[ }${[
['Winrate', `${stats.special.winrate.toFixed(2)}%`], ['Winrate', `${stats.special.winrate.toFixed(2)}%`],
[ ['Survival', `${stats.special.survivalRate.toFixed(2)}%`],
'Survival',
`${stats.special.survivalRate.toFixed(2)}%`,
],
[ [
'Accuracy', 'Accuracy',
`${( `${((stats.all.hits / stats.all.shots) * 100).toFixed(2)}%`,
(stats.all.hits / stats.all.shots) *
100
).toFixed(2)}%`,
], ],
['WN8', stats.wn8.toFixed(0)], ['WN8', stats.wn8.toFixed(0)],
['WN7', stats.wn7.toFixed(0)], ['WN7', stats.wn7.toFixed(0)],
@@ -110,20 +102,12 @@ export default {
(stats.all.xp / stats.all.battles).toFixed(0), (stats.all.xp / stats.all.battles).toFixed(0),
], ],
[], [],
[ ['Damage ratio', stats.special.damageRatio.toFixed(2)],
'Damage ratio', ['Kills to death ratio', stats.special.kdr.toFixed(2)],
stats.special.damageRatio.toFixed(2),
],
[
'Kills to death ratio',
stats.special.kdr.toFixed(2),
],
] ]
.filter((array) => array[1] !== `${-Infinity}`) .filter((array) => array[1] !== `${-Infinity}`)
.map((array) => .map((array) =>
array.length === 0 array.length === 0 ? '' : `**${array[0]}**: ${array[1]}`,
? ''
: `**${array[0]}**: ${array[1]}`,
) )
.join('\n')}\n\n${blitzLinks(blitzStarsAccount)}`, .join('\n')}\n\n${blitzLinks(blitzStarsAccount)}`,
), ),
@@ -131,9 +115,7 @@ export default {
], ],
}); });
console.log( console.log(`Showing ${blitzStarsAccount.nickname}'s ${period} stats`);
`Showing ${blitzStarsAccount.nickname}'s ${period} stats`,
);
} }
let stats: PeriodStatistics | null = null; let stats: PeriodStatistics | null = null;
@@ -141,11 +123,10 @@ export default {
if (period === 'career') { if (period === 'career') {
stats = blitzStarsAccount.statistics; stats = blitzStarsAccount.statistics;
} else if (period === 'today') { } else if (period === 'today') {
getWargamingResponse<AccountInfo>( const accountInfo = await getWargamingResponse<AccountInfo>(
`https://api.wotblitz.${server}/wotb/account/info/?application_id=${args['wargaming-application-id']}&account_id=${blitzAccount.account_id}`, `https://api.wotblitz.${server}/wotb/account/info/?application_id=${args['wargaming-application-id']}&account_id=${blitzAccount.account_id}`,
interaction, );
command,
async (accountInfo) => {
const a1 = blitzStarsAccount.statistics; const a1 = blitzStarsAccount.statistics;
const a2 = accountInfo[blitzAccount.account_id].statistics; const a2 = accountInfo[blitzAccount.account_id].statistics;
@@ -162,8 +143,7 @@ export default {
value2: (allStats: AllStats) => number, value2: (allStats: AllStats) => number,
) { ) {
return ( return (
(value1(a2.all) - value1(a1.all)) / (value1(a2.all) - value1(a1.all)) / (value2(a2.all) - value2(a1.all))
(value2(a2.all) - value2(a1.all))
); );
} }
@@ -173,9 +153,7 @@ export default {
capture_points: pb((a) => a.capture_points), capture_points: pb((a) => a.capture_points),
damage_dealt: pb((a) => a.damage_dealt), damage_dealt: pb((a) => a.damage_dealt),
damage_received: pb((a) => a.damage_received), damage_received: pb((a) => a.damage_received),
dropped_capture_points: diff( dropped_capture_points: diff((a) => a.dropped_capture_points),
(a) => a.dropped_capture_points,
),
frags: pb((a) => a.frags), frags: pb((a) => a.frags),
frags8p: pb((a) => a.frags8p), frags8p: pb((a) => a.frags8p),
hits: diff((a) => a.hits), hits: diff((a) => a.hits),
@@ -202,8 +180,7 @@ export default {
hitRate: pb((a) => a.hits / a.shots), hitRate: pb((a) => a.hits / a.shots),
hpb: pb((a) => a.hits), hpb: pb((a) => a.hits),
kdr: kdr:
diff((a) => a.frags) / diff((a) => a.frags) / diff((a) => a.battles - a.survived_battles),
diff((a) => a.battles - a.survived_battles),
kpb: pb((a) => a.frags), kpb: pb((a) => a.frags),
spb: pb((a) => a.spotted), spb: pb((a) => a.spotted),
}, },
@@ -215,8 +192,6 @@ export default {
}; };
reply(stats); reply(stats);
},
);
} else { } else {
stats = blitzStarsAccount[`period${period}d`]; stats = blitzStarsAccount[`period${period}d`];
} }
@@ -225,8 +200,4 @@ export default {
reply(stats); reply(stats);
} }
}, },
);
},
);
},
} satisfies CommandRegistry; } satisfies CommandRegistry;
+7 -16
View File
@@ -34,7 +34,7 @@ const COMP_TANKS = [
export default { export default {
inProduction: true, inProduction: true,
inDevelopment: false, inDevelopment: true,
inPublic: true, inPublic: true,
command: new SlashCommandBuilder() command: new SlashCommandBuilder()
@@ -53,21 +53,17 @@ export default {
async execute(interaction) { async execute(interaction) {
const tier = interaction.options.getInteger('tier')!; const tier = interaction.options.getInteger('tier')!;
await interaction.deferReply();
const extractedUser = await extractUser(interaction); const extractedUser = await extractUser(interaction);
if (!extractedUser) return; if (!extractedUser) return;
const { name, server } = extractedUser; const { name, server } = extractedUser;
const command = `tanks ${server} ${name} ${tier}`;
getBlitzAccount(interaction, command, name, server, async (account) => { const account = await getBlitzAccount(interaction, name, server);
getWargamingResponse<TanksStats>( if (!account) return;
const tankStats = await getWargamingResponse<TanksStats>(
`https://api.wotblitz.${server}/wotb/tanks/stats/?application_id=${args['wargaming-application-id']}&account_id=${account.account_id}`, `https://api.wotblitz.${server}/wotb/tanks/stats/?application_id=${args['wargaming-application-id']}&account_id=${account.account_id}`,
interaction, );
command,
async (tankStats) => {
const tanks = tankStats[account.account_id] const tanks = tankStats[account.account_id]
.map((tankData) => tankopedia.data[tankData.tank_id]) .map((tankData) => tankopedia.data[tankData.tank_id])
.filter((tank) => tank.tier === tier); .filter((tank) => tank.tier === tier);
@@ -106,11 +102,6 @@ export default {
], ],
}); });
console.log( console.log(`Displaying ${account.nickname}'s owned tanks in tier ${tier}`);
`Displaying ${account.nickname}'s owned tanks in tier ${tier}`,
);
},
);
});
}, },
} satisfies CommandRegistry; } satisfies CommandRegistry;
+23 -40
View File
@@ -13,7 +13,7 @@ import getWargamingResponse from '../utilities/getWargamingResponse.js';
export default { export default {
inProduction: true, inProduction: true,
inDevelopment: false, inDevelopment: true,
inPublic: true, inPublic: true,
command: new SlashCommandBuilder() command: new SlashCommandBuilder()
@@ -22,33 +22,28 @@ export default {
.addStringOption((option) => addServerChoices(option).setRequired(true)) .addStringOption((option) => addServerChoices(option).setRequired(true))
.addStringOption((Option) => addIGNOption(Option).setRequired(true)), .addStringOption((Option) => addIGNOption(Option).setRequired(true)),
execute(interaction) { async execute(interaction) {
let name = interaction.options.getString('name')!; let name = interaction.options.getString('name')!;
const server = interaction.options.getString('server') as BlitzServer; const server = interaction.options.getString('server') as BlitzServer;
const command = `verify ${server} ${name}`; const account = await getBlitzAccount(interaction, name, server);
if (!account) return;
getBlitzAccount(interaction, command, name, server, async (account) => {
name = account.nickname; name = account.nickname;
getWargamingResponse<PlayerClanData>( const clanData = await getWargamingResponse<PlayerClanData>(
`https://api.wotblitz.${server}/wotb/clans/accountinfo/?application_id=${args['wargaming-application-id']}&account_id=${account.account_id}&extra=clan`, `https://api.wotblitz.${server}/wotb/clans/accountinfo/?application_id=${args['wargaming-application-id']}&account_id=${account.account_id}&extra=clan`,
interaction, );
command, const clan = clanData[account.account_id]?.clan;
async (clanData) => { const clanTag = clan ? ` [${clan!.tag}]` : '';
const clan = clanData[account.account_id].clan;
const clanTag = clan === null ? '' : ` [${clan!.tag}]`;
if ( if (!interaction.guild?.members.me?.permissions.has('ManageNicknames')) {
!interaction.guild?.members.me?.permissions.has('ManageNicknames')
) {
interaction.editReply({ interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setColor(NEGATIVE_COLOR) .setColor(NEGATIVE_COLOR)
.setTitle( .setTitle(
`${markdownEscape( `${markdownEscape(interaction.user.username)} failed to verify`,
interaction.user.username,
)} failed to verify`,
) )
.setDescription( .setDescription(
"I don't have the permission to change your nickname.", "I don't have the permission to change your nickname.",
@@ -69,16 +64,14 @@ export default {
); );
if (member) { if (member) {
await member try {
?.setNickname( await member.setNickname(
`${name} (${BLITZ_SERVERS_SHORT[server]})${clanTag}`, `${name} (${BLITZ_SERVERS_SHORT[server]})${clanTag}`,
) );
.then(async () => {
if (interaction.guildId === discord.guild_id) { if (interaction.guildId === discord.guild_id) {
if ( if (
!interaction.guild?.members.me?.permissions.has( !interaction.guild?.members.me?.permissions.has('ManageRoles')
'ManageRoles',
)
) { ) {
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
@@ -112,11 +105,9 @@ export default {
.setColor(POSITIVE_COLOR) .setColor(POSITIVE_COLOR)
.setTitle(`${interaction.user.username} is verified`) .setTitle(`${interaction.user.username} is verified`)
.setDescription( .setDescription(
`The user is now verified as ${markdownEscape( `The user is now verified as ${markdownEscape(name)} (${
name, BLITZ_SERVERS_SHORT[server]
)} (${BLITZ_SERVERS_SHORT[server]})${markdownEscape( })${markdownEscape(clanTag)}`,
clanTag,
)}`,
), ),
], ],
}); });
@@ -124,29 +115,21 @@ export default {
console.log( console.log(
`${interaction.user.username} verified as ${name} (${BLITZ_SERVERS_SHORT[server]})${clanTag}`, `${interaction.user.username} verified as ${name} (${BLITZ_SERVERS_SHORT[server]})${clanTag}`,
); );
}) } catch (error) {
.catch(async () => {
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setColor(NEGATIVE_COLOR) .setColor(NEGATIVE_COLOR)
.setTitle( .setTitle(`${interaction.user.username} failed to verify`)
`${interaction.user.username} failed to verify`,
)
.setDescription( .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.",
), ),
], ],
}); });
console.warn( console.warn('Failed to verify because of higher permissions.');
'Failed to verify because of higher permissions.', }
);
});
} }
} }
},
);
});
}, },
} satisfies CommandRegistry; } satisfies CommandRegistry;
+1 -1
View File
@@ -14,5 +14,5 @@ export type PlayerClanData = {
clan_id: number; clan_id: number;
emblem_set_id: number; emblem_set_id: number;
}; };
}; } | null;
}; };
+10 -19
View File
@@ -6,29 +6,26 @@ import {
import markdownEscape from 'markdown-escape'; import markdownEscape from 'markdown-escape';
import { NEGATIVE_COLOR } from '../constants/colors.js'; import { NEGATIVE_COLOR } from '../constants/colors.js';
import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js'; import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js';
import { Player, Players } from '../types/players.js'; import { Players } from '../types/players.js';
import { args } from './args.js'; import { args } from './args.js';
import getWargamingResponse from './getWargamingResponse.js'; import getWargamingResponse from './getWargamingResponse.js';
export default async function getBlitzAccount( export default async function getBlitzAccount(
interaction: ChatInputCommandInteraction<CacheType>, interaction: ChatInputCommandInteraction<CacheType>,
command: string,
name: string, name: string,
server: BlitzServer, server: BlitzServer,
callback: (account: Player) => void,
) { ) {
const serverName = BLITZ_SERVERS[server]; const serverName = BLITZ_SERVERS[server];
getWargamingResponse<Players>( const players = await getWargamingResponse<Players>(
`https://api.wotblitz.${server}/wotb/account/list/?application_id=${args['wargaming-application-id']}&search=${name}`, `https://api.wotblitz.${server}/wotb/account/list/?application_id=${args['wargaming-application-id']}&search=${name}`,
interaction, );
command,
async (players) => {
if ( if (
players.length > 0 && players.length > 0 &&
players[0].nickname.toLowerCase() === name.toLowerCase() players[0].nickname.toLowerCase() === name.toLowerCase()
) { ) {
callback(players[0]); return players[0];
} else { } else {
// no exact match // no exact match
await interaction.editReply({ await interaction.editReply({
@@ -40,24 +37,18 @@ export default async function getBlitzAccount(
`I couldn't find "${markdownEscape( `I couldn't find "${markdownEscape(
name, name,
)}" in the ${serverName} server. I found ${ )}" in the ${serverName} server. I found ${
players players ? (players.length < 100 ? players.length : 'over 100') : 0
? players.length < 100 } similarly spelled account${players?.length !== 1 ? 's' : ''}. ${
? players.length
: 'over 100'
: 0
} similarly spelled account${
players?.length !== 1 ? 's' : ''
}. ${
players && players.length > 0 players && players.length > 0
? `Did you mean "${markdownEscape(players[0].nickname)}"? ` ? `Did you mean "${markdownEscape(players[0].nickname)}"? `
: '' : ''
}Re-run the command and don't make typos.`, }Use the \`/verify\` command to fix any issues or re-run the command and don't make typos.`,
), ),
], ],
}); });
console.log(`Account not found for ${name} in ${serverName} server.`); console.log(`Account not found for ${name} in ${serverName} server.`);
return null;
} }
},
);
} }
+16 -24
View File
@@ -1,43 +1,35 @@
import { import { CacheType, ChatInputCommandInteraction } from 'discord.js';
CacheType,
ChatInputCommandInteraction,
EmbedBuilder,
} from 'discord.js';
import markdownEscape from 'markdown-escape'; import markdownEscape from 'markdown-escape';
import fetch from 'node-fetch'; import fetch from 'node-fetch';
import { NEGATIVE_COLOR } from '../constants/colors.js';
import { PlayerStatistics } from '../types/statistics.js'; import { PlayerStatistics } from '../types/statistics.js';
import blitzStarsError from './blitzStarsError.js'; import errorEmbed from './errorEmbed.js';
export default async function getBlitzStarsAccount( export default async function getBlitzStarsAccount(
interaction: ChatInputCommandInteraction<CacheType>, interaction: ChatInputCommandInteraction<CacheType>,
command: string,
accountId: number, accountId: number,
name: string, name: string,
callback: (account: PlayerStatistics) => void,
) { ) {
if (!interaction.deferred) await interaction.deferReply(); try {
const response = await fetch(
`https://www.blitzstars.com/api/top/player/${accountId}`,
);
const parsed = (await response.json()) as PlayerStatistics;
fetch(`https://www.blitzstars.com/api/top/player/${accountId}`) if (parsed.statistics) {
.then(async (response) => { return parsed;
const data = (await response.json()) as PlayerStatistics; } else throw new Error('No data to display');
} catch (error) {
if (data.statistics) {
callback(data);
} else {
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
new EmbedBuilder() errorEmbed(
.setTitle('No data to display') 'No data to display',
.setDescription(
`${markdownEscape(name)} is not tracked by BlitzStars.`, `${markdownEscape(name)} is not tracked by BlitzStars.`,
) ),
.setColor(NEGATIVE_COLOR),
], ],
}); });
console.log(`${name} is not tracked by BlitzStars.`); console.log(`${name} is not tracked by BlitzStars.`);
return null;
} }
})
.catch((error) => blitzStarsError(interaction, error, command));
} }
+7 -10
View File
@@ -6,30 +6,27 @@ import {
import markdownEscape from 'markdown-escape'; import markdownEscape from 'markdown-escape';
import { NEGATIVE_COLOR } from '../constants/colors.js'; import { NEGATIVE_COLOR } from '../constants/colors.js';
import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js'; import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js';
import { Clan, ClanList } from '../types/clanList.js'; import { ClanList } from '../types/clanList.js';
import { args } from './args.js'; import { args } from './args.js';
import getWargamingResponse from './getWargamingResponse.js'; import getWargamingResponse from './getWargamingResponse.js';
export default async function getClan( export default async function getClan(
interaction: ChatInputCommandInteraction<CacheType>, interaction: ChatInputCommandInteraction<CacheType>,
command: string,
name: string, name: string,
server: BlitzServer, server: BlitzServer,
callback: (account: Clan) => void,
) { ) {
const serverName = BLITZ_SERVERS[server]; const serverName = BLITZ_SERVERS[server];
getWargamingResponse<ClanList>( const clans = await getWargamingResponse<ClanList>(
`https://api.wotblitz.${server}/wotb/clans/list/?application_id=${args['wargaming-application-id']}&search=${name}`, `https://api.wotblitz.${server}/wotb/clans/list/?application_id=${args['wargaming-application-id']}&search=${name}`,
interaction, );
command,
async (clans) => {
if ( if (
clans.length > 0 && clans.length > 0 &&
(clans[0].name.toLowerCase() === name.toLowerCase() || (clans[0].name.toLowerCase() === name.toLowerCase() ||
clans[0].tag.toLowerCase() === name.toLowerCase()) clans[0].tag.toLowerCase() === name.toLowerCase())
) { ) {
callback(clans[0]); return clans[0];
} else { } else {
// no exact match // no exact match
await interaction.editReply({ await interaction.editReply({
@@ -54,7 +51,7 @@ export default async function getClan(
}); });
console.log(`Clan not found for ${name} in ${serverName} server.`); console.log(`Clan not found for ${name} in ${serverName} server.`);
return null;
} }
},
);
} }
+7 -18
View File
@@ -1,28 +1,17 @@
import { CacheType, ChatInputCommandInteraction } from 'discord.js';
import fetch from 'node-fetch'; import fetch from 'node-fetch';
import { WargamingResponse } from '../types/wargamingResponse.js'; import { WargamingResponse } from '../types/wargamingResponse.js';
import wargamingError from './wargamingError.js';
export default async function getWargamingResponse<Data extends object>( export default async function getWargamingResponse<Data extends object>(
url: string, url: string,
interaction: ChatInputCommandInteraction<CacheType>,
command: string,
callback: (data: Data) => void,
) { ) {
if (!interaction.deferred) await interaction.deferReply(); let parsed: WargamingResponse<Data>;
fetch(url) const response = await fetch(url);
.then((response) => response.json() as Promise<WargamingResponse<Data>>) parsed = (await response.json()) as WargamingResponse<Data>;
.then((response) => {
if (response.status === 'ok') { if (parsed.status === 'ok') {
callback(response.data); return parsed.data;
} else { } else {
wargamingError( throw new Error(`Wargaming response status ${parsed.status}`);
interaction,
new Error(`Status ${response.status}`),
command,
);
} }
})
.catch((error) => wargamingError(interaction, error, command));
} }