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

NodeJS v16环境下discord.js调用voiceChannel.join()提示不是函数求助

你遇到的报错是因为discord.js v13及以上版本(适配NodeJS v16+的版本)已经将语音功能完全拆分到独立的@discordjs/voice包,原有voiceChannel.join()方法已废弃,且你未正确安装依赖、导入语法错误才会触发模块不存在的提示。

解决步骤

  • 先安装所需依赖,执行命令:
    npm install @discordjs/voice @discordjs/opus
  • 按照新的语音包语法修改你的play命令代码,修改后完整代码如下:
const ytdl = require("ytdl-core");
const ytSearch = require("yt-search");
// 导入语音包所需方法
const { joinVoiceChannel, createAudioPlayer, createAudioResource, getVoiceConnection } = require('@discordjs/voice');

module.exports = {
    name: 'play',
    description: 'Joins and plays a video from youtube',
    async execute(message, args) {
        const voiceChannel = message.member.voice.channel;
        if (!voiceChannel) return message.channel.send('You need to be in a channel to execute this command');
        const permissions = voiceChannel.permissionsFor(message.client.user);
        if (!permissions.has('CONNECT')) return message.channel.send('You dont have the neccesary permissions');
        if (!permissions.has("SPEAK")) return message.channel.send('You dont have the neccesary permissions');
        if (!args.length) return message.channel.send('Define Video');
        
        // 替换原有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',
                highWaterMark: 1<<25 // 减少加载卡顿
            });
            // 创建播放器和音频资源
            const player = createAudioPlayer();
            const resource = createAudioResource(stream);
            player.play(resource);
            connection.subscribe(player);

            // 监听播放结束事件
            player.on('finish', () => {
                // 销毁连接退出频道
                getVoiceConnection(voiceChannel.guild.id)?.destroy();
            });
            await message.reply(`Now Playing **${video.title}**`)
        } else {
            message.channel.send('No videos found');
        }
    }
}

如果你使用的是discord.js v14及以上版本,权限校验的参数需要替换为枚举值:PermissionsBitField.Flags.Connect、PermissionsBitField.Flags.Speak,提前从discord.js包导入PermissionsBitField即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:24:02