Discord斜杠命令获取目标用户报错:类型不匹配问题求助
解决Discord斜杠命令用户角色查询的类型错误
问题原因
错误TypeError [CommandInteractionOptionType]: Option "target" is of type: 3; expected 9的核心是选项类型定义与获取方式不匹配:
- 你用
addStringOption定义了类型为字符串(类型码3)的选项 - 但尝试用
getMentionable获取类型为可提及对象(类型码9)的选项,两者类型冲突导致报错
修复方案
根据你获取用户查询角色的需求,提供两种可行修改方式:
方式一:使用addUserOption(推荐,仅支持选择用户)
将选项定义为用户类型,获取时用getMember直接拿到服务器成员对象(包含角色数据):
module.exports = { data: new SlashCommandBuilder() .setName("list-roles") .setDescription("Check user roles") .addUserOption(option => option .setName('target') .setDescription('Select a user') .setRequired(true)), run: async (client, interaction) => { const member = interaction.options.getMember('target') const guildId = interaction.guild.id console.log(member.roles) // 直接输出该用户的角色集合 } }
方式二:使用addMentionableOption(支持选择用户/角色/频道)
如果需要兼容多种可提及对象,修改选项定义为可提及类型,保持getMentionable获取并额外判断类型:
module.exports = { data: new SlashCommandBuilder() .setName("list-roles") .setDescription("Check user roles") .addMentionableOption(option => option .setName('target') .setDescription('Select a user') .setRequired(true)), run: async (client, interaction) => { const target = interaction.options.getMentionable('target') // 判断是否为用户成员,避免选择角色/频道时出错 if (target.user) { console.log(target.roles) } const guildId = interaction.guild.id } }
关键说明
addUserOption对应getUser/getMember,专门用于用户选择,完全匹配你的角色查询场景addMentionableOption对应getMentionable,支持用户、角色、频道,需额外判断目标类型- 类型码对应关系:字符串=3,可提及对象=9,用户=6
内容的提问来源于stack exchange,提问作者nikkkushkaaafx
相关产品推荐
相关产品推荐

