You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Discord.js踢人命令添加非服务器成员检测提示功能

Fixing the Kick Command to Handle Users Not in the Server

Got it, let's adjust your kick command to properly handle cases where the target user isn't part of the current server. The core issue here is that options.getMember("target") will return null if the user isn't in the guild, so we just need to add a quick check for that early in your execution logic. I'll also fix a small logic bug in your role position check and add a safety net for DM failures (since some users disable server DMs).

Here's the modified full code:

const { Client, CommandInteraction, MessageEmbed } = require("discord.js");
module.exports = {
 name: "kick",
 description: "Kick a member",
 userPermission: ["KICK_MEMBERS"],
 options: [
  {
   name: "target",
   description: "target to kick",
   type: "USER",
   required: true
  },
  {
   name: "reason",
   description: "reason for this kick",
   type: "STRING",
   required: false,
  }
 ],
 /**
  *
  * @param {Client} client
  * @param {CommandInteraction} interaction
  * @param {String} args
  */
 execute: async(interaction, client, args) => {
  const { options, member, guild } = interaction;
  const target = options.getMember("target");
  const reason = options.getString("reason") || "No reason provided";

  // Check if the target is actually in the server
  if (!target) {
    return interaction.reply({
      content: "无法踢出该用户,因为他们不在此服务器中",
      ephemeral: true // Makes this reply only visible to you (optional but clean)
    });
  }

  // Fixed role position check (removed the incorrect ! operator)
  if (target.roles.highest.position >= member.roles.highest.position) {
    return interaction.reply({
      content: "You can't take action on this user as their role is higher than yours!",
      ephemeral: true
    });
  }

  try {
    // Attempt to send a DM to the target (handle cases where DMs are disabled)
    await target.send({
      embeds: [new MessageEmbed()
        .setColor("AQUA")
        .setTitle("🚪 Kicked")
        .setAuthor(target.user.tag, target.user.avatarURL({dynamic: true, size: 512}))
        .setDescription(`You have been kicked from **${guild.name}**!\nReason: \`${reason}\``)
        .setFooter(`ID: ${target.user.id}`)
      ]
    });
  } catch (err) {
    // Log the DM failure but don't cancel the kick
    console.log(`Failed to send DM to ${target.user.tag}:`, err);
  }

  await target.kick(reason);
  interaction.reply({
    embeds: [new MessageEmbed()
      .setColor("GREEN")
      .setTitle("🚪 Kick")
      .setAuthor(target.user.tag, target.user.avatarURL({dynamic: true, size: 512}))
      .setDescription(`**${target.user.tag}** has successfully been kicked from **${guild.name}**!\n**Reason:** \`${reason}\``)
      .setFooter(`ID: ${target.user.id}`)
    ]
  });
 },
};

Key Changes Explained:

  • Target Presence Check: The if (!target) block catches when getMember() returns null (meaning the user isn't in the guild) and sends your desired error message. The ephemeral: true flag ensures only the person who ran the command sees this message, keeping your channel clean.
  • Fixed Role Permission Logic: Your original code had an extra ! in the role position check, which reversed the logic. Now it correctly blocks actions if the target's highest role is equal to or higher than yours.
  • DM Failure Handling: Wrapping the DM send in a try/catch prevents the command from failing entirely if the target has DMs disabled. We just log the error to the console instead.

内容的提问来源于stack exchange,提问作者MrAplex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 14:19:08