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

Discord音乐机器人加入VC报错voiceChannel.join is not a function求助

问题1:TypeError: voiceChannel.join is not a function 报错
  • 触发原因:discord.js v13及以上版本已将语音相关能力从核心库拆分至独立的@discordjs/voice包,旧版voiceChannel.join()方法已被废弃移除。
  • 修复步骤:
    1. 先安装所需依赖:
    npm install @discordjs/voice libsodium-wrappers
    
    1. 替换原有语音连接、播放逻辑为新版API写法。
问题2:无法实时识别用户进出语音频道状态
  • 触发原因:discord.js v13+ 采用Intent机制管控事件推送,默认未开启语音状态相关的推送权限,没有对应事件触发就无法同步用户语音状态。
  • 修复步骤:
    1. 初始化Discord客户端时,添加GuildVoiceStates Intent,示例如下:
    const { Client, GatewayIntentBits } = require('discord.js');
    const client = new Client({
      intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.GuildVoiceStates, // 必须添加这行
        GatewayIntentBits.GuildMembers
      ]
    });
    
    1. 如果需要自定义用户进出语音频道的逻辑,可以监听voiceStateUpdate事件实时获取状态变更。
修复后的完整play命令代码
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require('@discordjs/voice');

module.exports = {
  name: 'play',
  description: "plays music in voice chat",
  async execute(message, args, Discord){
    const voiceChannel = message.member.voice.channel;
  
    if (!voiceChannel) return message.channel.send('You need to be in a voice channel to listen to music!');
    const permissions = voiceChannel.permissionsFor(message.client.user);
    if (!permissions.has('CONNECT')) return message.reply("You don't have the correct permissions to request music!");
    if (!permissions.has('SPEAK')) return message.reply("You don't have the correct permissions to request music!");
    if (!args.length) return message.channel.send("You Can't Request for no Music Silly >_<");

    // 替换原有join逻辑
    const connection = joinVoiceChannel({
      channelId: voiceChannel.id,
      guildId: voiceChannel.guild.id,
      adapterCreator: voiceChannel.guild.voiceAdapterCreator,
    });

    const videoFinder = async (query) => {
      const videoResult = await ytSearch(query);
      return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
    }

    const video = await videoFinder(args.join(' '));
    if(video){
      const stream = ytdl(video.url, {filter: 'audioonly'});
      const player = createAudioPlayer();
      const resource = createAudioResource(stream);
      
      player.play(resource);
      connection.subscribe(player);

      // 播放结束自动退出
      player.on(AudioPlayerStatus.Idle, () => {
        connection.destroy();
      });

      await message.reply(`:thumbsup: Now Playing >>>${video.title}<<<`)
    } else {
      message.reply('No Video Results Found :(');
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:15:03