我遵循了一些教程并获得了一些帮助,但无论我尝试什么,它都会显示 playFile
错误。该机器人还可以播放音乐,但音乐(通过链接)部分工作正常。那么,如何仅在有人加入语音 channel 时播放根文件夹中的音频文件呢?
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.");
}
});
最佳答案
附注:您正在使用 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);
关于discord.js - 当有人加入语音 channel 时播放音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53139372/