如何在Discord.js中将User转换为GuildMember?
问题
我在用.addUserOption开发ban斜杠命令时,尝试获取目标用户的权限以避免机器人因封禁管理员崩溃,但出现错误。已明确原因:无法从User对象获取权限,仅能通过GuildMember对象获取,请教如何将User转换为GuildMember?
参考代码:
const { SlashCommandBuilder } = require('@discordjs/builders'); const { MessageEmbed } = require('discord.js') module.exports = { data: new SlashCommandBuilder() .setName("ban") .setDescription("Bans the specified user!") .addUserOption((option) => option .setName("user") .setDescription('Who do you want to ban?') .setRequired(true) ) .addStringOption((option) => option .setName('reason') .setDescription("Whats the reason youre banning this user?") ), async execute(client, interaction) { if (client.cooldowns.has(interaction.user.id)) { let cooldownEmbed = new MessageEmbed() .setTitle("Please wait for the cooldown to end.") .setDescription("This is so that the bot doesnt overload") .setColor("RED") .setFooter("The cooldown is 5 sec") .setTimestamp() interaction.reply({ embeds: [cooldownEmbed], ephemeral: true }); } else { const user = interaction.member const permission = user.permissions.has('BAN_MEMBERS'); let embed = new MessageEmbed() .setTitle("❌️ | You dont have the permissions to use this command.") if(!permission) return interaction.reply({embeds: [embed]}) const tgt = interaction.options.getUser('user') let permsEmbed = new MessageEmbed() .setTitle("The user you are trying to ban is an Administrator!") .setColor("RED") if (tgt.permissions.has('BAN_MEMBERS')) return interaction.reply({ embeds: [permsEmbed]}) const reason = interaction.options.getString('reason') || "No reason specified" client.cooldowns.set(interaction.user.id, true); setTimeout(() => { client.cooldowns.delete(interaction.user.id); }, client.COOLDOWN_SECONDS * 1000); } } }
解决方案
方法1:直接获取GuildMember(推荐)
不需要先获取User再转换,直接用interaction.options.getMember('user')就能拿到目标用户的GuildMember对象:
const tgtMember = interaction.options.getMember('user');
替换原代码中const tgt = interaction.options.getUser('user')这一行,之后即可正常进行权限检查:
if (tgtMember.permissions.has('BAN_MEMBERS')) { return interaction.reply({ embeds: [permsEmbed]}) }
方法2:从User对象转换为GuildMember
如果必须先获取User对象,可通过服务器成员API获取对应的GuildMember(异步操作需加await):
const tgtUser = interaction.options.getUser('user'); const tgtMember = await interaction.guild.members.fetch(tgtUser.id);
注意事项
- 确保机器人拥有
GUILD_MEMBERS权限,否则fetch操作可能失败 - 若目标用户不在当前服务器,
getMember会返回null,需提前做空值判断
内容的提问来源于stack exchange,提问作者stixyyST5
相关产品推荐
相关产品推荐

