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

如何让Heroku托管的自定义Discord Bot在指定语音频道播放本地MP3

解决Discord Bot本地MP3语音频道播放问题

Got it, let's get your bot playing that funky tune directly in the voice channel instead of just dropping the file in text chat. Here's a step-by-step solution tailored to your needs—no YouTube dependencies, fully integrated into your existing bot, and optimized for Heroku.

1. 先安装必要的依赖

Discord.js本身不处理语音,所以我们需要额外的包来处理音频播放和语音连接。在你的项目根目录运行:

npm install discord.js @discordjs/voice libsodium-wrappers ffmpeg-static
  • @discordjs/voice: 官方语音处理库,负责连接频道和播放音频
  • libsodium-wrappers: 语音连接必需的加密依赖
  • ffmpeg-static: 预编译的FFmpeg,Heroku上可直接使用

2. 核心代码实现

替换你之前的文件发送逻辑,改成下面的语音播放代码,每一步都加了注释:

const { Client, GatewayIntentBits } = require('discord.js');
const { 
  joinVoiceChannel, 
  createAudioPlayer, 
  createAudioResource, 
  AudioPlayerStatus 
} = require('@discordjs/voice');
const path = require('path');

// 初始化Bot,必须包含语音状态Intent,否则无法获取频道信息
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildVoiceStates // 这个一定要加!
  ]
});

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', async (message) => {
  // 匹配你的播放命令
  if (message.content === 'Play the Funky Tune.') {
    // 先检查用户是否在语音频道内
    if (!message.member.voice.channel) {
      return message.reply('你得先加入一个语音频道才能听歌哦!');
    }

    try {
      // 连接到用户当前的语音频道(如果要固定频道,把channelId改成指定频道ID即可)
      const voiceConnection = joinVoiceChannel({
        channelId: message.member.voice.channel.id,
        guildId: message.guild.id,
        adapterCreator: message.guild.voiceAdapterCreator,
      });

      // 创建音频资源,指向本地MP3文件(确保路径正确)
      const audioResource = createAudioResource(
        path.join(__dirname, './Music/FunkyTune.mp3')
      );

      // 创建音频播放器实例
      const audioPlayer = createAudioPlayer();

      // 歌曲播放完毕后,自动断开语音连接
      audioPlayer.on(AudioPlayerStatus.Idle, () => {
        voiceConnection.destroy();
        message.channel.send('歌曲播放完毕啦!🎶');
      });

      // 绑定播放器到语音连接并开始播放
      voiceConnection.subscribe(audioPlayer);
      audioPlayer.play(audioResource);

      message.reply('马上为你播放Funky Tune!准备好摇摆吧!🎵');
    } catch (error) {
      console.error('播放出错:', error);
      message.reply('哎呀,播放音乐时出了点小问题,稍后再试试吧!');
    }
  }
});

// 替换成你的Bot Token
client.login('YOUR_BOT_TOKEN');

3. Heroku部署配置

Heroku默认没有FFmpeg,需要做以下配置:

3.1 添加FFmpeg Buildpack

在Heroku控制台的项目页面,进入Settings → Buildpacks,点击Add buildpack,输入:

https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git

然后点击Save changes。

3.2 确保MP3文件被部署

检查.gitignore文件,不要排除./Music文件夹,否则Heroku部署时不会上传MP3文件。运行git add ./Music/FunkyTune.mp3,提交到git后推送到Heroku。

3.3 检查依赖配置

确保package.json的dependencies包含所有安装的包,且start脚本正确指向Bot入口文件(比如"start": "node index.js")。

4. 权限和额外注意事项

  • Bot权限: 邀请Bot到服务器时,要勾选Connect和Speak权限,否则Bot无法加入语音频道和播放音频。
  • 固定频道播放: 如果不想让Bot跟随用户频道,把message.member.voice.channel.id改成指定语音频道ID即可。
  • 扩展功能: 可以添加暂停/停止命令,或者处理Bot已在其他频道播放的场景。

这样你的Bot就能在指定语音频道持续播放本地MP3,用户切换频道也不会影响播放啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 19:07:58