Discord.js报错:TypeError: SlashCommandBuilder不是构造函数
解决「TypeError: SlashCommandBuilder is not a constructor」错误
核心问题原因
- discord.js@12.5.3 不包含
SlashCommandBuilder类,这个API是从discord.js v13版本才开始引入的。你在v12环境中调用仅v13+支持的构造函数,必然会触发类型错误。
解决方案一:在discord.js v12中实现斜杠命令
v12版本没有封装好的SlashCommandBuilder,需要直接调用Discord API完成命令注册,示例代码如下:
const { Client } = require('discord.js'); const client = new Client(); // 注册/party斜杠命令 async function registerPartyCommand() { const guildId = '你的服务器ID'; // 仅服务器级命令需要,全局命令删除此参数 const apiUrl = guildId ? `https://discord.com/api/v8/applications/${client.user.id}/guilds/${guildId}/commands` : `https://discord.com/api/v8/applications/${client.user.id}/commands`; const commandPayload = { name: 'party', description: '创建派对的命令', // 可选:添加命令参数 options: [ { name: 'title', type: 3, // 对应STRING类型 description: '派对标题', required: true } ] }; try { const response = await fetch(apiUrl, { method: 'POST', headers: { 'Authorization': `Bot ${client.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify(commandPayload) }); if (response.ok) { console.log('/party命令注册成功'); } else { const errorDetails = await response.json(); console.error('命令注册失败:', errorDetails); } } catch (err) { console.error('请求出错:', err); } } client.on('ready', () => { console.log(`已登录:${client.user.tag}`); registerPartyCommand(); }); // 处理斜杠命令交互 client.on('interaction', (interaction) => { if (!interaction.isCommand()) return; if (interaction.commandName === 'party') { const partyTitle = interaction.options.getString('title'); interaction.reply(`已创建派对:${partyTitle}`); } }); client.login('你的机器人令牌');
解决方案二:升级到discord.js v13+(推荐)
若想使用SlashCommandBuilder的便捷API,需将discord.js升级到v13或更高版本(你的Node.js v18.12.1满足版本要求)。
- 卸载旧版本:
npm uninstall discord.js@12.5.3
- 安装最新稳定版:
npm install discord.js
- 使用
SlashCommandBuilder的示例代码:
const { Client, SlashCommandBuilder, Intents } = require('discord.js'); const client = new Client({ intents: [Intents.FLAGS.GUILDS] }); client.on('ready', async () => { console.log(`已登录:${client.user.tag}`); // 构建/party命令 const partyCommand = new SlashCommandBuilder() .setName('party') .setDescription('快速创建派对') .addStringOption(option => option.setName('title') .setDescription('派对标题') .setRequired(true)); // 服务器级注册(立即生效) await client.guilds.cache.get('你的服务器ID')?.commands.create(partyCommand.toJSON()); // 全局注册(需1小时左右同步到所有服务器) // await client.application?.commands.create(partyCommand.toJSON()); }); // 处理命令交互 client.on('interactionCreate', async (interaction) => { if (!interaction.isCommand()) return; if (interaction.commandName === 'party') { const partyTitle = interaction.options.getString('title'); await interaction.reply(`派对「${partyTitle}」已创建!`); } }); client.login('你的机器人令牌');
内容的提问来源于stack exchange,提问作者Elijah Nelson
相关产品推荐
相关产品推荐

