Discord.js 开发求助:踢人(Kick)命令出现TypeError: options.getMember is not a function错误
解决Discord.js Kick命令中的
options.getMember is not a function错误 这个错误的核心原因很明确:你在命令选项里把target的类型设为了USER,但getMember()方法只能用于类型为GUILD_MEMBER的选项。Discord.js中,USER类型对应的方法是getUser(),只有GUILD_MEMBER类型的选项才能调用getMember()。
这里有两种可行的修复方案,附带一些代码优化建议:
方案1:修改选项类型为GUILD_MEMBER
这是最直接的修复方式,把选项的type从"USER"改成"GUILD_MEMBER",就能直接使用getMember()获取服务器成员对象:
const { Client, CommandInteraction } = require("discord.js"); module.exports = { name: "kick", description: "Kick a member", userPermission: ["KICK_MEMBERS"], options: [ { name: "target", description: "target to kick", type: "GUILD_MEMBER", // 修改为GUILD_MEMBER类型 required: true }, { name: "reason", description: "reason for this kick", type: "STRING", required: false, } ], /** * * @param {Client} client * @param {CommandInteraction} interaction * @param {String} args */ execute: async(client, interaction, args) => { const { options, member } = interaction; const target = options.getMember("target"); // 现在可以正常调用 const reason = options.getString("reason") || "No reason provided"; // 修正权限判断逻辑:原代码的!会导致判断反转 if (target.roles.highest.position >= member.roles.highest.position) return interaction.followUp({content: "You can't take action on this user as their role is higher than yours!"}); // 处理私信发送失败的情况(比如用户关闭了私信) try { await target.send(`You have been kicked from ${interaction.guild.name}, reason: ${reason}`); } catch (err) { console.log(`无法给用户${target.user.tag}发送私信:`, err); } await target.kick(reason); // 加await确保操作完成 await interaction.followUp({content: `Kicked ${target.user.tag} successfully! Reason: ${reason}`}); }, };
方案2:保留USER类型,通过用户对象获取成员
如果你想保留USER类型的选项,可以先用getUser()获取用户对象,再通过服务器成员缓存或fetch方法获取成员:
// 其他代码不变 execute: async(client, interaction, args) => { const { options, member, guild } = interaction; const targetUser = options.getUser("target"); // 通过用户ID获取服务器成员 const target = await guild.members.fetch(targetUser.id); const reason = options.getString("reason") || "No reason provided"; // 修正权限判断逻辑 if (target.roles.highest.position >= member.roles.highest.position) return interaction.followUp({content: "You can't take action on this user as their role is higher than yours!"}); try { await target.send(`You have been kicked from ${interaction.guild.name}, reason: ${reason}`); } catch (err) { console.log(`无法给用户${target.user.tag}发送私信:`, err); } await target.kick(reason); await interaction.followUp({content: `Kicked ${target.user.tag} successfully! Reason: ${reason}`}); },
额外优化说明
- 权限判断修正:你原代码中的
!target.roles.highest.position >= member.roles.highest.position逻辑是反转的——它会在目标角色低于你的时候返回提示,和预期效果相反,所以要去掉前面的!。 - 添加
await:target.kick()和interaction.followUp()都是异步操作,加上await能确保命令按预期顺序执行。 - 私信异常处理:部分用户可能关闭了服务器成员的私信权限,用
try/catch包裹私信发送逻辑,避免因为发送失败导致整个命令崩溃。
内容的提问来源于stack exchange,提问作者MrAplex
相关产品推荐
相关产品推荐

