Некоторые проблемы с кодом команды !kick

#javascript #node.js #discord #discord.js

#javascript #node.js #Discord #discord.js

Вопрос:

У меня возникли некоторые проблемы с моей Discord.js командой kick.

Мой код:

 const Discord = require('discord.js');

const { prefix, token } = require('../config.json');

module.exports = {
 name: 'kick',
 description: 'kick users',
 execute(message, args) {
  if (!message.member.hasPermission('KICK_MEMBERS')) {
   return message.channel.send({
    embed: {
     color: 16777201,
     description: `:x: | ${message.author}, You are not allowed to use this command.`,
     footer: {
      text: ` | Required permission: KICK_MEMBERS`,
     },
    },
   });
  }
  if (!message.guild.me.permissions.has('KICK_MEMBERS')) {
   return message.channel.send({
    embed: {
     color: 16777201,
     description: `:x: | ${message.author}, I am not allowed to use this command.`,
     footer: {
      text: ` | Required permission: KICK_MEMBERS`,
     },
    },
   });
  }

  if (!args[0]) {
   return message.channel.send({
    embed: {
     color: 16777201,
     description: `:x: | ${message.author}, You need to mention a user first.`,
     footer: {
      text: ` | Example: !kick @Bot`,
     },
    },
   });
  }
  const member =
   message.mentions.members.first() || message.guild.members.cache.get(args[0]);
  if (member.user.id === message.author.id) {
   return message.channel.send({
    embed: {
     color: 16777201,
     description: `:x: | ${message.author}, You cannot expel yourself.`,
     footer: {
      text: ` | Example: !kick @Bot`,
     },
    },
   });
  }
  try {
   member.kick();
   message.channel.send(`${member} has been kicked!`);
  } catch (e) {
   return message.channel.send(`User isn't in this server!`);
  }
 },
};
  

Игнорируйте незавершенный код, я все еще думаю о дизайне встраиваемых!

Я пытаюсь сделать 3 вещи:

  • Я бы хотел, если бы кто-то попытался использовать команду, упомянув бота, они бы сказали что-то вроде «вам не разрешено это делать»

  • Другая вещь, которую я хочу, это то, что пользователь не может ударить кого-то выше него

  • Я хочу, чтобы участник был выгнан, вы должны отреагировать да или нет

Ответ №1:

Я собираюсь попытаться решить ваши проблемы одну за другой:


  • Прежде всего, я хотел бы, чтобы если кто-то попытался использовать команду, упомянув бота, он сказал бы что-то вроде «вам не разрешено это делать»

Вы можете выполнить if инструкцию, чтобы определить, использует ли упомянутый участник то же самое, ID что и ваш бот, используя client.user свойство (пользователь, от имени которого зарегистрирован ваш клиент)

 if (member.id === client.user.id)
 return message.channel.send('You cannot ban me');
  

  • Другая вещь, которую я хочу, это то, что пользователь не может ударить кого-то выше него

Вы можете решить это, сравнив roles.highest.position свойство обоих членов. Это свойство вернет число. чем больше число, тем выше роль в приоритете.

 if (message.member.roles.highest.position <= member.roles.highest.position)
 return message.channel.send(
  'Cannot kick that member because they have roles that are higher or equal to you.'
 );
  

  • И, наконец, я хочу, чтобы участник был выгнан, вы должны отреагировать да или нет

Для этого вам нужно будет использовать сборщик реакций. Вот как вы можете это сделать с помощью Message.awaitReactions . Этот метод будет ждать, пока кто-то отреагирует на сообщение, а затем зарегистрирует реакцию эмодзи.

 // first send the confirmation message, then react to it with yes/no emojis
message.channel
 .send(`Are you sure you want to kick ${member.username}?`)
 .then((msg) => {
  msg.react('👍');
  msg.react('👎');

  // filter function
  const filter = (reaction, user) =>
   ['👍', '👎'].includes(reaction.emoji.name) amp;amp; user.id === message.author.id; // make sure it's the correct reaction, and make sure it's the message author who's reacting to it

  message
   .awaitReactions(filter, { time: 30000 }) // make a 30 second time limit before cancelling
   .then((collected) => {
    // do whatever you'd like with the reactions now

    if (message.reaction.name === '👍') {
     // kick the user
    } else {
     // don't kick the user
    }
   })
   .catch(console.log(`${message.author.username} didn't react in time`));
 });