Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/basic_client/commands/report.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,5 @@ module.exports = new Command({

return ctx.message.reply(safeReply(ctx.t("test:report_prefix")));
},
preconditions: [require("../preconditions/error.cjs")],
});
27 changes: 27 additions & 0 deletions examples/basic_client/preconditions/adminOnly.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const { PermissionFlagsBits } = require("discord.js");

/** @type {import("../../../dist/index.cjs").IPrecondition} */
const adminOnly = {
name: "adminOnly",
run: (ctx) => {
const member = ctx.data.member;

if (!member?.permissions) {
return [
false,
{
reason: "missing_member_permissions",
defaultValue: "Precondition blocked: {{reason}}",
},
];
}

if (!member.permissions.has(PermissionFlagsBits.Administrator)) {
return [false];
}

return [true];
},
};

module.exports = adminOnly;
10 changes: 10 additions & 0 deletions examples/basic_client/preconditions/error.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = {
name: "error",
run: () => [
false,
{
reason: "forced_error_example",
defaultValue: "Precondition blocked: {{reason}}",
},
],
};
38 changes: 9 additions & 29 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
},
"scripts": {
"prepare": "node scripts/prepareHusky.js",
"example": "node examples/basic_client/index.js",
"test": "echo \"Error: no test specified\" && exit 1",
"check": "oxlint --type-aware --type-check && oxfmt --check",
"format": "oxfmt",
Expand Down
11 changes: 11 additions & 0 deletions src/events/interaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@ export default new EventBuilder(Events.InteractionCreate, false).onExecute(
context.logger.debug(
`${ctx.author?.tag ?? "Unknown"} used ${command.data.name}(interaction)`
);
const failedPrecondition = await command.checkPreconditions(ctx);
if (failedPrecondition) {
await interaction.reply({
content: ctx.t(
failedPrecondition.precondition.getErrorKey(),
failedPrecondition.translateOptions
),
flags: MessageFlags.Ephemeral,
});
return;
}
if (command._onInteraction) await command._onInteraction(ctx.toJSON());
} catch (error) {
context.client.logger.error(
Expand Down
13 changes: 13 additions & 0 deletions src/events/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,19 @@ export default new EventBuilder(
context.logger.debug(
`${ctx.author?.tag ?? "Unknown"} used ${command.data.name}(message)`
);
const failedPrecondition = await command.checkPreconditions(ctx);
if (failedPrecondition) {
await message
.reply({
content: ctx.t(
failedPrecondition.precondition.getErrorKey(),
failedPrecondition.translateOptions
),
allowedMentions: { parse: [], repliedUser: false },
})
.then(deleteMessageAfterSent);
return;
}
if (command._onMessage) await command._onMessage(ctx.toJSON());
} catch (error) {
context.client.logger.error(
Expand Down
31 changes: 27 additions & 4 deletions src/structures/builder/Command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,21 @@ import { Client } from "@structures/index.js";
import { Logger } from "@utils/index.js";
import type { MaybePromise } from "#types/extra.js";
import { ApplicationCommandBuilder } from "@structures/builder/Builder.js";
import { Precondition } from "@structures/builder/Precondition.js";
import type { FailedPrecondition } from "@structures/builder/Precondition.js";
import type { TemplateContext } from "#types/client.js";
import type { IPrecondition } from "#types/precondition.js";
import type {
InteractionContextJSON,
MessageContextJSON,
} from "@structures/builder/Context.js";

type MessageContext = MessageContextJSON;
type InteractionContext = InteractionContextJSON;
type CommandContext = MessageContext | InteractionContext;
type RuntimeCommandContext = MessageContext | InteractionContext;

export class CommandBuilder {
readonly preconditions: Precondition[] = [];
#client: Client | null = null;
#logger: Logger | null = null;
#supportsSlash: boolean;
Expand All @@ -20,9 +25,9 @@ export class CommandBuilder {
_onMessage?: (ctx: MessageContext) => MaybePromise<void>;
_onInteraction?: (ctx: InteractionContext) => MaybePromise<void>;

protected createContextHandler<T extends CommandContext>(
protected createContextHandler<T extends RuntimeCommandContext>(
primary: ((ctx: T) => MaybePromise<void>) | undefined,
fallback: ((ctx: CommandContext) => MaybePromise<void>) | undefined
fallback: ((ctx: RuntimeCommandContext) => MaybePromise<void>) | undefined
) {
if (primary) {
return (ctx: T) => primary(ctx);
Expand Down Expand Up @@ -63,6 +68,16 @@ export class CommandBuilder {
}
}

async checkPreconditions(
ctx: TemplateContext
): Promise<FailedPrecondition | null> {
for (const precondition of this.preconditions) {
const [passed, translateOptions] = await precondition.check(ctx);
if (!passed) return { precondition, translateOptions };
}
return null;
}

attach(client: Client) {
if (this.#attached) return this;
const commandJSON = this.data.toJSON();
Expand Down Expand Up @@ -95,14 +110,22 @@ export class CommandBuilder {

export interface CommandOptions {
data: ApplicationCommandBuilder;
execute?: (ctx: CommandContext) => MaybePromise<void>;
execute?: (ctx: RuntimeCommandContext) => MaybePromise<void>;
onMessage?: (ctx: MessageContext) => MaybePromise<void>;
onInteraction?: (ctx: InteractionContext) => MaybePromise<void>;
preconditions?: IPrecondition[];
}

export class Command extends CommandBuilder {
constructor(options: CommandOptions) {
super(options.data);
if (options.preconditions?.length) {
this.preconditions.push(
...options.preconditions.map(
(precondition) => new Precondition(precondition)
)
);
}
const commandJSON = options.data.toJSON();
if (commandJSON.prefix_support) {
const onMessage = this.createContextHandler(
Expand Down
Loading
Loading