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

discord.js机器人添加play、leave命令后所有命令无响应求助

问题修复方案

你代码的问题集中在discord.js版本适配的配置错误,按以下步骤修改即可恢复正常:

核心问题说明

  • 网关意图未配置:discord.js v13及以上版本要求明确声明网关意图才能接收对应数据,你当前传了空的intents数组,无法接收用户消息、语音状态等核心数据
  • 事件名使用已废弃接口:旧版message事件已在v13版本被替换为messageCreate,监听废弃事件无法获取用户发送的消息
  • 缺少自定义命令调用逻辑:你已经把commands目录下的命令加载到了client.commands集合,但没有写对应的调用逻辑,新增的play、leave命令自然不会生效

修复后完整代码

const { Client, GatewayIntentBits, Collection } = require('discord.js');
// 初始化时传入所有需要的意图
const client = new Client({ 
  intents: [
    GatewayIntentBits.Guilds, // 基础服务器访问意图,必选
    GatewayIntentBits.GuildMessages, // 接收服务器频道消息意图
    GatewayIntentBits.MessageContent, // 读取消息内容意图
    GatewayIntentBits.GuildVoiceStates // 语音功能所需的语音状态监听意图
  ] 
})

const prefix = '-';
const fs = require('fs');

client.commands = new Collection();

const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'))
for(const file of commandFiles){
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}

client.once('ready', () => {
   console.log('SaltSounds Is Online!');
});

// 监听正确的messageCreate事件
client.on('messageCreate', message =>{
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'ping'){
        message.channel.send('pong!')
    }
    // 新增自定义命令调用逻辑
    else if (client.commands.has(command)) {
        client.commands.get(command).execute(message, args);
    }
});

client.login('你的机器人token');

额外必要配置

登录Discord开发者后台,进入你的机器人应用的「Bot」设置页,找到Privileged Gateway Intents分区,把以下开关全部打开:

  • Message Content Intent
  • Server Members Intent
  • Voice State Intent
    未打开这些特权权限的话,就算代码配置了意图也无法正常获取对应数据。

内容的提问来源于stack exchange,提问作者MrPureSalt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:24:06