如何修复Discord音乐机器人在歌曲播放完成前断开连接的问题?
问题
我的Discord音乐机器人原本可正常播放音乐,但今日出现歌曲播放中途断开连接的情况,命令窗口无任何报错信息,此前并未出现该问题。
机器人核心代码(index.js)
require('dotenv').config(); const {REST} = require('@discordjs/rest'); const { Routes } = require('discord-api-types/v9'); const { Client, GatewayIntentBits, Collection } = require("discord.js"); const { Player } = require("discord-player"); const fs = require('fs'); const path = require('path'); const client = new Client({ intents: [ GatewayIntentBits.GuildMessages, GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildScheduledEvents, GatewayIntentBits.GuildMessageReactions, GatewayIntentBits.GuildVoiceStates, ], }); // List of all commands const commands = []; client.commands = new Collection(); const commandsPath = path.join(__dirname, "commands"); // E:\yt\discord bot\js\intro\commands 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); client.commands.set(command.data.name, command); commands.push(command.data.toJSON()); } // Add the player on the client client.player = new Player(client, { ytdlOptions: { quality: "highestaudio", highWaterMark: 1 << 25 },FFMPEG_OPTIONS: {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'} }) client.on("ready", () => { // Get all ids of the servers const guild_ids = client.guilds.cache.map(guild => guild.id); const rest = new REST({version: '9'}).setToken(process.env.TOKEN); for (const guildId of guild_ids) { rest.put(Routes.applicationGuildCommands(process.env.CLIENT_ID, guildId), {body: commands}) .then(() => console.log('Successfully updated commands for guild ' + guildId)) .catch(console.error); } }); client.on("interactionCreate", async interaction => { if(!interaction.isCommand()) return; const command = client.commands.get(interaction.commandName); if(!command) return; try { await command.execute({client, interaction}); } catch(error) { console.error(error); await interaction.reply({content: "BOCCHI.EXE IS NOT WORKING \nhttps://tenor.com/view/bocchi-bocchi-the-rock-non-linear-gif-27023528"}); } }); client.login(process.env.TOKEN);
依赖配置(package.json)
{ "name": "intro", "version": "1.0.0", "description": "After you have cloned the repo make sure to create a `.env` file with the `TOKEN` and `CLIENT_ID` specified for example", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "@discordjs/builders": "^1.4.0", "@discordjs/opus": "^0.9.0", "@discordjs/rest": "^1.5.0", "@discordjs/voice": "^0.10.0", "discord-api-types": "^0.37.28", "discord-player": "^5.3.2", "discord.js": "^14.7.1", "dotenv": "^16.0.3", "ffmpeg-static": "^5.1.0", "soundcloud-scraper": "^5.0.3", "youtube-sr": "^4.3.4", "ytdl-core": "^4.11.2" }, "devDependencies": { "@types/node": "^18.11.18" } }
请问是否有修复该问题的方法?或是Discord服务器出现了问题?
修复方案
1. 修正FFmpeg配置的位置与命名
你当前的FFMPEG_OPTIONS配置位置错误,且参数名不符合discord-player的要求,导致自动重连逻辑未生效。修改player初始化代码:
client.player = new Player(client, { ytdlOptions: { quality: "highestaudio", highWaterMark: 1 << 25, // 将FFmpeg选项移至ytdlOptions内部,且使用小写参数名 ffmpegOptions: { before_options: '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', options: '-vn' } } })
2. 添加player错误监听
当前代码未捕获播放/连接错误,导致断开无日志。在client初始化后添加以下代码:
client.player.on('error', (queue, error) => { console.log(`[${queue.guild.name}] 播放出错: ${error.message}`); }); client.player.on('connectionError', (queue, error) => { console.log(`[${queue.guild.name}] 连接出错: ${error.message}`); });
这能帮你定位断开的具体原因,区分是Discord服务器问题还是本地/资源故障。
3. 排查语音连接稳定性
- 检查机器人所在服务器的网络状态,确保无高延迟或丢包
- 在Discord服务器设置中切换「语音区域」,排除节点故障
- 确认无其他占用带宽的应用干扰音频流
4. 更新核心依赖
你的discord-player版本较旧,可能存在已知连接bug。执行命令更新:
npm update discord-player @discordjs/voice ytdl-core
更新后重启机器人测试。
5. 清理冗余Intent配置
你重复添加了GuildVoiceStates,清理后确保intent列表唯一:
const client = new Client({ intents: [ GatewayIntentBits.GuildMessages, GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildScheduledEvents, GatewayIntentBits.GuildMessageReactions ], });
内容的提问来源于stack exchange,提问作者Mushkin Fyodosky
相关产品推荐
相关产品推荐

