Discord.js 机器人运行时报错TypeError: "" is not a function 如何修复?
Discord.js 机器人运行时报错TypeError: "" is not a function 如何修复?
这个错误的根源是你在使用 setIntegrationTypes 和 setContexts 方法时,参数传递方式不符合Discord.js的要求。在v14及以上版本中,这两个方法都需要接收数组类型的参数,而不是把每个值作为独立参数逐个传递。
具体问题分析
你当前代码里的调用方式是这样的:
.setIntegrationTypes(0, 1) .setContexts(0, 1, 2);
但 setIntegrationTypes 和 setContexts 的设计逻辑是接收一个包含类型值的数组,直接传递多个数值参数会导致方法解析失败,进而抛出 TypeError: "" is not a function 异常。
修复步骤
- 核心修复:把
setIntegrationTypes和setContexts的参数改成数组形式。 - 可读性优化(可选):使用Discord.js提供的枚举值替代纯数字,让代码更易维护。
- 避免重复命令(可选):不要在每次机器人启动时都创建命令,否则会生成大量重复命令,建议添加检查逻辑或使用REST API批量注册。
修正后的完整代码
const { Client, Events, GatewayIntentBits, SlashCommandBuilder, IntegrationType, InteractionContextType } = require('discord.js'); const { token } = require('./config.json'); const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers] }); client.once(Events.ClientReady, async c => { console.log(`Logged in as ${c.user.tag}`); const ping = new SlashCommandBuilder() .setName('ping') .setDescription('Pings another user') .addUserOption(option => option .setName('pingd') .setDescription('Who to ping?') .setRequired(false) ) // 修正:传递数组参数,使用枚举值增强可读性 .setIntegrationTypes([IntegrationType.GuildInstall, IntegrationType.UserInstall]) .setContexts([ InteractionContextType.Guild, InteractionContextType.BotDM, InteractionContextType.PrivateChannel ]); const noni = new SlashCommandBuilder() .setName('noni') .setDescription('Test command') .setIntegrationTypes([IntegrationType.GuildInstall, IntegrationType.UserInstall]) .setContexts([ InteractionContextType.Guild, InteractionContextType.BotDM, InteractionContextType.PrivateChannel ]); // 可选:先检查命令是否存在再创建,避免重复堆积 const existingCommands = await client.application.commands.fetch(); if (!existingCommands.find(cmd => cmd.name === 'ping')) { await client.application.commands.create(ping); } if (!existingCommands.find(cmd => cmd.name === 'noni')) { await client.application.commands.create(noni); } }); client.on(Events.InteractionCreate, interaction => { if (!interaction.isChatInputCommand()) return; if (interaction.commandName === "ping") { let user = interaction.options.getUser('pingd'); if (!user) user = interaction.user; // 使用user.toString()生成正确的@提及格式(会触发提醒) interaction.reply(`\`test\`\n${user.toString()}`); } if (interaction.commandName === "noni") { interaction.reply(`\`another test!\``); } }); client.login(token);
额外说明
- 如果你不想使用枚举值,直接用数字数组也能正常工作,比如
.setIntegrationTypes([0,1])和.setContexts([0,1,2])。 - 回复用户时,
user.toString()会生成<@用户ID>的格式,能真正触发@提醒;而@${user.username}只是纯文本,不会有提醒效果。 - 生产环境中更推荐使用REST API批量注册命令,而非在Ready事件中逐个创建,这是Discord官方推荐的最佳实践。
备注:内容来源于stack exchange,提问作者dawutheuwad
相关产品推荐
相关产品推荐

