Skip to content

Commit

Permalink
feat(logs): add permissions to error message
Browse files Browse the repository at this point in the history
Now, the error message will include the specific permission that is missing,
making it easier for users to resolve the issue.
out of scope but had to be done.
But too lazy to go to develop and come back to this branch
  • Loading branch information
adan-ea committed Jun 20, 2024
1 parent 1adcbba commit b071aad
Show file tree
Hide file tree
Showing 6 changed files with 114 additions and 61 deletions.
5 changes: 3 additions & 2 deletions src/modules/core/commands/moderation/purge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ export default {
examples: ['purge 10', 'purge 100 @adan_ea'],

async execute(client: Client, interaction: ChatInputCommandInteraction, guildSettings: IGuild) {
if (!hasBotPermission(interaction.guild!, [PermissionsBitField.Flags.ManageMessages]))
throw CustomErrors.SelfNoPermissionsError;
const permissions = [PermissionsBitField.Flags.ManageMessages];
if (!hasBotPermission(interaction.guild!, permissions))
throw CustomErrors.SelfNoPermissionsError(interaction.guild!, permissions);

const amountToDelete = interaction.options.getNumber('montant', true);
if (amountToDelete > 100 || amountToDelete < 0) {
Expand Down
9 changes: 8 additions & 1 deletion src/modules/jail/components/contextMenus/jail.contextMenu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from 'discord.js';
import { IGuild, IJailModule } from 'adroi.d.ea';
import { CustomErrors } from '../../../../utils/errors';
import { hasBotPermission } from '../../../../utils/bot.util';
import jailQueue from '../../tasks/jail.queue';

export const jailContextMenu = new ContextMenuCommandBuilder()
Expand All @@ -18,6 +19,13 @@ export const jailContextMenu = new ContextMenuCommandBuilder()
export default {
data: jailContextMenu.toJSON(),
async execute(interaction: UserContextMenuCommandInteraction, guildSettings: IGuild) {
const permissions = [
PermissionsBitField.Flags.MoveMembers,
PermissionsBitField.Flags.MuteMembers,
PermissionsBitField.Flags.DeafenMembers
];
if (!hasBotPermission(interaction.guild!, permissions))
throw CustomErrors.SelfNoPermissionsError(interaction.guild!, permissions);
const { jail } = guildSettings.modules;

// check if the jail module is enabled and if the jail channel is set
Expand Down Expand Up @@ -62,7 +70,6 @@ export default {
},
{ delay: jailTime * 1000 }
);

}
};

Expand Down
38 changes: 38 additions & 0 deletions src/utils/bot.util.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Guild, GuildBasedChannel, PermissionsBitField } from 'discord.js';
import { Emojis } from './consts';

export const hasBotPermission = (guild: Guild, permissionsFlag: bigint[]) => {
return guild.members.me!.permissions.has(permissionsFlag);
Expand Down Expand Up @@ -62,3 +63,40 @@ export const canSendMessage = (channel: GuildBasedChannel | undefined) => {
PermissionsBitField.Flags.SendMessagesInThreads
]);
};

/**
* Checks if the bot has each permission in the provided list and returns a formatted string.
* @param guild - The guild to check permissions in.
* @param permissions - An array of permission flags to check.
* @returns A string with each permission and its status (allowed or denied).
*/
export const listBotPermissions = (guild: Guild, permissions: bigint[]): string => {
let result = '';

permissions.forEach(perm => {
const permName = getPermissionName(perm);
const permWithSpaces = permName.replace(/([a-z])([A-Z])|([A-Z])([A-Z][a-z])/g, '$1$3 $2$4');

if (hasBotPermission(guild, [perm])) {
result += `> ${Emojis.check} ${permWithSpaces}\n`;
} else {
result += `> ${Emojis.cross} ${permWithSpaces}\n`;
}
});

return result;
};

/**
* Retrieves the permission name from a permission flag.
* @param perm - The permission flag as a bigint.
* @returns The human-readable name of the permission.
*/
const getPermissionName = (perm: bigint): string => {
for (const [key, value] of Object.entries(PermissionsBitField.Flags)) {
if (value === perm) {
return key;
}
}
return perm.toString();
};
56 changes: 56 additions & 0 deletions src/utils/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,59 @@ export enum Channels {
}

export const OWNER_ID = '294916386072035328';

