有人加入语音频道时播放音频文件

时间:2018-11-04 09:29:54

标签: discord.js

我遵循了一些教程并获得了一些帮助,但是无论我尝试什么,它始终显示playFile的错误。机器人也可以播放音乐,但音乐(通过链接)部分效果很好。那么,仅当有人加入语音通道时,我才如何播放位于根文件夹中的音频文件?

bot.on('voiceStateUpdate', (oldMember, newMember) => {

// Here I'm storing the IDs of their voice channels, if available
let oldChannel = oldMember.voiceChannel ? oldMember.voiceChannel.id : null;
let newChannel = newMember.voiceChannel ? newMember.voiceChannel.id : null;
if (oldChannel === newChannel) return; // If there has been no change, exit

// Here I'm getting the bot's channel (bot.voiceChannel does not exist)
let botMember = oldMember.guild.member(bot.user),
    botChannel = botMember ? botMember.voiceChannel.id : null;

var server = servers[botMember.guild.id];

// Here I'm getting the channel, just replace VVV this VVV with the channel's ID
let textChannel = oldMember.guild.channels.get('438025505615249408');
if (!textChannel) throw new Error("That channel does not exist.");

// Here I don't need to check if they're the same, since it would've exit before
if (newChannel === botChannel) {
    // console.log("A user joined.");

    server.dispatcher = botMember.voiceConnection.playFile('./audiofile.mp3');

    textChannel.send(newMember.displayName + " joined.");

} else if (oldChannel === botChannel) {
    // console.log("A user left.");
    textChannel.send(newMember.displayName + " left.");
}
});

1 个答案:

答案 0 :(得分:0)

旁注:您正在使用GuildMember.voiceConnection,但该属性不存在。查找GuildMember的文档。

VoiceConnection.playFile()的文档说,file参数必须是绝对路径(例如C:/yourfolder/audio.mp3)。要将相对路径(./audio.mp3)转换为绝对路径,您需要将目录(存储在全局变量__dirname中)和相对路径进行连接:

let conn = bot.voiceConnections.get(newMember.guild.id);
if (!conn) throw new Error("The bot is not in a voiceChannel, fix your code.");

let path = __dirname + '/audiofile.mp3';
conn.playFile(path);

或者,您可以使用path模块(docs)。

let path = require('path').join(__dirname, './audiofile.mp3');
conn.playFile(path);