Sunar

Admin only

Restrict command execution to server administrators using middleware in Sunar. This guide provides examples to ensure only admins can access specific commands.

Usage

protect(builder, [adminOnly])

Logic

import { Message, PermissionFlagsBits, PermissionsBitField } from 'discord.js';
import { Protector, execute } from 'sunar';
 
const adminOnly = new Protector({
    commands: ['autocomplete', 'contextMenu', 'slash'],
    components: ['button', 'modal', 'selectMenu'],
    signals: ['interactionCreate', 'messageCreate'],
});
 
const content = 'Only the admins can use this.';
 
/** @param {PermissionsBitField | string | undefined} permissions */
function checkIsAdmin(permissions) {
    if (!permissions || typeof permissions === 'string') return false;
    return permissions.has(PermissionFlagsBits.Administrator);
}
 
execute(adminOnly, (arg, next) => {
    const entry = Array.isArray(arg) ? arg[0] : arg;
 
    const isAdmin = checkIsAdmin(entry.member?.permissions);
 
    if (entry instanceof Message) {
        if (isAdmin) return next();
        return entry.reply({ content });
    }
 
    if (entry.isAutocomplete() && !isAdmin) return entry.respond([]);
    if (entry.isRepliable() && !isAdmin) return entry.reply({ content, ephemeral: true });
 
    return isAdmin && next();
});
 
export { adminOnly };

Last updated on

On this page

GitHubEdit on Github ↗