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

discord.js v13报错connection.play is not a function解决方案问询

报错根因

你遇到的TypeError: connection.play is not a function报错是因为discord.js v13起语音相关功能完全重构,独立到@discordjs/voice包中,旧版本的connection.play()方法已经被移除,你参考的旧教程代码是针对v12及更早版本编写的,所以存在版本兼容问题。


方案1:适配discord.js v13修复代码

直接修改play.js文件即可,完整修正后的代码如下:

const ytSearch = require("yt-search");
const ytdl = require("ytdl-core");
const { joinVoiceChannel, createAudioPlayer, createAudioResource, StreamType, AudioPlayerStatus } = require("@discordjs/voice");

module.exports = {
  name: "play",
  description: "this is play command",
  async execute(message, args) {
    // 前置校验:判断用户是否在语音频道
    if (!message.member.voice.channel) {
      return message.reply("你需要先加入一个语音频道");
    }

    const connection = joinVoiceChannel({
      channelId: message.member.voice.channel.id,
      guildId: message.guild.id,
      adapterCreator: message.guild.voiceAdapterCreator,
    });

    // 创建音频播放器并绑定到语音连接
    const player = createAudioPlayer();
    const subscription = connection.subscribe(player);

    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" });
      // 生成音频资源
      const resource = createAudioResource(stream, {
        inputType: StreamType.Arbitrary,
      });
      // 播放器播放资源
      player.play(resource);

      // 播放完成后自动退出频道
      player.on(AudioPlayerStatus.Idle, () => {
        subscription.unsubscribe();
        connection.destroy();
      });

      await message.reply(`:thumbsup: 正在播放 ----${video.title}---`);
    } else {
      message.channel.send("未找到对应视频");
    }
  },
};

本次修改主要覆盖以下问题:

  • 补充缺失的ytdl-core导入
  • 新增v13语音体系要求的播放器、音频资源创建逻辑
  • 修复原代码未定义变量voiceChannel、事件名未加引号的语法问题
  • 增加用户不在语音频道的前置校验,避免额外报错

方案2:降级到discord.js v12版本

如果想直接沿用旧教程的全部代码,可以按以下步骤降级:

  1. 先卸载现有不兼容的依赖包:
npm uninstall discord.js @discordjs/voice @discordjs/opus
  1. 安装v12版本的discord.js和语音依赖:
npm install discord.js@12.x opusscript
  1. 修改index.js适配v12版本:
  • 删除Intents相关代码,client初始化改为:
const client = new Discord.Client();
  • 将监听事件名messageCreate改为message

修改完成后旧教程的语音播放代码就可以正常运行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 04:15:03