求助:基于discord.js的Discord机器人不响应Slash命令
Discord机器人不响应Slash命令问题
我基于discord.js库开发的机器人,已经实现了interactionCreate事件处理器,但Slash命令没有任何响应。
以下是相关代码:
const { Client, GatewayIntentBits, Partials, InteractionType, Permissions, SlashCommandBuilder, Collection } = require('discord.js'); const dotenv = require('dotenv'); const fs = require('fs'); dotenv.config(); const token = process.env.TOKEN; const clientId = process.env.CLIENT_ID; const guildId = process.env.GUILD_ID; const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildVoiceStates, ], partials: [Partials.Channel], }); client.commands = new Collection(); const commandsPath = './commands'; const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const filePath = `./commands/${file}`; const command = require(filePath); if ('data' in command && typeof command.data === 'object') { if ('toJSON' in command.data) { client.commands.set(command.data.name, command); } else { console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "toJSON" export.`); } } else { console.log(`[WARNING] The command at ${filePath} is missing a required "data" export.`); } } console.log('Starting bot...'); client.once('ready', () => { console.log(`Logged in as ${client.user.tag}!`); const guild = client.guilds.cache.get(guildId); guild.commands.set(client.commands.map(command => command.data)) .then(() => console.log('Slash commands registered successfully.')) .catch(console.error); }); client.on('interactionCreate', async interaction => { // Filter out non-command interactions if (!interaction.isChatInputCommand()) return; const command = client.commands.get(interaction.commandName); if (!command) return; try { await command.execute(interaction); } catch (error) { console.error(`Error handling interaction ${interaction.commandName}:`, error); if (interaction.replied || interaction.deferred) { await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true }); } else { await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true }); } } }); client.login(token);
我原本期望机器人能响应Slash命令并执行对应操作,但目前没有任何响应。已尝试以下排查步骤:
- 确保机器人在线且拥有必要权限
- 检查Slash命令注册流程
- 验证interactionCreate事件处理器逻辑
- 测试不同Slash命令以隔离问题
内容的提问来源于stack exchange,提问作者sultan mhmwwed
相关产品推荐
相关产品推荐

