feat: refresh button

This commit is contained in:
TresAbhi committed 2023-06-25 02:32:56 +00:00
1 parent ae2d12a629
commit 58f5b894f9
30 files changed
+479 -299

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@ import { tankAverages } from '../core/blitzstars/tankAverages.js';
import cleanTable from '../core/interaction/cleanTable.js';
import infoEmbed from '../core/interaction/infoEmbed.js';
import getClientId from '../core/process/getClientId.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
import { client } from '../index.js';
const executionStart = new Date().getTime();
+1 -1
View File
@@ -13,7 +13,7 @@ import positiveEmbed from '../core/interaction/positiveEmbed.js';
import addUsernameOption from '../core/options/addUsernameOption.js';
import resolvePlayer from '../core/options/resolvePlayer.js';
import { WARGAMING_APPLICATION_ID } from '../core/process/args.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
import { AccountInfo } from '../types/accountInfo.js';
export type SkilledClan = 'SKLLD' | 'SMRI';
+1 -1
View File
@@ -5,7 +5,7 @@ import resolveTankId from '../core/blitz/resolveTankId.js';
import addStatsSubCommandGroups from '../core/options/addStatsSubCommandGroups.js';
import resolvePeriod from '../core/options/resolvePeriod.js';
import resolvePlayer from '../core/options/resolvePlayer.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
import evolution from '../renderers/evolution.js';
import { StatType } from '../renderers/stats.js';
+1 -1
View File
@@ -5,7 +5,7 @@ import {
CommandRegistry,
guildCommands,
publicCommands,
} from '../events/interactionCreate.js';
} from '../events/interactionCreate/index.js';
import { client } from '../index.js';
export default {
+1 -1
View File
@@ -10,7 +10,7 @@ import getBlitzClan from '../core/blitz/getBlitzClan.js';
import getWargamingResponse from '../core/blitz/getWargamingResponse.js';
import addClanChoices from '../core/options/addClanChoices.js';
import { WARGAMING_APPLICATION_ID } from '../core/process/args.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
import { AccountInfo } from '../types/accountInfo.js';
import { ClanInfo } from '../types/clanInfo.js';
+1 -1
View File
@@ -16,7 +16,7 @@ import {
import addUsernameOption from '../core/options/addUsernameOption.js';
import resolvePlayer from '../core/options/resolvePlayer.js';
import { WARGAMING_APPLICATION_ID } from '../core/process/args.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
import { AccountInfo } from '../types/accountInfo.js';
import { PlayerClanData } from '../types/playerClanData.js';
+1 -1
View File
@@ -1,5 +1,5 @@
import { SlashCommandBuilder } from 'discord.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
export default {
inProduction: true,
+1 -1
View File
@@ -8,7 +8,7 @@ import infoEmbed from '../core/interaction/infoEmbed.js';
import addUsernameOption from '../core/options/addUsernameOption.js';
import resolvePlayer from '../core/options/resolvePlayer.js';
import { WARGAMING_APPLICATION_ID } from '../core/process/args.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
import { AccountAchievements } from '../types/accountAchievements.js';
import { AccountInfo } from '../types/accountInfo.js';
+1 -1
View File
@@ -7,7 +7,7 @@ import infoEmbed from '../core/interaction/infoEmbed.js';
import addUsernameOption from '../core/options/addUsernameOption.js';
import resolvePlayer from '../core/options/resolvePlayer.js';
import { WARGAMING_APPLICATION_ID } from '../core/process/args.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
import { AccountInfo } from '../types/accountInfo.js';
export default {
+1 -1
View File
@@ -6,7 +6,7 @@ import infoEmbed from '../core/interaction/infoEmbed.js';
import addClanChoices from '../core/options/addClanChoices.js';
import addServerChoices from '../core/options/addServerChoices.js';
import { WARGAMING_APPLICATION_ID } from '../core/process/args.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
import { ClanList } from '../types/clanList.js';
export default {
+1 -1
View File
@@ -7,7 +7,7 @@ import infoEmbed from '../core/interaction/infoEmbed.js';
import addServerChoices from '../core/options/addServerChoices.js';
import addUsernameOption from '../core/options/addUsernameOption.js';
import { WARGAMING_APPLICATION_ID } from '../core/process/args.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
import { AccountList } from '../types/accountList.js';
export default {
+1 -1
View File
@@ -4,7 +4,7 @@ import markdownEscape from 'markdown-escape';
import { TANK_NAMES } from '../core/blitz/tankopedia.js';
import infoEmbed from '../core/interaction/infoEmbed.js';
import addTankChoices from '../core/options/addTankChoices.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
export default {
inProduction: true,
+34 -2
View File
@@ -1,11 +1,16 @@
import { SlashCommandBuilder } from 'discord.js';
import { CYCLIC_API } from '../constants/cyclic.js';
import tanksAutocomplete from '../core/autocomplete/tanks.js';
import usernameAutocomplete from '../core/autocomplete/username.js';
import resolveTankId from '../core/blitz/resolveTankId.js';
import interactionToURL from '../core/interaction/interactionToURL.js';
import linkButton from '../core/interaction/linkButton.js';
import primaryButton from '../core/interaction/primaryButton.js';
import { Period } from '../core/options/addPeriodSubCommands.js';
import addStatsSubCommandGroups from '../core/options/addStatsSubCommandGroups.js';
import resolvePeriod from '../core/options/resolvePeriod.js';
import resolvePlayer from '../core/options/resolvePlayer.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
import stats, { StatType } from '../renderers/stats.js';
export default {
@@ -23,16 +28,43 @@ export default {
const commandGroup = interaction.options.getSubcommandGroup(
true,
) as StatType;
const subcommand = interaction.options.getSubcommand() as Period;
const player = await resolvePlayer(interaction);
const period = resolvePeriod(interaction);
const tankIdRaw = interaction.options.getString('tank')!;
const tankId = commandGroup === 'tank' ? resolveTankId(tankIdRaw) : 0;
const start = interaction.options.getInteger('start');
const end = interaction.options.getInteger('end');
const path = `stats/${commandGroup}/${subcommand}?server=${
player.server
}&id=${player.id}&tankId=${tankId}&start=${start ?? 0}&end=${end ?? 0}`;
return await stats(commandGroup, period, player, tankId);
interactionToURL(interaction);
return [
await stats(commandGroup, period, player, tankId),
primaryButton(path, 'Refresh'),
linkButton(path, 'Embed'),
];
},
autocomplete: (interaction) => {
usernameAutocomplete(interaction);
tanksAutocomplete(interaction);
},
async button(interaction) {
const url = new URL(`${CYCLIC_API}/${interaction.customId}`);
const path = url.pathname.split('/').filter(Boolean);
const commandGroup = path[1] as StatType;
const period = resolvePeriod(interaction);
const player = await resolvePlayer(interaction);
return await stats(
commandGroup,
period,
player,
parseInt(url.searchParams.get('tankId')!),
);
},
} satisfies CommandRegistry;
+1 -1
View File
@@ -2,7 +2,7 @@ import { SlashCommandBuilder } from 'discord.js';
import usernameAutocomplete from '../core/autocomplete/username.js';
import addUsernameOption from '../core/options/addUsernameOption.js';
import resolvePlayer from '../core/options/resolvePlayer.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
import today from '../renderers/today.js';
export default {
+1 -1
View File
@@ -8,7 +8,7 @@ import positiveEmbed from '../core/interaction/positiveEmbed.js';
import addUsernameOption from '../core/options/addUsernameOption.js';
import resolvePlayer from '../core/options/resolvePlayer.js';
import { WARGAMING_APPLICATION_ID } from '../core/process/args.js';
import { CommandRegistry } from '../events/interactionCreate.js';
import { CommandRegistry } from '../events/interactionCreate/index.js';
import { AccountInfo } from '../types/accountInfo.js';
import { PlayerClanData } from '../types/playerClanData.js';
+1
View File
@@ -0,0 +1 @@
export const CYCLIC_API = 'https://blitzkrieg.cyclic.app';
+20
View File
@@ -0,0 +1,20 @@
import { CacheType, ChatInputCommandInteraction } from 'discord.js';
export default function interactionToURL(
interaction: ChatInputCommandInteraction<CacheType>,
) {
const pathname = [
interaction.commandName,
interaction.options.getSubcommandGroup(),
interaction.options.getSubcommand(),
]
.filter(Boolean)
.join('/');
const urlSearchParams = new URLSearchParams();
interaction.options.data.forEach((option) => {
if (option.value) urlSearchParams.set(option.name, `${option.value}`);
});
console.log(`${urlSearchParams}`);
}
+21
View File
@@ -0,0 +1,21 @@
import {
ButtonBuilder,
ButtonStyle,
ComponentEmojiResolvable,
} from 'discord.js';
import { CYCLIC_API } from '../../constants/cyclic.js';
export default function linkButton(
id: string,
label: string,
emoji?: ComponentEmojiResolvable,
) {
const button = new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setURL(`${CYCLIC_API}/${id}`)
.setLabel(label);
if (emoji) button.setEmoji(emoji);
return button;
}
@@ -0,0 +1,40 @@
import {
ActionRowBuilder,
ButtonBuilder,
EmbedBuilder,
InteractionEditReplyOptions,
} from 'discord.js';
import { InteractionReturnable } from '../../events/interactionCreate/index.js';
import render from '../ui/render.js';
export default async function normalizeInteractionReturnable(
returnable: InteractionReturnable,
) {
const reply: InteractionEditReplyOptions = {};
const awaitedReturnable = await returnable;
const normalizedReturnable = Array.isArray(awaitedReturnable)
? awaitedReturnable
: [awaitedReturnable];
await Promise.all(
normalizedReturnable.map(async (item) => {
if (item instanceof EmbedBuilder) {
if (!reply.embeds) reply.embeds = [];
reply.embeds.push(item);
} else if (item instanceof ButtonBuilder) {
if (!reply.components)
reply.components = [new ActionRowBuilder<ButtonBuilder>()];
(reply.components[0] as ActionRowBuilder<ButtonBuilder>).addComponents(
item,
);
} else {
const image = await render(item);
if (!reply.files) reply.files = [];
reply.files.push(image);
}
}),
);
return reply;
}
+20
View File
@@ -0,0 +1,20 @@
import {
ButtonBuilder,
ButtonStyle,
ComponentEmojiResolvable,
} from 'discord.js';
export default function primaryButton(
id: string,
label: string,
emoji?: ComponentEmojiResolvable,
) {
const button = new ButtonBuilder()
.setCustomId(id)
.setStyle(ButtonStyle.Primary)
.setLabel(label);
if (emoji) button.setEmoji(emoji);
return button;
}
+32 -7
View File
@@ -1,4 +1,9 @@
import { CacheType, ChatInputCommandInteraction } from 'discord.js';
import {
ButtonInteraction,
CacheType,
ChatInputCommandInteraction,
} from 'discord.js';
import { CYCLIC_API } from '../../constants/cyclic.js';
import getPeriodNow from '../blitzstars/getPeriodNow.js';
import getPeriodStart from '../blitzstars/getPeriodStart.js';
import getTimeDaysAgo from '../blitzstars/getTimeDaysAgo.js';
@@ -31,19 +36,39 @@ export interface ResolvedPeriod {
}
export default function resolvePeriod(
interaction: ChatInputCommandInteraction<CacheType>,
interaction:
| ChatInputCommandInteraction<CacheType>
| ButtonInteraction<CacheType>,
) {
const period = interaction.options.getSubcommand(true) as Period;
let statsName: string;
let evolutionName: string;
let start: number;
let end: number;
const relativePeriodName =
RELATIVE_PERIOD_NAMES[interaction.options.getSubcommand() as Period];
let subcommand: Period;
let url: typeof interaction extends ChatInputCommandInteraction
? undefined
: URL;
if (interaction instanceof ChatInputCommandInteraction) {
subcommand = interaction.options.getSubcommand() as Period;
} else {
url = new URL(`${CYCLIC_API}/${interaction.customId}`);
const path = url.pathname.split('/').filter(Boolean);
subcommand = path[path.length - 1] as Period;
}
const period = subcommand;
const relativePeriodName = RELATIVE_PERIOD_NAMES[subcommand];
if (period === 'custom') {
const startRaw = interaction.options.getInteger('start')!;
const endRaw = interaction.options.getInteger('end')!;
const startRaw =
interaction instanceof ChatInputCommandInteraction
? interaction.options.getInteger('start')!
: parseInt(url!.searchParams.get('start')!);
const endRaw =
interaction instanceof ChatInputCommandInteraction
? interaction.options.getInteger('end')!
: parseInt(url!.searchParams.get('end')!);
const startMin = Math.min(startRaw, endRaw);
const endMax = Math.max(startRaw, endRaw);
+46 -31
View File
@@ -1,4 +1,9 @@
import { CacheType, ChatInputCommandInteraction } from 'discord.js';
import {
ButtonInteraction,
CacheType,
ChatInputCommandInteraction,
} from 'discord.js';
import { CYCLIC_API } from '../../constants/cyclic.js';
import { BlitzServer } from '../../constants/servers.js';
import listAccountsPanServer, {
usernamePatternWithoutPosition,
@@ -13,40 +18,50 @@ export interface ResolvedPlayer {
}
export default async function resolvePlayer(
interaction: ChatInputCommandInteraction<CacheType>,
interaction:
| ChatInputCommandInteraction<CacheType>
| ButtonInteraction<CacheType>,
) {
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 (interaction instanceof ChatInputCommandInteraction) {
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),
} satisfies ResolvedPlayer;
} else {
const accounts = await listAccountsPanServer(username);
if (accounts[0]) {
return {
server: accounts[0].server,
id: accounts[0].account_id,
} satisfies ResolvedPlayer;
} else {
if (username === undefined) {
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.`,
'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),
} satisfies ResolvedPlayer;
} else {
const accounts = await listAccountsPanServer(username);
if (accounts[0]) {
return {
server: accounts[0].server,
id: accounts[0].account_id,
} satisfies ResolvedPlayer;
} else {
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.`,
);
}
}
} else {
const url = new URL(`${CYCLIC_API}/${interaction.customId}`);
return {
id: parseInt(url.searchParams.get('id')!),
server: url.searchParams.get('server') as BlitzServer,
} satisfies ResolvedPlayer;
}
}
+2 -2
View File
@@ -4,10 +4,10 @@ export interface PSAData {
}
export interface PSA {
data?: PSAData;
data: PSAData | null;
}
export const psa: PSA = {};
export const psa: PSA = { data: null };
console.log('Caching PSA...');
fetch(
-241
View File
@@ -1,241 +0,0 @@
import {
ActionRowBuilder,
AutocompleteInteraction,
ButtonBuilder,
ButtonInteraction,
ButtonStyle,
CacheType,
ChatInputCommandInteraction,
EmbedBuilder,
Interaction,
InteractionEditReplyOptions,
REST,
RESTPostAPIChatInputApplicationCommandsJSONBody,
Routes,
SlashCommandBuilder,
SlashCommandSubcommandsOnlyBuilder,
} from 'discord.js';
import discord from '../../discord.json' assert { type: 'json' };
import debug from '../commands/debug.js';
import eligible from '../commands/eligible.js';
import evolution from '../commands/evolution.js';
import help from '../commands/help.js';
import inactive from '../commands/inactive.js';
import ownedtanks from '../commands/ownedtanks.js';
import ping from '../commands/ping.js';
import playerachievements from '../commands/playerachievements.js';
import playerinfo from '../commands/playerinfo.js';
import searchclans from '../commands/searchclans.js';
import searchplayers from '../commands/searchplayers.js';
import searchtanks from '../commands/searchtanks.js';
import stats from '../commands/stats.js';
import today from '../commands/today.js';
import verify from '../commands/verify.js';
import negativeEmbed from '../core/interaction/negativeEmbed.js';
import warningEmbed from '../core/interaction/warningEmbed.js';
import { DISCORD_TOKEN } from '../core/process/args.js';
import getClientId from '../core/process/getClientId.js';
import isDev from '../core/process/isDev.js';
import { psa } from '../core/process/psa.js';
import render from '../core/ui/render.js';
import { handleError } from './error.js';
export type CommandReturnable = EmbedBuilder | ButtonBuilder | JSX.Element;
export type RichCommandReturnable = CommandReturnable | CommandReturnable[];
export type CommandRegistry = {
inDevelopment: boolean;
inProduction: boolean;
inPublic: boolean;
command:
| SlashCommandBuilder
| SlashCommandSubcommandsOnlyBuilder
| Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'>;
autocomplete?: (interaction: AutocompleteInteraction<CacheType>) => void;
} & (
| {
handlesInteraction?: false;
execute: (
interaction: ChatInputCommandInteraction<CacheType>,
) => RichCommandReturnable | Promise<RichCommandReturnable>;
}
| {
handlesInteraction: true;
execute: (interaction: ChatInputCommandInteraction<CacheType>) => void;
}
);
const rest = new REST().setToken(DISCORD_TOKEN);
const commands = (
[
debug,
eligible,
help,
inactive,
ownedtanks,
playerachievements,
playerinfo,
searchclans,
searchplayers,
searchtanks,
stats,
today,
verify,
ping,
evolution,
] as CommandRegistry[]
).reduce<Record<string, CommandRegistry>>((accumulator, registry) => {
registry.command.setName(
isDev() ? `${registry.command.name}dev` : registry.command.name,
);
return { ...accumulator, [registry.command.name]: registry };
}, {});
export const guildCommands: RESTPostAPIChatInputApplicationCommandsJSONBody[] =
[];
export const publicCommands: RESTPostAPIChatInputApplicationCommandsJSONBody[] =
[];
Object.entries(commands).forEach(([, registry]) => {
if (isDev() ? registry.inDevelopment : registry.inProduction) {
const json = registry.command.toJSON();
if (registry.inPublic) {
publicCommands.push(json);
} else {
guildCommands.push(json);
}
}
});
try {
console.log(`Refreshing ${publicCommands.length} public command(s).`);
rest
.put(Routes.applicationCommands(getClientId()), { body: publicCommands })
.then((publicData) => {
console.log(
`Successfully refreshed ${
(publicData as RESTPostAPIChatInputApplicationCommandsJSONBody[])
.length
} public command(s).`,
);
});
console.log(`Refreshing ${guildCommands.length} guild command(s).`);
rest
.put(
Routes.applicationGuildCommands(getClientId(), discord.tres_guild_id),
{ body: guildCommands },
)
.then((guildData) => {
console.log(
`Successfully refreshed ${
(guildData as unknown[]).length
} guild command(s).`,
);
});
} catch (error) {
console.error(error);
}
//#region Event type handlers
function handleAutocomplete(interaction: AutocompleteInteraction<CacheType>) {
const command = commands[interaction.commandName];
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
if (command.autocomplete) command.autocomplete(interaction);
}
async function handleChatInputCommand(
interaction: ChatInputCommandInteraction<CacheType>,
) {
const command = commands[interaction.commandName];
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
console.log(interaction.toString());
await interaction.deferReply();
try {
const result = await command.execute(interaction);
if (command.handlesInteraction) return;
const normalizedResult = Array.isArray(result) ? result : [result];
const reply: InteractionEditReplyOptions = {};
if (psa.data) {
normalizedResult.push(warningEmbed(psa.data.title, psa.data.description));
}
await Promise.all(
normalizedResult.map(async (item) => {
if (item instanceof EmbedBuilder) {
if (!reply.embeds) reply.embeds = [];
reply.embeds.push(item);
} else if (item instanceof ButtonBuilder) {
if (!reply.components)
reply.components = [new ActionRowBuilder<ButtonBuilder>()];
(
reply.components[0] as ActionRowBuilder<ButtonBuilder>
).addComponents(item);
} else {
const image = await render(item!);
if (!reply.files) reply.files = [];
reply.files.push(image);
}
}),
);
await interaction.editReply(reply);
} catch (error) {
const actionRow = new ActionRowBuilder<ButtonBuilder>().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);
}
}
function handleButton(interaction: ButtonInteraction<CacheType>) {
console.log(interaction.customId);
interaction.message.edit({
files: [],
});
}
//#endregion
export default async function interactionCreate(
interaction: Interaction<CacheType>,
) {
if (interaction.isAutocomplete()) {
handleAutocomplete(interaction);
} else if (interaction.isChatInputCommand()) {
handleChatInputCommand(interaction);
} else if (interaction.isButton()) {
handleButton(interaction);
}
}
@@ -0,0 +1,15 @@
import { AutocompleteInteraction, CacheType } from 'discord.js';
import { commands } from '../index.js';
export default function handleAutocomplete(
interaction: AutocompleteInteraction<CacheType>,
) {
const command = commands[interaction.commandName];
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
if (command.autocomplete) command.autocomplete(interaction);
}
@@ -0,0 +1,20 @@
import { ButtonInteraction, CacheType } from 'discord.js';
import normalizeInteractionReturnable from '../../../core/interaction/normalizeInteractionReturnable.js';
import { commands } from '../index.js';
export default async function handleButton(
interaction: ButtonInteraction<CacheType>,
) {
const commandName = interaction.customId.split('/')[0];
const button = commands[commandName]?.button;
if (!button) {
console.error(`Button handler not found for "${commandName}"`);
return;
}
await interaction.deferUpdate();
await interaction.message.edit(
await normalizeInteractionReturnable(button(interaction)),
);
}
@@ -0,0 +1,56 @@
import {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
CacheType,
ChatInputCommandInteraction,
} from 'discord.js';
import negativeEmbed from '../../../core/interaction/negativeEmbed.js';
import normalizeInteractionReturnable from '../../../core/interaction/normalizeInteractionReturnable.js';
import warningEmbed from '../../../core/interaction/warningEmbed.js';
import { psa } from '../../../core/process/psa.js';
import { handleError } from '../../error.js';
import { commands } from '../index.js';
export default async function handleChatInputCommand(
interaction: ChatInputCommandInteraction<CacheType>,
) {
const command = commands[interaction.commandName];
console.log(interaction.toString());
await interaction.deferReply();
try {
const returnable = await command.execute(interaction);
if (command.handlesInteraction) return;
const reply = await normalizeInteractionReturnable(returnable!);
if (psa.data) {
if (!reply.embeds) reply.embeds = [];
reply.embeds.push(warningEmbed(psa.data.title, psa.data.description));
}
await interaction.editReply(reply);
} catch (error) {
const actionRow = new ActionRowBuilder<ButtonBuilder>().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);
}
}
+156
View File
@@ -0,0 +1,156 @@
import {
AutocompleteInteraction,
ButtonBuilder,
ButtonInteraction,
CacheType,
ChatInputCommandInteraction,
EmbedBuilder,
Interaction,
REST,
RESTPostAPIChatInputApplicationCommandsJSONBody,
Routes,
SlashCommandBuilder,
SlashCommandSubcommandsOnlyBuilder,
} from 'discord.js';
import discord from '../../../discord.json' assert { type: 'json' };
import debug from '../../commands/debug.js';
import eligible from '../../commands/eligible.js';
import evolution from '../../commands/evolution.js';
import help from '../../commands/help.js';
import inactive from '../../commands/inactive.js';
import ownedtanks from '../../commands/ownedtanks.js';
import ping from '../../commands/ping.js';
import playerachievements from '../../commands/playerachievements.js';
import playerinfo from '../../commands/playerinfo.js';
import searchclans from '../../commands/searchclans.js';
import searchplayers from '../../commands/searchplayers.js';
import searchtanks from '../../commands/searchtanks.js';
import stats from '../../commands/stats.js';
import today from '../../commands/today.js';
import verify from '../../commands/verify.js';
import { DISCORD_TOKEN } from '../../core/process/args.js';
import getClientId from '../../core/process/getClientId.js';
import isDev from '../../core/process/isDev.js';
import handleAutocomplete from './handlers/autocomplete.js';
import handleButton from './handlers/button.js';
import handleChatInputCommand from './handlers/chatInputCommand.js';
export type InteractionRawReturnable =
| EmbedBuilder
| ButtonBuilder
| JSX.Element;
export type InteractionIterableReturnable =
| InteractionRawReturnable
| InteractionRawReturnable[];
export type InteractionReturnable =
| InteractionIterableReturnable
| Promise<InteractionIterableReturnable>;
export type CommandRegistry = {
inDevelopment: boolean;
inProduction: boolean;
inPublic: boolean;
command:
| SlashCommandBuilder
| SlashCommandSubcommandsOnlyBuilder
| Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'>;
autocomplete?: (interaction: AutocompleteInteraction<CacheType>) => void;
button?: (interaction: ButtonInteraction<CacheType>) => InteractionReturnable;
} & (
| {
handlesInteraction?: false;
execute: (
interaction: ChatInputCommandInteraction<CacheType>,
) => InteractionReturnable;
}
| {
handlesInteraction: true;
execute: (interaction: ChatInputCommandInteraction<CacheType>) => void;
}
);
const rest = new REST().setToken(DISCORD_TOKEN);
export const commands: Record<string, CommandRegistry> = (
[
debug,
eligible,
help,
inactive,
ownedtanks,
playerachievements,
playerinfo,
searchclans,
searchplayers,
searchtanks,
stats,
today,
verify,
ping,
evolution,
] as CommandRegistry[]
).reduce((accumulator, registry) => {
// if (isDev()) registry.command.setName(`${registry.command.name}dev`);
return { ...accumulator, [registry.command.name]: registry };
}, {});
export const guildCommands: RESTPostAPIChatInputApplicationCommandsJSONBody[] =
[];
export const publicCommands: RESTPostAPIChatInputApplicationCommandsJSONBody[] =
[];
Object.entries(commands).forEach(([, registry]) => {
if (isDev() ? registry.inDevelopment : registry.inProduction) {
const json = registry.command.toJSON();
if (registry.inPublic) {
publicCommands.push(json);
} else {
guildCommands.push(json);
}
}
});
try {
console.log(`Refreshing ${publicCommands.length} public command(s).`);
rest
.put(Routes.applicationCommands(getClientId()), { body: publicCommands })
.then((publicData) => {
console.log(
`Successfully refreshed ${
(publicData as RESTPostAPIChatInputApplicationCommandsJSONBody[])
.length
} public command(s).`,
);
});
console.log(`Refreshing ${guildCommands.length} guild command(s).`);
rest
.put(
Routes.applicationGuildCommands(getClientId(), discord.tres_guild_id),
{ body: guildCommands },
)
.then((guildData) => {
console.log(
`Successfully refreshed ${
(guildData as unknown[]).length
} guild command(s).`,
);
});
} catch (error) {
console.error(error);
}
export default async function interactionCreate(
interaction: Interaction<CacheType>,
) {
if (interaction.isAutocomplete()) {
handleAutocomplete(interaction);
} else if (interaction.isChatInputCommand()) {
handleChatInputCommand(interaction);
} else if (interaction.isButton()) {
handleButton(interaction);
}
}
+1 -1
View File
@@ -2,7 +2,7 @@ import { Client, GatewayIntentBits } from 'discord.js';
import { DISCORD_TOKEN } from './core/process/args.js';
import { registerErrorHandlers } from './events/error.js';
import guildMemberAdd from './events/guildMemberAdd.js';
import interactionCreate from './events/interactionCreate.js';
import interactionCreate from './events/interactionCreate/index.js';
import ready from './events/ready.js';
export const client = new Client({
+1 -1
View File
@@ -11,5 +11,5 @@
"resolveJsonModule": true,
"jsx": "react-jsx"
},
"include": ["src/**/*.ts", "src/renderers/stats.tsx"]
"include": ["src/**/*.ts", "src/renderers/stats.tsx", "src/events/interactionCreate/handlers/button.tsx"]
}