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

discord.js报错voiceChannel.join is not a function 机器人无法加入语音频道

问题原因

你当前使用的discord.js为v13及以上版本,官方已将语音相关功能从核心库中剥离,移除了原有的voiceChannel.join()、connection.play()、voiceChannel.leave()这类旧API,调用不存在的方法就会抛出该类型错误。

解决步骤
  • 第一步:安装适配新版本的依赖
npm install @discordjs/voice ytdl-core yt-search @discordjs/opus ffmpeg-static
  • 第二步:替换指令代码
    将原p.js的全部逻辑替换为适配新语音API的代码:
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require('@discordjs/voice');
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');

module.exports = {
    name: 'p',
    description: 'Joins + plays stuff'
}

module.exports.execute = async function (message, args){
    const voiceChannel = message.member.voice.channel;
    if(!voiceChannel) return message.channel.send('Not in a vc');
    if(!args.length) return message.channel.send('Invalid Input. Missing second argument.')

    // 新版加入语音频道逻辑
    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 > 0) ? videoResult.videos[0] : null;
    }

    const video = await videoFinder(args.join(' '));

    if(video){
        const stream = ytdl(video.url, {filter: 'audioonly', highWaterMark: 1<<25});
        const audioResource = createAudioResource(stream);
        const audioPlayer = createAudioPlayer();
        
        audioPlayer.play(audioResource);
        connection.subscribe(audioPlayer);

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

        // 播放错误处理
        audioPlayer.on('error', err => {
            console.error('播放出错:', err);
            message.channel.send('音频播放失败');
            connection.destroy();
        });

        await message.reply(`Now Playing *${video.title}*`)
    } else {
        message.channel.send('No results found.');
    }
}
  • 第三步:检查配置与权限

额外提醒:如果使用discord.js v14版本,需要在主文件初始化Client时确认已开启GuildVoiceStates意图,否则无法正常获取语音状态、操作语音频道。同时需要给机器人授予「连接语音频道」「说话」「消息发送」的服务器权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:06:03