gcommands icon indicating copy to clipboard operation
gcommands copied to clipboard

refactor: Inhibitors

Open S222em opened this issue 2 years ago • 1 comments

Please describe the changes this PR makes and why it should be merged: These PR refactors inhibitors are easier to work with. Sample:

import type { PermissionResolvable } from 'discord.js';
import { Inhibitor, InhibitorOptions } from './Inhibitor';
import type { CommandContext } from '../lib/structures/contexts/CommandContext';
import type { ComponentContext } from '../lib/structures/contexts/ComponentContext';

export interface ClientPermissionsOptions extends InhibitorOptions {
	permissions: Array<PermissionResolvable>;
}

const defaultMessage = (permissions: PermissionResolvable[]) => {
	return `I need the following permissions to execute this command: ${permissions
		.join(', ')
		.replace(/_/g, ' ')
		.toLowerCase()}`;
};

export class ClientPermissions extends Inhibitor {
	public readonly permissions: Array<PermissionResolvable>;

	constructor(options: ClientPermissionsOptions) {
		super(options);
		this.permissions = options.permissions;
	}

	run(ctx: CommandContext | ComponentContext): boolean | any {
		if (!ctx.inGuild()) return;
		if (!ctx.guild.me.permissions.has(this.permissions))
			return this.error(this.resolveMessage(ctx, defaultMessage(this.permissions)));
		else return this.ok();
	}
}

This PR also fixes an issue with the Or inhibitor. If both inhibitors fail, this will now resolve the message from its own class, rather than using the ones from the inhibitors within. Before the inhibitor would send a reply itself, but this was not working as there would be a chance both inhibitors fail with different messages, and can cause a INTERACTION_ALREADY_REPLIED error.

Status and versioning classification:

  • This PR changes the library's interface (methods or parameters added)
  • This PR includes breaking changes (methods removed or renamed, parameters moved or removed)

S222em avatar Mar 17 '22 10:03 S222em