feat: infastructure for public

This commit is contained in:
TresAbhi committed 2023-04-26 00:02:10 +00:00
1 parent ab725c7f86
commit 468bca77de
6 files changed
+525 -486

No files matched your search

+34 -14
View File
@@ -1,5 +1,6 @@
import { import {
CacheType, CacheType,
ChatInputCommandInteraction,
Collection, Collection,
Interaction, Interaction,
REST, REST,
@@ -13,34 +14,53 @@ import getClientId from '../utilities/getClientId.js';
import isDev from '../utilities/isDev.js'; import isDev from '../utilities/isDev.js';
export interface CommandRegistry { export interface CommandRegistry {
inDev?: boolean; inDevelopment: boolean; // register with Skilled Bot (default: false)
data: SlashCommandBuilder; inProduction: boolean; // register with Skilled Canary (default: false)
execute: (interaction: Interaction) => void; inPublic: boolean; // registers on all servers (default: true)
command: Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'>;
execute: (interaction: ChatInputCommandInteraction<CacheType>) => void;
} }
const commandCollection = new Collection<string, CommandRegistry>();
const commands: RESTPostAPIChatInputApplicationCommandsJSONBody[] = [];
const commandFolders = readdirSync('src/commands/');
const rest = new REST().setToken(process.env.DISCORD_TOKEN!); const rest = new REST().setToken(process.env.DISCORD_TOKEN!);
const commandFolders = readdirSync('src/commands/');
const commandCollection = new Collection<string, CommandRegistry>();
const guildCommands: RESTPostAPIChatInputApplicationCommandsJSONBody[] = [];
const publicCommands: RESTPostAPIChatInputApplicationCommandsJSONBody[] = [];
for (const file of commandFolders) { for (const file of commandFolders) {
const command = (await import(`../commands/${file}`)) as CommandRegistry; const command = (await import(`../commands/${file}`))
.default as CommandRegistry;
if (isDev() ? command.inDev ?? false : true) { if (isDev() ? command.inDevelopment : command.inProduction) {
commands.push(command.data.toJSON()); if (command.inPublic) {
commandCollection.set(command.data.name, command); publicCommands.push(command.command.toJSON());
} else {
guildCommands.push(command.command.toJSON());
}
commandCollection.set(command.command.name, command);
} }
} }
try { try {
console.log(`Started refreshing ${commands.length} command(s).`); console.log(`Refreshing ${guildCommands.length} guild command(s).`);
const data = (await rest.put( const guildData = (await rest.put(
Routes.applicationGuildCommands(getClientId(), discord.guild_id), Routes.applicationGuildCommands(getClientId(), discord.guild_id),
{ body: commands }, { body: guildCommands },
)) as RESTPostAPIChatInputApplicationCommandsJSONBody[]; )) as RESTPostAPIChatInputApplicationCommandsJSONBody[];
console.log(`Successfully reloaded ${data.length} command(s).`); console.log(`Successfully refreshed ${guildData.length} guild command(s).`);
console.log(`Refreshing ${publicCommands.length} public command(s).`);
const publicData = (await rest.put(
Routes.applicationCommands(getClientId()),
{ body: publicCommands },
)) as RESTPostAPIChatInputApplicationCommandsJSONBody[];
console.log(`Successfully refreshed ${publicData.length} public command(s).`);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
} }
+131 -126
View File
@@ -1,9 +1,5 @@
import { import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
CacheType, import { CommandRegistry } from '../behaviors/interactionCreate.js';
ChatInputCommandInteraction,
EmbedBuilder,
SlashCommandBuilder,
} from 'discord.js';
import { NEGATIVE_COLOR, POSITIVE_COLOR } from '../constants/colors.js'; import { NEGATIVE_COLOR, POSITIVE_COLOR } from '../constants/colors.js';
import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js'; import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js';
import blitzLinks from '../utilities/blitzLinks.js'; import blitzLinks from '../utilities/blitzLinks.js';
@@ -22,131 +18,140 @@ export const CLANS = {
}, },
}; };
export async function execute( export default {
interaction: ChatInputCommandInteraction<CacheType>, inProduction: true,
) { inDevelopment: false,
const ign = interaction.options.getString('ign')!; inPublic: false,
const server = interaction.options.getString('server') as BlitzServer;
const clan = interaction.options.getString('clan') as keyof typeof CLANS;
getBlitzAccount(interaction, ign, server, async (account) => { command: new SlashCommandBuilder()
getBlitzStarsAccount(interaction, account.account_id, ign, async (data) => { .setName('eligible')
const issues: string[] = []; .setDescription("Gets the user's eligibility for Skilled clans")
.addStringOption((option) =>
option
.setName('clan')
.setDescription('The Skilled clan you are checking')
.addChoices(
{ name: CLANS.sklld.name, value: 'sklld' },
{ name: CLANS.smri.name, value: 'smri' },
)
.setRequired(true),
)
.addStringOption((option) =>
option
.setName('server')
.setDescription('The Blitz server you are in')
.addChoices(
{ name: BLITZ_SERVERS.com, value: 'com' },
{ name: BLITZ_SERVERS.eu, value: 'eu' },
{ name: BLITZ_SERVERS.asia, value: 'asia' },
)
.setRequired(true),
)
.addStringOption((option) =>
option
.setName('ign')
.setDescription('The username you use in Blitz')
.setRequired(true),
),
if (clan === 'sklld') { execute(interaction) {
if (data.period30d.all.battles < 150) { const ign = interaction.options.getString('ign')!;
issues.push( const server = interaction.options.getString('server') as BlitzServer;
`**Battles**: ${data.period30d.all.battles} (${ const clan = interaction.options.getString('clan') as keyof typeof CLANS;
data.period30d.all.battles - 150
})`,
);
}
if (data.period30d.avg_tier < 8) {
issues.push(
`**Tier**: ${data.period30d.avg_tier.toFixed(2)} (${(
data.period30d.avg_tier - 8
).toFixed(2)})`,
);
}
if (data.period30d.special.winrate < 60) {
issues.push(
`**Winrate**: ${data.period30d.special.winrate.toFixed(2)}% (${(
data.period30d.special.winrate - 60
).toFixed(2)}%)`,
);
}
if (data.period30d.wn8 < 2100) {
issues.push(
`**WN8**: ${data.period30d.wn8.toFixed(0)} (${(
data.period30d.wn8 - 2100
).toFixed(0)})`,
);
}
if (data.period30d.special.dpb < 2400) {
issues.push(
`**Damage per battle**: ${data.period30d.special.dpb.toFixed(
0,
)} (${(data.period30d.special.dpb - 2400).toFixed(0)})`,
);
}
} else {
if (data.statistics.all.battles < 1500) {
issues.push(
`**Battles**: ${data.statistics.all.battles} (${
data.statistics.all.battles - 1500
})`,
);
}
if (data.statistics.special.winrate < 53) {
issues.push(
`**Winrate**: ${data.statistics.special.winrate.toFixed(2)}% (${(
data.statistics.special.winrate - 53
).toFixed(2)}%)`,
);
}
}
const eligible = issues.length === 0; getBlitzAccount(interaction, ign, server, async (account) => {
getBlitzStarsAccount(
interaction,
account.account_id,
ign,
async (data) => {
const issues: string[] = [];
await interaction.reply({ if (clan === 'sklld') {
embeds: [ if (data.period30d.all.battles < 150) {
poweredByBlitzStars( issues.push(
new EmbedBuilder() `**Battles**: ${data.period30d.all.battles} (${
.setTitle( data.period30d.all.battles - 150
`${data.nickname} is ${eligible ? '' : 'not '}eligible for ${ })`,
CLANS[clan].name );
}`, }
) if (data.period30d.avg_tier < 8) {
.setColor(eligible ? POSITIVE_COLOR : NEGATIVE_COLOR) issues.push(
.setDescription( `**Tier**: ${data.period30d.avg_tier.toFixed(2)} (${(
`${ data.period30d.avg_tier - 8
eligible ).toFixed(2)})`,
? `${data.nickname} meets all the requirements set for ${CLANS[clan].name}.` );
: `${data.nickname}'s shortcomings for ${ }
CLANS[clan].name if (data.period30d.special.winrate < 60) {
} (${ issues.push(
clan === 'sklld' ? '30 days stats' : 'career stats' `**Winrate**: ${data.period30d.special.winrate.toFixed(2)}% (${(
}):\n\n${issues.join('\n')}` data.period30d.special.winrate - 60
}\n\n${blitzLinks(data)}`, ).toFixed(2)}%)`,
);
}
if (data.period30d.wn8 < 2100) {
issues.push(
`**WN8**: ${data.period30d.wn8.toFixed(0)} (${(
data.period30d.wn8 - 2100
).toFixed(0)})`,
);
}
if (data.period30d.special.dpb < 2400) {
issues.push(
`**Damage per battle**: ${data.period30d.special.dpb.toFixed(
0,
)} (${(data.period30d.special.dpb - 2400).toFixed(0)})`,
);
}
} else {
if (data.statistics.all.battles < 1500) {
issues.push(
`**Battles**: ${data.statistics.all.battles} (${
data.statistics.all.battles - 1500
})`,
);
}
if (data.statistics.special.winrate < 53) {
issues.push(
`**Winrate**: ${data.statistics.special.winrate.toFixed(
2,
)}% (${(data.statistics.special.winrate - 53).toFixed(2)}%)`,
);
}
}
const eligible = issues.length === 0;
await interaction.reply({
embeds: [
poweredByBlitzStars(
new EmbedBuilder()
.setTitle(
`${data.nickname} is ${
eligible ? '' : 'not '
}eligible for ${CLANS[clan].name}`,
)
.setColor(eligible ? POSITIVE_COLOR : NEGATIVE_COLOR)
.setDescription(
`${
eligible
? `${data.nickname} meets all the requirements set for ${CLANS[clan].name}.`
: `${data.nickname}'s shortcomings for ${
CLANS[clan].name
} (${
clan === 'sklld' ? '30 days stats' : 'career stats'
}):\n\n${issues.join('\n')}`
}\n\n${blitzLinks(data)}`,
),
), ),
), ],
], });
});
console.log( console.log(
`Showing ${data.nickname}'s eligibility for ${CLANS[clan].name}`, `Showing ${data.nickname}'s eligibility for ${CLANS[clan].name}`,
);
},
); );
}); });
}); },
} } satisfies CommandRegistry;
export const data = new SlashCommandBuilder()
.setName('eligible')
.setDescription("Gets the user's eligibility for Skilled clans")
.addStringOption((option) =>
option
.setName('clan')
.setDescription('The Skilled clan you are checking')
.addChoices(
{ name: CLANS.sklld.name, value: 'sklld' },
{ name: CLANS.smri.name, value: 'smri' },
)
.setRequired(true),
)
.addStringOption((option) =>
option
.setName('server')
.setDescription('The Blitz server you are in')
.addChoices(
{ name: BLITZ_SERVERS.com, value: 'com' },
{ name: BLITZ_SERVERS.eu, value: 'eu' },
{ name: BLITZ_SERVERS.asia, value: 'asia' },
)
.setRequired(true),
)
.addStringOption((option) =>
option
.setName('ign')
.setDescription('The username you use in Blitz')
.setRequired(true),
);
+85 -83
View File
@@ -1,10 +1,6 @@
import { import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
CacheType,
ChatInputCommandInteraction,
EmbedBuilder,
SlashCommandBuilder,
} from 'discord.js';
import fetch from 'node-fetch'; import fetch from 'node-fetch';
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 { ClanDetails } from '../types/clanDetails.js'; import { ClanDetails } from '../types/clanDetails.js';
import { PlayerPersonalData } from '../types/playerPersonalData.js'; import { PlayerPersonalData } from '../types/playerPersonalData.js';
@@ -12,85 +8,91 @@ import { CLANS } from './eligible.js';
const DEFAULT_THRESHOLD = 7; const DEFAULT_THRESHOLD = 7;
export async function execute( export default {
interaction: ChatInputCommandInteraction<CacheType>, inProduction: true,
) { inDevelopment: false,
const threshold = inPublic: false,
interaction.options.getNumber('threshold')! ?? DEFAULT_THRESHOLD;
const time = new Date().getTime() / 1000;
const clanName = interaction.options.getString('clan') as keyof typeof CLANS;
const clanData = (await (
await fetch(
`https://api.wotblitz.com/wotb/clans/info/?application_id=${process.env.WARGAMING_APPLICATION_ID}&clan_id=${CLANS[clanName].id}`,
)
).json()) as ClanDetails;
const clan = clanData.data[CLANS[clanName].id];
const memberIds = clan.members_ids;
const playerPersonalData = (await (
await fetch(
`https://api.wotblitz.com/wotb/account/info/?application_id=${
process.env.WARGAMING_APPLICATION_ID
}&account_id=${memberIds.join(',')}`,
)
).json()) as PlayerPersonalData;
const inactiveInfo = memberIds command: new SlashCommandBuilder()
.map((memberId) => { .setName('inactive')
const member = playerPersonalData.data[memberId]; .setDescription('Lists all inactive players')
const inactiveDays = (time - member.last_battle_time) / 60 / 60 / 24; .addStringOption((option) =>
option
return [member.nickname, inactiveDays] as const; .setName('clan')
}) .setDescription('The Skilled clan you are checking')
.filter(([, inactiveDays]) => inactiveDays >= threshold) .addChoices(
.sort((a, b) => b[1] - a[1]) { name: CLANS.sklld.name, value: 'sklld' },
.map(([nickname, inactiveDays]) => { { name: CLANS.smri.name, value: 'smri' },
const days = Math.floor(inactiveDays);
return `**${nickname}**: ${days} day${days === 1 ? '' : 's'}`;
});
const hasInactiveMembers = inactiveInfo.length > 0;
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor(hasInactiveMembers ? NEGATIVE_COLOR : POSITIVE_COLOR)
.setTitle(
hasInactiveMembers
? `${CLANS[clanName].name}'s inactive members`
: `No inactive members in ${CLANS[clanName].name}`,
) )
.setRequired(true),
)
.addNumberOption((option) =>
option
.setName('threshold')
.setDescription( .setDescription(
hasInactiveMembers `The number of days inactive (default: ${DEFAULT_THRESHOLD})`,
? `Players that exceed the threshold of ${threshold} days:\n\n${inactiveInfo.join( )
'\n', .setMinValue(0),
)}` ),
: `No players exceed the threshold of ${threshold} days.`,
),
],
});
console.log( async execute(interaction) {
`Displaying inactive members in ${CLANS[clanName].name} for ${threshold} days`, const threshold =
); interaction.options.getNumber('threshold')! ?? DEFAULT_THRESHOLD;
} const time = new Date().getTime() / 1000;
const clanName = interaction.options.getString(
'clan',
) as keyof typeof CLANS;
const clanData = (await (
await fetch(
`https://api.wotblitz.com/wotb/clans/info/?application_id=${process.env.WARGAMING_APPLICATION_ID}&clan_id=${CLANS[clanName].id}`,
)
).json()) as ClanDetails;
const clan = clanData.data[CLANS[clanName].id];
const memberIds = clan.members_ids;
const playerPersonalData = (await (
await fetch(
`https://api.wotblitz.com/wotb/account/info/?application_id=${
process.env.WARGAMING_APPLICATION_ID
}&account_id=${memberIds.join(',')}`,
)
).json()) as PlayerPersonalData;
export const data = new SlashCommandBuilder() const inactiveInfo = memberIds
.setName('inactive') .map((memberId) => {
.setDescription('Lists all inactive players') const member = playerPersonalData.data[memberId];
.addStringOption((option) => const inactiveDays = (time - member.last_battle_time) / 60 / 60 / 24;
option
.setName('clan') return [member.nickname, inactiveDays] as const;
.setDescription('The Skilled clan you are checking') })
.addChoices( .filter(([, inactiveDays]) => inactiveDays >= threshold)
{ name: CLANS.sklld.name, value: 'sklld' }, .sort((a, b) => b[1] - a[1])
{ name: CLANS.smri.name, value: 'smri' }, .map(([nickname, inactiveDays]) => {
) const days = Math.floor(inactiveDays);
.setRequired(true), return `**${nickname}**: ${days} day${days === 1 ? '' : 's'}`;
) });
.addNumberOption((option) => const hasInactiveMembers = inactiveInfo.length > 0;
option
.setName('threshold') await interaction.reply({
.setDescription( embeds: [
`The number of days inactive (default: ${DEFAULT_THRESHOLD})`, new EmbedBuilder()
) .setColor(hasInactiveMembers ? NEGATIVE_COLOR : POSITIVE_COLOR)
.setMinValue(0), .setTitle(
); hasInactiveMembers
? `${CLANS[clanName].name}'s inactive members`
: `No inactive members in ${CLANS[clanName].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 ${CLANS[clanName].name} for ${threshold} days`,
);
},
} satisfies CommandRegistry;
+120 -110
View File
@@ -1,9 +1,5 @@
import { import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
CacheType, import { CommandRegistry } from '../behaviors/interactionCreate.js';
ChatInputCommandInteraction,
EmbedBuilder,
SlashCommandBuilder,
} from 'discord.js';
import { SKILLED_COLOR } from '../constants/colors.js'; import { SKILLED_COLOR } from '../constants/colors.js';
import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js'; import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js';
import blitzLinks from '../utilities/blitzLinks.js'; import blitzLinks from '../utilities/blitzLinks.js';
@@ -11,113 +7,127 @@ import getBlitzAccount from '../utilities/getBlitzAccount.js';
import getBlitzStarsAccount from '../utilities/getBlitzStarsAccount.js'; import getBlitzStarsAccount from '../utilities/getBlitzStarsAccount.js';
import poweredByBlitzStars from '../utilities/poweredByBlitzStars.js'; import poweredByBlitzStars from '../utilities/poweredByBlitzStars.js';
export async function execute( export default {
interaction: ChatInputCommandInteraction<CacheType>, inProduction: true,
) { inDevelopment: true,
const ign = interaction.options.getString('ign')!; inPublic: true,
const server = interaction.options.getString('server') as BlitzServer;
const period = interaction.options.getString('period')! as
| '30'
| '90'
| 'career';
getBlitzAccount(interaction, ign, server, async (account) => { command: new SlashCommandBuilder()
getBlitzStarsAccount(interaction, account.account_id, ign, async (data) => { .setName('stats')
{ .setDescription("Gets the user's in-game statistics")
const stats = .addStringOption((option) =>
period === 'career' ? data.statistics : data[`period${period}d`]; option
.setName('period')
.setDescription('The last number of days of stats')
.setChoices(
{ name: '30 Days', value: '30' },
{ name: '90 Days', value: '90' },
{ name: 'Career', value: 'career' },
)
.setRequired(true),
)
.addStringOption((option) =>
option
.setName('server')
.setDescription('The Blitz server you are in')
.addChoices(
{ name: BLITZ_SERVERS.com, value: 'com' },
{ name: BLITZ_SERVERS.eu, value: 'eu' },
{ name: BLITZ_SERVERS.asia, value: 'asia' },
)
.setRequired(true),
)
.addStringOption((option) =>
option
.setName('ign')
.setDescription('The username you use in Blitz')
.setRequired(true),
),
await interaction.reply({ execute(interaction) {
embeds: [ const ign = interaction.options.getString('ign')!;
poweredByBlitzStars( const server = interaction.options.getString('server') as BlitzServer;
new EmbedBuilder() const period = interaction.options.getString('period')! as
.setColor(SKILLED_COLOR) | '30'
.setTitle( | '90'
`${data.nickname}'s ${ | 'career';
period === 'career' ? period : `${period} day`
} stats`, getBlitzAccount(interaction, ign, server, async (account) => {
) getBlitzStarsAccount(
.setDescription( interaction,
`${[ account.account_id,
['Winrate', `${stats.special.winrate.toFixed(2)}%`], ign,
['Survival', `${stats.special.survivalRate.toFixed(2)}%`], async (data) => {
[ {
'Accuracy', const stats =
`${((stats.all.hits / stats.all.shots) * 100).toFixed( period === 'career' ? data.statistics : data[`period${period}d`];
2,
)}%`, await interaction.reply({
], embeds: [
['WN8', stats.wn8.toFixed(0)], poweredByBlitzStars(
['WN7', stats.wn7.toFixed(0)], new EmbedBuilder()
[], .setColor(SKILLED_COLOR)
['Battles', stats.all.battles], .setTitle(
['Wins', stats.all.wins], `${data.nickname}'s ${
['Losses', stats.all.losses], period === 'career' ? period : `${period} day`
['Average tier', stats.avg_tier.toFixed(2)], } stats`,
[],
['Hits per battle', stats.special.hpb.toFixed(2)],
['Damage per battle', stats.special.dpb.toFixed(0)],
['Kills per battle', stats.special.kpb.toFixed(2)],
['Spots per battle', stats.special.spb.toFixed(2)],
[
'Shots per battle',
(stats.all.shots / stats.all.battles).toFixed(2),
],
[
'Hits per battle',
(stats.all.hits / stats.all.battles).toFixed(2),
],
[
'XP per battle',
(stats.all.xp / stats.all.battles).toFixed(0),
],
[],
['Damage ratio', stats.special.damageRatio.toFixed(2)],
['Kills to death ratio', stats.special.kdr.toFixed(2)],
]
.map((array) =>
array.length === 0 ? '' : `**${array[0]}**: ${array[1]}`,
) )
.join('\n')}\n\n${blitzLinks(data)}`, .setDescription(
`${[
['Winrate', `${stats.special.winrate.toFixed(2)}%`],
[
'Survival',
`${stats.special.survivalRate.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)],
[],
['Hits per battle', stats.special.hpb.toFixed(2)],
['Damage per battle', stats.special.dpb.toFixed(0)],
['Kills per battle', stats.special.kpb.toFixed(2)],
['Spots per battle', stats.special.spb.toFixed(2)],
[
'Shots per battle',
(stats.all.shots / stats.all.battles).toFixed(2),
],
[
'Hits per battle',
(stats.all.hits / stats.all.battles).toFixed(2),
],
[
'XP per battle',
(stats.all.xp / stats.all.battles).toFixed(0),
],
[],
['Damage ratio', stats.special.damageRatio.toFixed(2)],
['Kills to death ratio', stats.special.kdr.toFixed(2)],
]
.map((array) =>
array.length === 0
? ''
: `**${array[0]}**: ${array[1]}`,
)
.join('\n')}\n\n${blitzLinks(data)}`,
),
), ),
), ],
], });
});
console.log(`Showing ${data.nickname}'s ${period} stats`); console.log(`Showing ${data.nickname}'s ${period} stats`);
} }
},
);
}); });
}); },
} } satisfies CommandRegistry;
export const data = new SlashCommandBuilder()
.setName('stats')
.setDescription("Gets the user's in-game statistics")
.addStringOption((option) =>
option
.setName('period')
.setDescription('The last number of days of stats')
.setChoices(
{ name: '30 Days', value: '30' },
{ name: '90 Days', value: '90' },
{ name: 'Career', value: 'career' },
)
.setRequired(true),
)
.addStringOption((option) =>
option
.setName('server')
.setDescription('The Blitz server you are in')
.addChoices(
{ name: BLITZ_SERVERS.com, value: 'com' },
{ name: BLITZ_SERVERS.eu, value: 'eu' },
{ name: BLITZ_SERVERS.asia, value: 'asia' },
)
.setRequired(true),
)
.addStringOption((option) =>
option
.setName('ign')
.setDescription('The username you use in Blitz')
.setRequired(true),
);
+74 -74
View File
@@ -1,85 +1,85 @@
import { import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
CacheType,
ChatInputCommandInteraction,
EmbedBuilder,
SlashCommandBuilder,
} from 'discord.js';
import fetch from 'node-fetch'; import fetch from 'node-fetch';
import { CommandRegistry } from '../behaviors/interactionCreate.js';
import { SKILLED_COLOR } from '../constants/colors.js'; import { SKILLED_COLOR } from '../constants/colors.js';
import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js'; import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js';
import { TanksStats } from '../types/tanksStats.js'; import { TanksStats } from '../types/tanksStats.js';
import getBlitzAccount from '../utilities/getBlitzAccount.js'; import getBlitzAccount from '../utilities/getBlitzAccount.js';
import { tankTypeEmojis, tankopedia } from '../utilities/tankopedia.js'; import { tankTypeEmojis, tankopedia } from '../utilities/tankopedia.js';
export async function execute( export default {
interaction: ChatInputCommandInteraction<CacheType>, inProduction: true,
) { inDevelopment: false,
const server = interaction.options.getString('server') as BlitzServer; inPublic: true,
const ign = interaction.options.getString('ign')!;
const tier = Math.round(interaction.options.getNumber('tier')!);
getBlitzAccount(interaction, ign, server, async (account) => { command: new SlashCommandBuilder()
const tankStats = (await ( .setName('tanks')
await fetch( .setDescription("Shows a player's owned tanks")
`https://api.wotblitz.${server}/wotb/tanks/stats/?application_id=${process.env.WARGAMING_APPLICATION_ID}&account_id=${account.account_id}`, .addStringOption((option) =>
) option
).json()) as TanksStats; .setName('server')
.setDescription('The Blitz server you are in')
.setRequired(true)
.addChoices(
{ name: BLITZ_SERVERS.com, value: 'com' },
{ name: BLITZ_SERVERS.eu, value: 'eu' },
{ name: BLITZ_SERVERS.asia, value: 'asia' },
),
)
.addStringOption((option) =>
option
.setName('ign')
.setDescription('The username you use in Blitz')
.setRequired(true),
)
.addNumberOption((option) =>
option
.setName('tier')
.setDescription('The tier you want to see (default: all tiers)')
.setMinValue(1)
.setMaxValue(10)
.setRequired(true),
),
const tanks = tankStats.data[account.account_id]!.map( execute(interaction) {
(tankData) => tankopedia.data[tankData.tank_id], const server = interaction.options.getString('server') as BlitzServer;
).filter((tank) => tank.tier === tier); const ign = interaction.options.getString('ign')!;
const tier = Math.round(interaction.options.getNumber('tier')!);
interaction.reply({ getBlitzAccount(interaction, ign, server, async (account) => {
embeds: [ const tankStats = (await (
new EmbedBuilder() await fetch(
.setTitle( `https://api.wotblitz.${server}/wotb/tanks/stats/?application_id=${process.env.WARGAMING_APPLICATION_ID}&account_id=${account.account_id}`,
`${account.nickname}'s owned ${ )
tier === null ? '' : `tier ${tier} ` ).json()) as TanksStats;
}tanks`,
) const tanks = tankStats.data[account.account_id]!.map(
.setDescription( (tankData) => tankopedia.data[tankData.tank_id],
tanks.length === 0 ).filter((tank) => tank.tier === tier);
? `No tanks found for player in tier ${tier}`
: tanks interaction.reply({
.map( embeds: [
(tank) => new EmbedBuilder()
`${tankTypeEmojis[tank.type]} ${tank.name} ${ .setTitle(
tank.is_premium ? '⭐' : '' `${account.nickname}'s owned ${
}`, tier === null ? '' : `tier ${tier} `
) }tanks`,
.join('\n'), )
) .setDescription(
.setColor(SKILLED_COLOR), tanks.length === 0
], ? `No tanks found for player in tier ${tier}`
: tanks
.map(
(tank) =>
`${tankTypeEmojis[tank.type]} ${tank.name} ${
tank.is_premium ? '⭐' : ''
}`,
)
.join('\n'),
)
.setColor(SKILLED_COLOR),
],
});
}); });
}); },
} } satisfies CommandRegistry;
export const data = new SlashCommandBuilder()
.setName('tanks')
.setDescription("Shows a player's owned tanks")
.addStringOption((option) =>
option
.setName('server')
.setDescription('The Blitz server you are in')
.setRequired(true)
.addChoices(
{ name: BLITZ_SERVERS.com, value: 'com' },
{ name: BLITZ_SERVERS.eu, value: 'eu' },
{ name: BLITZ_SERVERS.asia, value: 'asia' },
),
)
.addStringOption((option) =>
option
.setName('ign')
.setDescription('The username you use in Blitz')
.setRequired(true),
)
.addNumberOption((option) =>
option
.setName('tier')
.setDescription('The tier you want to see (default: all tiers)')
.setMinValue(1)
.setMaxValue(10)
.setRequired(true),
);
+81 -79
View File
@@ -1,90 +1,92 @@
import { import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
CacheType,
ChatInputCommandInteraction,
EmbedBuilder,
SlashCommandBuilder,
} from 'discord.js';
import fetch from 'node-fetch'; import fetch from 'node-fetch';
import discord from '../../discord.json' assert { type: 'json' }; import discord from '../../discord.json' assert { type: 'json' };
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 { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js'; import { BLITZ_SERVERS, BlitzServer } from '../constants/servers.js';
import { PlayerClanData } from '../types/playerClanData.js'; import { PlayerClanData } from '../types/playerClanData.js';
import getBlitzAccount from '../utilities/getBlitzAccount.js'; import getBlitzAccount from '../utilities/getBlitzAccount.js';
export async function execute( export default {
interaction: ChatInputCommandInteraction<CacheType>, inProduction: true,
) { inDevelopment: false,
const ign = interaction.options.getString('ign')!; inPublic: false,
const server = interaction.options.getString('server') as BlitzServer;
getBlitzAccount(interaction, ign, server, async (account) => { command: new SlashCommandBuilder()
// good match .setName('verify')
const clanData = (await fetch( .setDescription('Verifies the user with Blitz')
`https://api.wotblitz.${server}/wotb/clans/accountinfo/?application_id=${process.env.WARGAMING_APPLICATION_ID}&account_id=${account.account_id}&extra=clan`, .addStringOption((option) =>
).then((response) => response.json())) as PlayerClanData; option
const clan = clanData.data[account.account_id].clan; .setName('server')
const clanTag = clan === null ? '' : ` [${clan!.tag}]`; .setDescription('The Blitz server you are in')
.setRequired(true)
.addChoices(
{ name: BLITZ_SERVERS.com, value: 'com' },
{ name: BLITZ_SERVERS.eu, value: 'eu' },
{ name: BLITZ_SERVERS.asia, value: 'asia' },
),
)
.addStringOption((option) =>
option
.setName('ign')
.setDescription('The username you use in Blitz')
.setRequired(true),
),
if (interaction.member && interaction.guild) { execute(interaction) {
const member = interaction.guild?.members.cache.get( const ign = interaction.options.getString('ign')!;
interaction.member?.user.id, const server = interaction.options.getString('server') as BlitzServer;
);
member getBlitzAccount(interaction, ign, server, async (account) => {
?.setNickname(`${ign}${clanTag}`) // good match
.then(async () => { const clanData = (await fetch(
await member.roles.remove(discord.verify_role); `https://api.wotblitz.${server}/wotb/clans/accountinfo/?application_id=${process.env.WARGAMING_APPLICATION_ID}&account_id=${account.account_id}&extra=clan`,
await member.roles.add(discord.peasant_role); ).then((response) => response.json())) as PlayerClanData;
await interaction.reply({ const clan = clanData.data[account.account_id].clan;
embeds: [ const clanTag = clan === null ? '' : ` [${clan!.tag}]`;
new EmbedBuilder()
.setColor(POSITIVE_COLOR) if (interaction.member && interaction.guild) {
.setTitle(`${interaction.user.username} is verified`) const member = interaction.guild?.members.cache.get(
.setDescription(`The user is now verified as ${ign}${clanTag}`), interaction.member?.user.id,
], );
member
?.setNickname(`${ign}${clanTag}`)
.then(async () => {
await member.roles.remove(discord.verify_role);
await member.roles.add(discord.peasant_role);
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor(POSITIVE_COLOR)
.setTitle(`${interaction.user.username} is verified`)
.setDescription(
`The user is now verified as ${ign}${clanTag}`,
),
],
});
console.log(
`${interaction.user.username} verified as ${ign}${clanTag}`,
);
})
.catch(async () => {
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor(NEGATIVE_COLOR)
.setTitle(`${interaction.user.username} failed to verify`)
.setDescription(
'I may not have the permission to change your nickname.',
),
],
});
console.warn(
`${interaction.user.username} failed to verify as ${ign}${clanTag}`,
);
}); });
}
console.log( });
`${interaction.user.username} verified as ${ign}${clanTag}`, },
); } satisfies CommandRegistry;
})
.catch(async () => {
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor(NEGATIVE_COLOR)
.setTitle(`${interaction.user.username} failed to verify`)
.setDescription(
'I may not have the permission to change your nickname.',
),
],
});
console.warn(
`${interaction.user.username} failed to verify as ${ign}${clanTag}`,
);
});
}
});
}
export const data = new SlashCommandBuilder()
.setName('verify')
.setDescription('Verifies the user with Blitz')
.addStringOption((option) =>
option
.setName('server')
.setDescription('The Blitz server you are in')
.setRequired(true)
.addChoices(
{ name: BLITZ_SERVERS.com, value: 'com' },
{ name: BLITZ_SERVERS.eu, value: 'eu' },
{ name: BLITZ_SERVERS.asia, value: 'asia' },
),
)
.addStringOption((option) =>
option
.setName('ign')
.setDescription('The username you use in Blitz')
.setRequired(true),
);