Skip to content

Commit 95c8a6a

Browse files
committed
fix: minor improvements
1 parent a4d253a commit 95c8a6a

File tree

4 files changed

+70
-8
lines changed

4 files changed

+70
-8
lines changed

apps/test-bot/src/app/commands/(developer)/middleware.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ export function beforeExecute(ctx: MiddlewareContext) {
66

77
const user = ctx.isInteraction() ? ctx.interaction.user : ctx.message.author;
88

9-
if (user.id === '12345678901234567890') {
9+
if (user.id !== '12345678901234567890') {
1010
if (ctx.isSlashCommand()) {
1111
ctx.interaction.reply({
1212
content: 'You are not allowed to use this command.',
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import type { CommandData, SlashCommand, MessageCommand } from 'commandkit';
1+
import {
2+
type CommandData,
3+
type SlashCommand,
4+
type MessageCommand,
5+
Logger,
6+
} from 'commandkit';
27

38
export const command: CommandData = {
49
name: 'server',
@@ -7,9 +12,11 @@ export const command: CommandData = {
712
};
813

914
export const chatInput: SlashCommand = async (ctx) => {
15+
Logger.log('Running server command');
1016
await ctx.interaction.reply('Hello from server!');
1117
};
1218

1319
export const message: MessageCommand = async (ctx) => {
20+
Logger.log('Running server command');
1421
await ctx.message.reply('Hello from server!');
1522
};

packages/commandkit/src/CommandKit.ts

+3
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ export class CommandKit extends EventEmitter {
123123

124124
await this.#init();
125125

126+
this.commandHandler.registerCommandHandler();
126127
this.incrementClientListenersCount();
127128

128129
if (token !== false && !this.options.client.isReady()) {
@@ -133,6 +134,8 @@ export class CommandKit extends EventEmitter {
133134
await this.options.client.login(
134135
token ?? process.env.TOKEN ?? process.env.DISCORD_TOKEN,
135136
);
137+
} else if (this.options.client.isReady()) {
138+
await this.commandHandler.registrar.register();
136139
}
137140

138141
this.#started = true;

packages/commandkit/src/app/handlers/AppCommandHandler.ts

+58-6
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,18 @@ import { MessageCommandParser } from '../commands/MessageCommandParser';
2626
import { CommandKitErrorCodes, isErrorType } from '../../utils/error-codes';
2727
import { ParsedCommand, ParsedMiddleware, ParsedSubCommand } from '../router';
2828
import { CommandRegistrar } from '../register/CommandRegistrar';
29-
import { GenericFunction } from '../../context/async-context';
29+
import {
30+
GenericFunction,
31+
makeContextAwareFunction,
32+
useEnvironment,
33+
} from '../../context/async-context';
3034
import { Logger } from '../../logger/Logger';
3135
import { AsyncFunction } from '../../cache';
36+
import {
37+
afterCommand,
38+
CommandKitEnvironment,
39+
CommandKitEnvironmentType,
40+
} from '../../context/environment';
3241

3342
export type RunCommand = <T extends AsyncFunction>(fn: T) => T;
3443

@@ -238,7 +247,14 @@ export class AppCommandHandler {
238247

239248
let runCommand: RunCommand | null = null;
240249

250+
const env = new CommandKitEnvironment(this.commandkit);
251+
env.setType(CommandKitEnvironmentType.CommandHandler);
252+
env.variables.set('commandHandlerType', 'app');
253+
env.variables.set('currentCommandName', prepared.command.command.name);
254+
env.variables.set('execHandlerKind', executionMode);
255+
241256
const ctx = new MiddlewareContext(this.commandkit, {
257+
environment: env,
242258
executionMode,
243259
interaction: !(source instanceof Message)
244260
? (source as ChatInputCommandInteraction)
@@ -271,11 +287,35 @@ export class AppCommandHandler {
271287

272288
if (fn) {
273289
try {
274-
const _executeCommand = async () => fn(ctx.clone());
290+
const _executeCommand = makeContextAwareFunction(
291+
env,
292+
async () => fn(ctx.clone()),
293+
this.#finalizer.bind(this),
294+
);
295+
275296
const executeCommand =
276297
runCommand != null
277298
? (runCommand as RunCommand)(_executeCommand)
278299
: _executeCommand;
300+
301+
afterCommand((env) => {
302+
const error = env.getExecutionError();
303+
const marker = env.getMarker();
304+
const time = `${env.getExecutionTime().toFixed(2)}ms`;
305+
306+
if (error) {
307+
Logger.error(
308+
`[${marker} - ${time}] Error executing command: ${error.stack || error}`,
309+
);
310+
311+
return;
312+
}
313+
314+
Logger.info(`[${marker} - ${time}] Command executed successfully`);
315+
});
316+
317+
env.markStart(prepared.command.command.name);
318+
279319
const res = await this.commandkit.plugins.execute(
280320
async (ctx, plugin) => {
281321
return plugin.executeCommand(ctx, source, prepared, executeCommand);
@@ -290,12 +330,24 @@ export class AppCommandHandler {
290330
}
291331
}
292332

293-
// Run middleware after command execution
294-
for (const middleware of prepared.middlewares) {
295-
await middleware.data.afterExecute(ctx);
333+
try {
334+
// Run middleware after command execution
335+
for (const middleware of prepared.middlewares) {
336+
await middleware.data.afterExecute(ctx);
337+
}
338+
} finally {
339+
env.markEnd();
296340
}
297341
}
298342

343+
async #finalizer() {
344+
const env = useEnvironment();
345+
346+
await env.runDeferredFunctions();
347+
348+
env.clearAllDeferredFunctions();
349+
}
350+
299351
public async prepareCommandRun(
300352
source: Interaction | Message,
301353
): Promise<PreparedAppCommandExecution | null> {
@@ -367,7 +419,7 @@ export class AppCommandHandler {
367419
if (isErrorType(e, CommandKitErrorCodes.InvalidCommandPrefix)) {
368420
return null;
369421
}
370-
console.error(e);
422+
Logger.error(e);
371423
return null;
372424
}
373425
} else {

0 commit comments

Comments
 (0)