Discord.js音乐机器人报错:GatewayIntentBits未定义,求修复方案
修复Discord音乐机器人的GatewayIntentBits未定义错误
错误原因
你的代码中导入了Intents对象,但使用了未声明的GatewayIntentBits——这是Discord.js版本差异导致的:
- Discord.js v13 中,意图常量通过
Intents.FLAGS访问 - Discord.js v14 中,意图常量被移至
GatewayIntentBits对象
修复方案
根据你使用的Discord.js版本选择对应方案:
方案1:适配Discord.js v14版本
修改导入语句,替换Intents为GatewayIntentBits,并修正login方法参数:
const { Client, GatewayIntentBits } = require('discord.js'); const ytdl = require('ytdl-core'); const ytSearch = require('youtube-search'); const token = 'xxxxxxxxxxxxxxxxxxxx'; // ds token const client = new Client({ intents: [ GatewayIntentBits.GUILDS, GatewayIntentBits.GUILD_MESSAGES, GatewayIntentBits.GUILD_VOICE_STATES, GatewayIntentBits.GUILD_MESSAGE_REACTIONS, ] }); const opts = { maxResults: 5, key: 'xxxxxxxxxxxxxxxxxxxxxxxx', // youtube api type: 'video', }; let dispatcher = null; let repeat = false; client.once('ready', () => { console.log('Bot is online!'); }); client.on('messageCreate', async (message) => { if (message.author.bot) return; const voiceChannel = message.member.voice.channel; if (message.content.startsWith('!play')) { if (!voiceChannel) { return message.channel.send('Вы должны находиться в голосовом канале, чтобы проиграть музыку!'); } const searchQuery = message.content.replace('!play', '').trim(); try { const results = await ytSearch(searchQuery, opts); const videoURL = results[0].link; const connection = await voiceChannel.join(); const stream = ytdl(videoURL, { filter: 'audioonly' }); dispatcher = connection.play(stream, { seek: 0, volume: 1 }); dispatcher.on('finish', () => { if (repeat) { dispatcher = connection.play(stream, { seek: 0, volume: 1 }); } else { voiceChannel.leave(); dispatcher = null; } }); } catch (error) { console.error(error); message.channel.send('Произошла ошибка при воспроизведении музыки!'); } } if (message.content === '!stop') { if (!voiceChannel) return message.channel.send('Вы должны находиться в голосовом канале!'); if (dispatcher) { dispatcher.end(); dispatcher = null; voiceChannel.leave(); } } if (message.content === '!skip') { if (dispatcher) { dispatcher.end(); dispatcher = null; } } if (message.content === '!repeat') { repeat = !repeat; message.channel.send(`Режим повтора воспроизведения: ${repeat ? 'Включен' : 'Выключен'}`); } }); client.login(token);
方案2:适配Discord.js v13版本
保留Intents导入,将意图常量改为Intents.FLAGS前缀:
const { Client, Intents } = require('discord.js'); const ytdl = require('ytdl-core'); const ytSearch = require('youtube-search'); const token = 'xxxxxxxxxxxxxxxxxxxx'; // ds token const client = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS, ] }); // 后续代码与方案1一致,需将client.login(xxxxxxxxxxxxxxxx);改为client.login(token);
额外修复说明
- 修正
client.login参数,使用定义好的token变量避免硬编码错误 - 在
!stop命令中增加语音频道判断,防止用户不在频道时出现undefined错误
内容的提问来源于stack exchange,提问作者Belenciuc Nichita
相关产品推荐
相关产品推荐

