Discord.js机器人服务器指令正常,DM中无指令显示问题求助
Discord机器人DM场景指令无法显示问题排查与解决
问题概述
开发的Discord机器人可查看用户状态(在线、请勿打扰、离线)及正在收听的歌曲,在自建服务器内运行正常,但切换至私信(DM)场景时,所有指令(activity、ping、user)均无法显示。
项目目录结构
commands/ └── utility/ ├── ping.js ├── check_activity.js ├── user.js server/ ├── api.js ├── models/ └── activity.js deploy-commands.js index.js
关键代码片段
index.js(不含MongoDB部分)
const fs = require('node:fs'); const path = require('node:path'); const { Client, Collection, Events, GatewayIntentBits, MessageFlags } = require('discord.js'); const { token } = require('./config.json'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildPresences, ], }); client.commands = new Collection(); const foldersPath = path.join(__dirname, 'commands'); const commandFolders = fs.readdirSync(foldersPath); for (const folder of commandFolders) { const commandsPath = path.join(foldersPath, folder); const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const filePath = path.join(commandsPath, file); const command = require(filePath); if ('data' in command && 'execute' in command) { client.commands.set(command.data.name, command); } else { console.warn(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`); } } } client.once(Events.ClientReady, readyClient => { console.log(`Ready! Logged in as ${readyClient.user.tag}`); }); client.on(Events.InteractionCreate, async interaction => { if (!interaction.isChatInputCommand()) return; const command = interaction.client.commands.get(interaction.commandName); if (!command) { console.error(`No command matching ${interaction.commandName} was found.`); return; } try { await command.execute(interaction); } catch (error) { console.error(error); const errorMessage = 'There was an error while executing this command!'; if (interaction.replied || interaction.deferred) { await interaction.followUp({ content: errorMessage, flags: MessageFlags.Ephemeral }); } else { await interaction.reply({ content: errorMessage, flags: MessageFlags.Ephemeral }); } } }); client.login(token);
deploy-commands.js
const { REST, Routes } = require('discord.js'); const { clientId, guildId, token } = require('./config.json'); const fs = require('node:fs'); const path = require('node:path'); const commands = []; const foldersPath = path.join(__dirname, 'commands'); const commandFolders = fs.readdirSync(foldersPath); for (const folder of commandFolders) { const commandsPath = path.join(foldersPath, folder); const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const filePath = path.join(commandsPath, file); const command = require(filePath); if ('data' in command && 'execute' in command) { commands.push(command.data.toJSON()); } else { console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`); } } } const rest = new REST().setToken(token); (async () => { try { console.log(`Started refreshing ${commands.length} application (/) commands.`); const data = await rest.put( Routes.applicationCommands(clientId), { body: commands }, ); console.log(`Successfully reloaded ${data.length} application (/) commands.`); } catch (error) { console.error(error); } })();
已尝试操作
- 在线搜索类似问题,未找到有效解决方案
- 检查DM场景的权限与Intents配置
问题核心疑问
是否因机器人依赖服务器(Guild)相关功能导致无法在DM中运行?若如此,需修改哪些内容以同时支持服务器和DM场景?
解决方案
1. 补充DM相关网关Intents
机器人无法接收DM交互的核心原因是缺少DirectMessage类的网关权限,需修改index.js中客户端的Intents配置:
const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildPresences, // 添加以下两个DM相关Intent GatewayIntentBits.DirectMessages, GatewayIntentBits.DirectMessageContent ], });
2. 验证开发者门户权限设置
进入Discord开发者门户的Bot页面:
- 确保Privileged Gateway Intents下的
Message Content Intent已开启(该权限同时影响服务器与DM的内容读取) - 确认
Public Bot选项状态:若关闭,仅已邀请机器人的服务器成员可互动,需根据需求调整
3. 适配命令的DM兼容性
部分命令(如check_activity、user)可能依赖服务器(Guild)数据,在DM场景下interaction.guild为null,需在命令的execute函数中添加兼容判断:
示例:限制命令仅在服务器使用
// 以check_activity.js为例 module.exports = { data: ..., async execute(interaction) { // 若在DM中调用,直接提示 if (!interaction.guild) { return interaction.reply({ content: "此命令仅支持在服务器内使用", ephemeral: true }); } // 原服务器内的逻辑代码... } };
示例:兼容DM场景(查看用户自身状态)
若要支持在DM中查看用户自身状态,可修改逻辑使用interaction.user替代服务器成员获取:
// 调整状态查询逻辑 const user = interaction.user; const presence = client.presences.cache.get(user.id); // 后续处理逻辑...
4. 重新部署命令(可选)
虽然已全局部署命令,但若DM仍未同步,可重新运行deploy-commands.js确保命令全局生效:
node deploy-commands.js
内容的提问来源于stack exchange,提问作者Stephanie Yao
相关产品推荐
相关产品推荐

