要解决所有用户都可以使用Discord.js执行ban/kick命令的问题,你需要实施权限管理。以下是一些基础概念和相关解决方案:
Discord允许你为服务器成员分配角色,并为这些角色设置权限。你可以创建一个只有管理员才能使用的角色,并为该角色分配ban/kick权限。
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] });
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag}`);
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'ban' || commandName === 'kick') {
const member = interaction.member;
if (!member.permissions.has('BAN_MEMBERS') && !member.permissions.has('KICK_MEMBERS')) {
return interaction.reply('You do not have permission to use this command.');
}
// 执行ban/kick操作
}
});
client.login('YOUR_BOT_TOKEN');
在执行ban/kick命令之前,检查调用者的权限。
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'ban' || commandName === 'kick') {
const member = interaction.member;
if (!member.permissions.has('BAN_MEMBERS') && !member.permissions.has('KICK_MEMBERS')) {
return interaction.reply('You do not have permission to use this command.');
}
// 执行ban/kick操作
}
});
你可以创建一个中间件函数,在每个命令执行前检查权限。
function checkPermissions(interaction, requiredPermissions) {
const member = interaction.member;
if (!member.permissions.has(requiredPermissions)) {
return interaction.reply('You do not have permission to use this command.');
}
return true;
}
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'ban' || commandName === 'kick') {
if (!checkPermissions(interaction, 'BAN_MEMBERS')) return;
// 执行ban操作
} else if (commandName === 'kick') {
if (!checkPermissions(interaction, 'KICK_MEMBERS')) return;
// 执行kick操作
}
});
通过以上方法,你可以有效地管理Discord服务器中的权限,确保只有授权用户才能执行ban/kick命令。
领取专属 10元无门槛券
手把手带您无忧上云