请求优化Discord机器人!song1命令:指定YouTube URL播放功能
解决方案:适配Discord.js v14的预设YouTube播放命令
第一步:安装最新依赖
你的旧代码基于Discord.js老版本,现在需要更新到最新稳定版,同时安装语音功能所需的配套包:
npm install discord.js @discordjs/voice ytdl-core ffmpeg-static
第二步:替换为新版无报错代码
以下是适配Discord.js v14的song1.js完整代码,直接替换你现有的文件即可:
const { EmbedBuilder } = require('discord.js'); const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require('@discordjs/voice'); const ytdl = require('ytdl-core'); module.exports = { commands: 'song1', callback: async (message) => { // 预设的YouTube歌曲链接 const targetUrl = 'https://www.youtube.com/your-song-url-here'; // 检查用户是否在语音频道 if (!message.member.voice.channel) { return message.reply('你得先加入一个语音频道才行!'); } try { // 加入用户所在的语音频道 const voiceConnection = joinVoiceChannel({ channelId: message.member.voice.channel.id, guildId: message.guild.id, adapterCreator: message.guild.voiceAdapterCreator, }); // 创建音频播放器和资源 const player = createAudioPlayer(); const audioResource = createAudioResource(ytdl(targetUrl, { filter: 'audioonly' })); // 播放音频 player.play(audioResource); voiceConnection.subscribe(player); // 播放结束后自动断开连接 player.on(AudioPlayerStatus.Idle, () => { voiceConnection.destroy(); }); // 发送播放通知Embed const playEmbed = new EmbedBuilder() .setTitle('正在播放:song1') .setAuthor({ name: message.author.username, iconURL: message.author.displayAvatarURL() }) .setTimestamp() .setColor('#447a88'); await message.reply({ embeds: [playEmbed] }); } catch (error) { console.error('播放出错:', error); await message.reply('播放失败,请检查链接是否有效或机器人权限是否足够!'); } } };
关键更新说明
- 语音功能迁移:Discord.js v14将语音功能拆分到
@discordjs/voice包,替代了旧版废弃的VoiceConnectionAPI,避免版本兼容报错。 - 组件更新:旧版
MessageEmbed已被EmbedBuilder替代,符合v14的组件规范。 - 错误处理优化:添加全局
try/catch捕获异常,同时给用户明确的失败提示。 - 资源优化:使用
filter: 'audioonly'只拉取音频流,减少不必要的带宽占用。
必备权限
确保你的机器人在服务器中有以下权限:
- 连接语音频道(Connect)
- 在语音频道发言(Speak)
内容的提问来源于stack exchange,提问作者Mansoor
相关产品推荐
相关产品推荐

