Discord机器人封禁功能异常:命令无响应问题求助
问题排查与解决
核心错误分析
你的代码存在两个关键问题,直接导致机器人无法正常响应:
- 错误引用了不存在的变量:当前是
interactionCreate事件(处理Slash命令交互),不存在message对象,你用的message.author.id会直接抛出异常,机器人没有任何回复动作,Discord因此显示“The application did not respond”。 - 未正确获取交互发起用户ID:Slash命令场景下,应该用
interaction.user.id来获取发起命令的用户ID。
修复后的代码
client.on('interactionCreate', async (interaction) => { if (!interaction.isCommand()) { return; } const { commandName } = interaction; // 替换为实际的封禁用户ID,注意是字符串格式 const bannedid = "目标用户的ID"; if (commandName === 'ping') { if (interaction.user.id === bannedid) { return interaction.reply({ content: 'You are banned from usage', ephemeral: true, }); } await interaction.reply({ content: 'pong', }); } });
额外优化建议
- 如果需要封禁多个用户,可以用数组存储ID,判断逻辑改为
bannedIds.includes(interaction.user.id),示例:const bannedIds = ["用户ID1", "用户ID2"]; // ... if (bannedIds.includes(interaction.user.id)) { // 封禁提示逻辑 } - 添加异常捕获,避免单个命令报错导致机器人崩溃:
client.on('interactionCreate', async (interaction) => { try { if (!interaction.isCommand()) { return; } const { commandName } = interaction; const bannedid = "目标用户的ID"; if (commandName === 'ping') { if (interaction.user.id === bannedid) { return interaction.reply({ content: 'You are banned from usage', ephemeral: true, }); } await interaction.reply({ content: 'pong', }); } } catch (error) { console.error(error); if (!interaction.replied) { await interaction.reply({ content: '命令执行出错', ephemeral: true, }); } } });
内容的提问来源于stack exchange,提问作者rat
相关产品推荐
相关产品推荐

