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

请求优化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('播放失败,请检查链接是否有效或机器人权限是否足够!');
        }
    }
};

关键更新说明

  1. 语音功能迁移:Discord.js v14将语音功能拆分到@discordjs/voice包,替代了旧版废弃的VoiceConnection API,避免版本兼容报错。
  2. 组件更新:旧版MessageEmbed已被EmbedBuilder替代,符合v14的组件规范。
  3. 错误处理优化:添加全局try/catch捕获异常,同时给用户明确的失败提示。
  4. 资源优化:使用filter: 'audioonly'只拉取音频流,减少不必要的带宽占用。

必备权限

确保你的机器人在服务器中有以下权限:

  • 连接语音频道(Connect)
  • 在语音频道发言(Speak)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:15:48