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

基于discord.js v13开发支持YouTube搜索的Discord音乐机器人求助

Discord.js v13 音乐机器人实现方案

前置环境与依赖

  • Node.js版本要求 ≥ 16.9.0,这是discord.js v13的最低运行要求
  • 所需依赖安装命令:
npm install discord.js@13 @discordjs/voice ytdl-core yt-search
  • 需在Discord开发者门户的机器人设置页开启Message Content Intent、Guild Voice States权限

核心功能实现逻辑

discord.js v13将语音相关能力完全拆分到@discordjs/voice独立包中,原有v12的voiceChannel.join()等方法已废弃,需按新逻辑实现:

  1. 语音频道加入逻辑
    使用joinVoiceChannel方法创建语音连接,必填参数为当前语音频道ID、服务器ID、服务器内置的语音适配器:
const { joinVoiceChannel } = require('@discordjs/voice');

const connection = joinVoiceChannel({
  channelId: userVoiceChannel.id,
  guildId: userVoiceChannel.guild.id,
  adapterCreator: userVoiceChannel.guild.voiceAdapterCreator,
});
  1. YouTube搜索逻辑
    调用yt-search包获取搜索结果,自动取第一条有效结果:
const yts = require('yt-search');
const searchResult = await yts(用户输入的搜索关键词);
const targetVideo = searchResult.videos[0];
  1. 音频播放逻辑
    创建音频播放器与资源,将播放器订阅到已建立的语音连接中:
const { createAudioPlayer, createAudioResource, NoSubscriberBehavior } = require('@discordjs/voice');
const ytdl = require('ytdl-core');

const player = createAudioPlayer({
  behaviors: {
    noSubscriber: NoSubscriberBehavior.Pause,
  },
});
const resource = createAudioResource(ytdl(targetVideo.url, { filter: 'audioonly' }));
player.play(resource);
connection.subscribe(player);

完整可运行示例

const { Client, Intents } = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, NoSubscriberBehavior } = require('@discordjs/voice');
const yts = require('yt-search');
const ytdl = require('ytdl-core');

const client = new Client({
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.GUILD_VOICE_STATES
  ]
});

const PREFIX = '!play';

client.on('messageCreate', async message => {
  if (!message.content.startsWith(PREFIX) || message.author.bot) return;

  // 校验用户是否在语音频道
  const userVoiceChannel = message.member.voice.channel;
  if (!userVoiceChannel) {
    return message.reply('你需要先加入一个语音频道');
  }

  // 提取搜索关键词
  const searchKeyword = message.content.slice(PREFIX.length).trim();
  if (!searchKeyword) {
    return message.reply('请输入要搜索的音乐关键词');
  }

  try {
    // 加入语音频道
    const connection = joinVoiceChannel({
      channelId: userVoiceChannel.id,
      guildId: userVoiceChannel.guild.id,
      adapterCreator: userVoiceChannel.guild.voiceAdapterCreator,
    });

    // 搜索YouTube资源
    const searchResult = await yts(searchKeyword);
    const targetVideo = searchResult.videos[0];
    if (!targetVideo) {
      return message.reply('未找到对应资源');
    }

    // 初始化播放器并播放
    const player = createAudioPlayer({
      behaviors: { noSubscriber: NoSubscriberBehavior.Pause }
    });
    const resource = createAudioResource(ytdl(targetVideo.url, { filter: 'audioonly', highWaterMark: 1 << 25 }));
    player.play(resource);
    connection.subscribe(player);

    message.reply(`正在播放:${targetVideo.title}`);

    // 播放错误捕获
    player.on('error', error => {
      console.error('播放出错:', error);
      message.reply('播放失败,请稍后重试');
    });
  } catch (err) {
    console.error('运行错误:', err);
    message.reply('操作失败,请稍后重试');
  }
});

client.login('你的机器人Token');

常见问题排查

  • 若出现无法接收消息的问题,确认已在Discord开发者门户开启Message Content Intent权限
  • 若ytdl-core拉取流失败,可执行npm update ytdl-core升级到最新版本修复
  • 若机器人加入语音频道后没有声音,检查机器人在当前服务器是否有说话、连接语音权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:09:03