Discord.js机器人添加选择菜单报错:interaction.isStringSelectMenu不是函数
原因分析
这个报错是Discord.js版本不匹配导致的:
- Discord.js v14 才新增了细分的交互校验方法,比如
isStringSelectMenu()、isUserSelectMenu()等 - 如果你当前用的是v13版本,只有通用的
isSelectMenu()方法,没有细分的字符串选择菜单校验方法,所以会报错。而isChatInputCommand()在v13和v14版本中都存在,因此能正常运行。
解决方案
方案1:升级到Discord.js v14
如果要使用isStringSelectMenu(),需将Discord.js升级到v14版本,执行以下命令:
npm install discord.js@latest
升级后记得同步调整代码,适配v14的其他变动(比如组件构建方式、交互处理逻辑)。
方案2:适配v13版本(不升级)
如果暂时不想升级,把校验代码改成v13的通用写法:
// 替换原来的 if (interaction.isStringSelectMenu()) if (interaction.isSelectMenu()) { // 处理选择菜单交互 // 如需区分字符串选择菜单,可通过componentType判断 if (interaction.componentType === 'STRING_SELECT') { // 字符串选择菜单的业务逻辑 } }
对应Discord.js指南内容翻译
构建并发送选择菜单
创建字符串选择菜单
字符串选择菜单允许用户从预设选项列表中选择单个或多个选项,可通过StringSelectMenuBuilder构建:
const { StringSelectMenuBuilder, ActionRowBuilder } = require('discord.js'); const select = new StringSelectMenuBuilder() .setCustomId('select') .setPlaceholder('选择一个选项') .addOptions( { label: '选项1', description: '这是第一个选项的描述', value: 'option1', }, { label: '选项2', description: '这是第二个选项的描述', value: 'option2', }, { label: '选项3', description: '这是第三个选项的描述', value: 'option3', }, ); const row = new ActionRowBuilder().addComponents(select); // 发送到指定频道 channel.send({ content: '请选择一个选项:', components: [row] });
处理选择菜单交互
要处理选择菜单交互,需要监听interactionCreate事件并校验交互类型:
client.on('interactionCreate', interaction => { if (!interaction.isStringSelectMenu()) return; // 处理选择逻辑 console.log(`用户选择了:${interaction.values.join(', ')}`); interaction.reply(`你选择了:${interaction.values.join(', ')}`); });
注意:这段代码仅适用于Discord.js v14及以上版本,v13版本需使用isSelectMenu()并通过componentType区分菜单类型。
内容的提问来源于stack exchange,提问作者DaveExotic
相关产品推荐
相关产品推荐

