Discord机器人已上线但不响应命令,遇GatewayIntentBits问题求助
Discord机器人无法响应命令的解决方法
你的代码存在三个关键问题,导致机器人无法响应命令,以下是对应的修复方案:
- 事件监听错误:discord.js v14及以上版本已废弃
message事件,必须改用messageCreate事件来监听消息。 - 参数分割逻辑错误:原代码中
message.content.split(prefix.length)用法错误,split方法需要传入字符串参数而非数字,应使用slice(prefix.length)截取前缀后的内容,再进行参数分割。 - 缺失必要意图:要读取消息内容,必须添加
GatewayIntentBits.MessageContent意图,同时需要在Discord开发者门户的机器人设置中开启消息内容特权(Message Content Intent)。
修复后的完整代码:
const { Client, GatewayIntentBits } = require('discord.js'); const prefix = '$'; const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessages, GatewayIntentBits.MessageContent // 添加消息内容读取意图 ] }); client.once('ready', () => { console.log('- - - - -'); console.log('bot is online!'); console.log('- - - - -'); }); // 改用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'); } }); client.login('TOKEN');
内容的提问来源于stack exchange,提问作者Aloxenツ
相关产品推荐
相关产品推荐