export const categories = {
[`${Emojis.cog} Générales`]: [
'ManageChannels',
'ManageGuild',
'ViewAuditLog',
'ViewChannel',
'ViewGuildInsights',
'ManageRoles',
'ManageWebhooks',
'ManageEmojisAndStickers',
'ManageGuildExpressions'
],
[`${Emojis.members} Membres`]: [
'CreateInstantInvite',
'KickMembers',
'BanMembers',
'ChangeNickname',
'ManageNicknames',
'ModerateMembers'
],
[`${Emojis.event} Evènements`]: ['ManageEvents'],
[`${Emojis.textChannel} Salon textuel`]: [
'AddReactions',
'SendMessages',
'SendTTSMessages',
'ManageMessages',
'EmbedLinks',
'AttachFiles',
'ReadMessageHistory',
'MentionEveryone',
'UseExternalEmojis',
'UseApplicationCommands',
'ManageThreads',
'CreatePublicThreads',
'CreatePrivateThreads',
'UseExternalStickers',
'SendMessagesInThreads',
'SendVoiceMessages'
],
[`${Emojis.voiceChannel} Salon vocal`]: [
'PrioritySpeaker',
'Stream',
'Connect',
'Speak',
'MuteMembers',
'DeafenMembers',
'MoveMembers',
'UseVAD',
'UseEmbeddedActivities',
'UseSoundboard',
'UseExternalSounds'
],
[`${Emojis.stageChannel} Salon de conférence`]: ['RequestToSpeak'],
[`${Emojis.advanced} Avancées`]: ['Administrator']
};
9 changes: 8 additions & 1 deletion src/utils/errors.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { Guild } from 'discord.js';
import { listBotPermissions } from './bot.util';

export class CustomError extends Error {}

export const CustomErrors = {
Expand All @@ -9,7 +12,11 @@ export const CustomErrors = {
`Comme dirait Orel San, ça va trop vite. Cette fonction est en cooldown. tu pourras l'utiliser <t:${cooldownTime}:R>.`
),
UserNoPermissionsError: new CustomError("Eh non, t'as pas les droits, cheh !"),
SelfNoPermissionsError: new CustomError("Peux pas faire ça, j'ai pas les droits."),
SelfNoPermissionsError: (guild: Guild, permissions: bigint[]) =>
new CustomError(
"Peux pas faire ça, j'ai pas les droits. J'ai besoin de :\n" +
listBotPermissions(guild, permissions)
),
ToDoError: new CustomError("Ca fonctionne, mais t'as pas setup d'erreur pour ce cas encore."),
UnknownCommandError: new CustomError(
'Mmh, il semblerait que je ne connais pas cette commande.'
Expand Down
58 changes: 1 addition & 57 deletions src/utils/modules.uil.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { EmbedBuilder, GuildMember, PermissionsBitField } from 'discord.js';
import { Emojis, categories } from './consts';
import { IGuild, ITVMUserSettings } from 'adroi.d.ea';
import { CustomErrors } from './errors';
import { Emojis } from './consts';
import guildService from '../services/guild.service';

/**
Expand Down Expand Up @@ -73,62 +73,6 @@ export const getorCreateUserSettings = async (
return userSettings;
};

const categories = {
[`${Emojis.cog} Générales`]: [
'ManageChannels',
'ManageGuild',
'ViewAuditLog',
'ViewChannel',
'ViewGuildInsights',
'ManageRoles',
'ManageWebhooks',
'ManageEmojisAndStickers',
'ManageGuildExpressions'
],
[`${Emojis.members} Membres`]: [
'CreateInstantInvite',
'KickMembers',
'BanMembers',
'ChangeNickname',
'ManageNicknames',
'ModerateMembers'
],
[`${Emojis.event} Evènements`]: ['ManageEvents'],
[`${Emojis.textChannel} Salon textuel`]: [
'AddReactions',
'SendMessages',
'SendTTSMessages',
'ManageMessages',
'EmbedLinks',
'AttachFiles',
'ReadMessageHistory',
'MentionEveryone',
'UseExternalEmojis',
'UseApplicationCommands',
'ManageThreads',
'CreatePublicThreads',
'CreatePrivateThreads',
'UseExternalStickers',
'SendMessagesInThreads',
'SendVoiceMessages'
],
[`${Emojis.voiceChannel} Salon vocal`]: [
'PrioritySpeaker',
'Stream',
'Connect',
'Speak',
'MuteMembers',
'DeafenMembers',
'MoveMembers',
'UseVAD',
'UseEmbeddedActivities',
'UseSoundboard',
'UseExternalSounds'
],
[`${Emojis.stageChannel} Salon de conférence`]: ['RequestToSpeak'],
[`${Emojis.advanced} Avancées`]: ['Administrator']
};

export const addPermissionsNames = (permissions: PermissionsBitField, embed: EmbedBuilder) => {
const permissionNames: string[] = permissions.toArray();

Expand Down

0 comments on commit b071aad

Please sign in to comment.