Skip to content

Commit

Permalink
fix: all commands gone (#1021)
Browse files Browse the repository at this point in the history
  • Loading branch information
geisterfurz007 authored Jul 15, 2023
1 parent d183da8 commit 06ea2a1
Show file tree
Hide file tree
Showing 5 changed files with 130 additions and 187 deletions.
31 changes: 11 additions & 20 deletions src/event-distribution/event-distribution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import {
isMessageRelated,
rejectWithError,
} from "./events/events";
import { registerSlashCommands } from "./events/slash-commands";
import { registerContextMenuCommands } from "./events/context-menu";
import { getIocName } from "./helper";
import {
DiscordEvent,
Expand All @@ -29,6 +27,7 @@ import {
StringIndexedHIOCTreeNode,
} from "./types/hioc";
import * as Sentry from "@sentry/node";
import { registerApplicationCommands } from "./register-commands";

const logger = createYesBotLogger("event-distribution", "event-distribution");

Expand Down Expand Up @@ -68,8 +67,7 @@ export class EventDistribution {
[DiscordEvent.MEMBER_JOIN]: {},
};

private slashCommandNameIdMap: Record<string, Snowflake> = {};
private contextMenuNameIdMap: Record<string, Snowflake> = {};
private nameIdMap: Record<string, Snowflake> = {};

private infoToFilterResults<T extends DiscordEvent>(
info: HandlerInfo,
Expand Down Expand Up @@ -268,23 +266,16 @@ export class EventDistribution {
logger.debug("Loading complete!");

// Slash Commands and related stuff
const { tree, nameIdMap } = await registerSlashCommands(
this.handlers[DiscordEvent.SLASH_COMMAND]
);

this.slashCommandNameIdMap = nameIdMap ?? {};
this.handlers[DiscordEvent.SLASH_COMMAND] = tree;

const {
userTree,
messageTree,
nameIdMap: contextNameIdMap,
} = await registerContextMenuCommands(
this.handlers[DiscordEvent.CONTEXT_MENU_MESSAGE],
this.handlers[DiscordEvent.CONTEXT_MENU_USER]
);
const { userTree, messageTree, slashCommandTree, nameIdMap } =
await registerApplicationCommands(
this.handlers[DiscordEvent.SLASH_COMMAND],
this.handlers[DiscordEvent.CONTEXT_MENU_MESSAGE],
this.handlers[DiscordEvent.CONTEXT_MENU_USER]
);

this.contextMenuNameIdMap = contextNameIdMap ?? {};
this.nameIdMap = nameIdMap ?? {};
this.handlers[DiscordEvent.SLASH_COMMAND] = slashCommandTree;
this.handlers[DiscordEvent.CONTEXT_MENU_MESSAGE] = messageTree;
this.handlers[DiscordEvent.CONTEXT_MENU_USER] = userTree;
}
Expand Down Expand Up @@ -406,6 +397,6 @@ export class EventDistribution {
}

public getIdForCommandName(commandName: string): Snowflake {
return this.slashCommandNameIdMap[commandName];
return this.nameIdMap[commandName];
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
import { ContextMenuUserHandlerOptions } from "./context-menu-user";
import { ContextMenuMessageHandlerOptions } from "./context-menu-message";
import { ContextMenuCommandBuilder, Snowflake } from "discord.js";
import { ContextMenuUserHandlerOptions } from "./context-menu-user";
import { DiscordEvent } from "../../types/base";
import { ContextMenuCommandBuilder } from "discord.js";
import { ApplicationCommandType } from "discord-api-types/v10";
import { Routes } from "discord-api-types/rest";
import { StringIndexedHIOCTree } from "../../types/hioc";
import { createYesBotLogger } from "../../../log";
import { getAllOptions } from "../../helper";
import { REST } from "@discordjs/rest";

type ContextMenuOptions =
| ContextMenuMessageHandlerOptions
Expand All @@ -24,88 +19,9 @@ const getType = (options: ContextMenuOptions) => {
}
};

const buildContextMenuCommand = (command: ContextMenuOptions) => {
export const buildContextMenuCommand = (command: ContextMenuOptions) => {
const type = getType(command);
if (!type) return undefined;

return new ContextMenuCommandBuilder().setName(command.name).setType(type);
};

interface RegistrationResponseItem {
id: string;
name: string;
type: ApplicationCommandType;
}

interface RegistrationResult {
messageTree: StringIndexedHIOCTree<DiscordEvent.CONTEXT_MENU_MESSAGE>;
userTree: StringIndexedHIOCTree<DiscordEvent.CONTEXT_MENU_USER>;

nameIdMap?: Record<string, Snowflake>;
}

export const registerContextMenuCommands = async (
messageTree: StringIndexedHIOCTree<DiscordEvent.CONTEXT_MENU_MESSAGE>,
userTree: StringIndexedHIOCTree<DiscordEvent.CONTEXT_MENU_USER>
): Promise<RegistrationResult> => {
const logger = createYesBotLogger(
"event-distribution",
"register-context-menu-commands"
);

const messageCommands = getAllOptions(messageTree);
const userCommands = getAllOptions(userTree);

const builtCommands = [...messageCommands, ...userCommands].map(
buildContextMenuCommand
);

const jsonCommands = builtCommands
.filter((c): c is ContextMenuCommandBuilder => !!c)
.map((c) => c.toJSON());

logger.info(`Registering ${jsonCommands.length} context menu commands`);

const rest = new REST({ version: "10" }).setToken(process.env.BOT_TOKEN);
try {
const result = (await rest.put(
Routes.applicationGuildCommands(
process.env.CLIENT_ID,
process.env.GUILD_ID
),
{ body: jsonCommands }
)) as RegistrationResponseItem[];

const newMessageCommandTree: StringIndexedHIOCTree<DiscordEvent.CONTEXT_MENU_MESSAGE> =
{};
const newUserCommandTree: StringIndexedHIOCTree<DiscordEvent.CONTEXT_MENU_USER> =
{};
const nameIdMap: Record<string, Snowflake> = {};

for (const item of result) {
const targetTree =
item.type === ApplicationCommandType.User
? newUserCommandTree
: newMessageCommandTree;
const sourceTree =
item.type === ApplicationCommandType.User ? userTree : messageTree;

targetTree[item.id] = sourceTree[item.name];
nameIdMap[item.name] = item.id;
}

logger.info(
`Finished registering ${jsonCommands.length} context menu commands`
);

return {
messageTree: newMessageCommandTree,
userTree: newUserCommandTree,
nameIdMap: nameIdMap,
};
} catch (e) {
logger.error("Failed registering context menu commands, exception was ", e);

return { messageTree, userTree };
}
};
2 changes: 1 addition & 1 deletion src/event-distribution/events/context-menu/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export * from "./context-menu-message";
export * from "./context-menu-user";

export { registerContextMenuCommands } from "./build-context-menu-commands";
export { buildContextMenuCommand } from "./build-context-menu-commands";
81 changes: 2 additions & 79 deletions src/event-distribution/events/slash-commands/slash-commands.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,18 @@
import { REST } from "@discordjs/rest";
import { Routes } from "discord-api-types/rest";
import {
ChannelType,
ChatInputCommandInteraction,
SlashCommandBuilder,
SlashCommandSubcommandBuilder,
SlashCommandSubcommandGroupBuilder,
Snowflake,
} from "discord.js";
import { createYesBotLogger } from "../../../log";
import {
addToTree,
ensureGuildMemberOrNull,
getAllOptions,
} from "../../helper";
import { addToTree, ensureGuildMemberOrNull } from "../../helper";
import {
AddEventHandlerFunction,
BaseOptions,
DiscordEvent,
ExtractInfoForEventFunction,
HandlerFunctionFor,
} from "../../types/base";
import { StringIndexedHIOCTree } from "../../types/hioc";
import {
addOptions,
APIApplicationCommandBasicOptionWithAutoCompleteHandler,
Expand Down Expand Up @@ -83,7 +74,7 @@ export const extractSlashCommandInfo: ExtractInfoForEventFunction<
};
};

const buildCommand = (
export const buildSlashCommand = (
options: SlashCommandHandlerOptions,
builderCache: Record<string, SlashCommandBuilder>,
groupBuilderCache: Record<string, SlashCommandSubcommandGroupBuilder>
Expand Down Expand Up @@ -126,71 +117,3 @@ const buildCommand = (

builderCache[options.root] ??= builder;
};

interface RegistrationResponseItem {
id: string;
name: string;
}

interface RegistrationResult {
tree: StringIndexedHIOCTree<DiscordEvent.SLASH_COMMAND>;
nameIdMap?: Record<string, Snowflake>;
}

export const registerSlashCommands = async (
commandTree: StringIndexedHIOCTree<DiscordEvent.SLASH_COMMAND>
): Promise<RegistrationResult> => {
const logger = createYesBotLogger(
"event-distribution",
"register-slash-commands"
);

const allOptions = getAllOptions(commandTree);

if (allOptions.length === 0) {
logger.info("No slash commands registered; skipping API call!");
return { tree: commandTree };
}

logger.info(`Registering ${allOptions.length} slash commands`);

const builderCache: Record<string, SlashCommandBuilder> = {};
const groupBuilderCache: Record<string, SlashCommandSubcommandGroupBuilder> =
{};

allOptions.forEach((option) =>
buildCommand(option, builderCache, groupBuilderCache)
);
const commands = Object.values(builderCache).map((builder) =>
builder.toJSON()
);

const rest = new REST({ version: "10" }).setToken(process.env.BOT_TOKEN);

try {
const result = (await rest.put(
Routes.applicationGuildCommands(
process.env.CLIENT_ID,
process.env.GUILD_ID
),
{ body: commands }
)) as RegistrationResponseItem[];

const newCommandTree: StringIndexedHIOCTree<DiscordEvent.SLASH_COMMAND> =
{};
const nameIdMap: Record<string, Snowflake> = {};

for (const item of result) {
newCommandTree[item.id] = commandTree[item.name];
nameIdMap[item.name] = item.id;
}

logger.info(`Finished registering ${allOptions.length} slash commands`);

return { tree: newCommandTree, nameIdMap };
} catch (e) {
logger.error("Failed registering slash commands, exception was ", e);

return { tree: commandTree };
}
};
Loading

0 comments on commit 06ea2a1

Please sign in to comment.