You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:基于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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 15:03:25