【问题标题】:How do we make a kick command with userid?我们如何使用用户 ID 发出踢命令?
【发布时间】:2021-06-11 14:14:29
【问题描述】:

那么我们如何通过下面的 kick 命令检测用户 ID 呢?

下面是我的踢命令,每当我踢一个人时,我都需要提及他们 (?kick @test) 我想通过用户 ID (?kick 354353) 和他们的提及来踢一个用户。



const client = new Discord.Client();

client.on('ready', () => {
  console.log('I am ready!');
});

client.on('message', message => {
  // Ignore messages that aren't from a guild
  if (!message.guild) return;


  if (message.content.startsWith('?kick')) {
    if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS'])) 
    return;
    
    const user = message.mentions.users.first();
    if (user) {
      const member = message.guild.member(user);
      if (member) {
        member
          .kick('Optional reason that will display in the audit logs')
          .then(() => {
            message.reply(`Successfully kicked ${user.tag}`);
          })
          .catch(err => {
            message.reply('I was unable to kick the member');
            // Log the error
            console.error(err);
          });
      } else {
        // The mentioned user isn't in this guild
        message.reply("That user isn't in this guild!");
      }
      // Otherwise, if no user was mentioned
    } else {
      message.reply("You didn't mention the user to kick!");
    }
  }
});

client.login('TOKEN');

【问题讨论】:

    标签: discord command discord.js bots


    【解决方案1】:

    如果您打算执行更多需要用户输入的命令,我建议您设置 Arguments

    但是,如果您对完全设置参数不感兴趣,则可以将消息切片并获取 id。然后你需要获取成员对象,确保你的函数是 async 的,或者如果你愿意,可以使用Promise#then

    if (message.content.startsWith('?kick')) {
        if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS'])) 
        return;
       const memberId = message.content.slice(' ')[1];
    
       if (memberId) {
          const memberToKick = await message.guild.members.cache.fetch(userId);
    
          memberToKick.kick('Optional reason that will display in the audit logs')
              .then(() => {
                message.reply(`Successfully kicked ${user.tag}`);
              })
              .catch(err => {
                message.reply('I was unable to kick the member');
                // Log the error
                console.error(err);
              });
       }
    }
    

    【讨论】:

    • const memberToKick = await message.guild.members.cache.fetch(userId); ^^^^^ SyntaxError: await 仅在异步函数中有效
    • 就像我在回答中所说:确保你的函数是 async 为此
    • 您可以通过将消息事件标头更改为client.on('message', async message =>来做到这一点
    猜你喜欢
    • 2018-02-16
    • 2021-11-13
    • 2022-07-16
    • 2021-08-04
    • 2021-09-12
    • 2019-09-08
    • 2021-03-12
    • 2020-07-01
    • 2021-01-15
    相关资源
    最近更新 更多