Moderation
Ban command
Moderation with permission checks
Slash /ban with Ban Members permission, hierarchy checks, and ephemeral errors — the pattern Discord recommends for mod tools.
Based on discord.js guide — command permissions
/ban
Source preview
import {
Client,
Events,
GatewayIntentBits,
REST,
Routes,
SlashCommandBuilder,
PermissionFlagsBits,
MessageFlags,
} from "discord.js";
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers],
});
const commands = [
new SlashCommandBuilder()
.setName("ban")
.setDescription("Ban a member")
.addUserOption((o) =>
o.setName("user").setDescription("Target").setRequired(true),
)
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers),
].map((c) => c.toJSON());
client.once(Events.ClientReady, async () => {
const rest = new REST({ version: "10" }).setToken(process.env.DISCORD_TOKEN!);
await rest.put(Routes.applicationCommands(client.user!.id), { body: commands });
});
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName !== "ban") return;
if (!interaction.memberPermissions?.has(PermissionFlagsBits.BanMembers)) {
await interaction.reply({
content: "You need the Ban Members permission.",
flags: MessageFlags.Ephemeral,
});
return;
}
const user = interaction.options.getUser("user", true);
const member = await interaction.guild!.members.fetch(user.id);
if (!member.bannable) {
await interaction.reply({
content: "I cannot ban that member.",
flags: MessageFlags.Ephemeral,
});
return;
}
await member.ban({ reason: "sandbox test" });
await interaction.reply({ content: `Banned ${user.username}.` });
});
client.login(process.env.DISCORD_TOKEN);