discord.js - 当有人加入语音 channel 时播放音频文件

标签 discord.js

我遵循了一些教程并获得了一些帮助,但无论我尝试什么,它都会显示 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/

相关文章:

javascript - 如何向具有特定 ID 的 channel 发布公告?

javascript - ( Node :25372) DeprecationWarning: The message event is deprecated. 改用 messageCreate

javascript - Discord.js | guild.iconURL 在嵌入中不起作用

javascript - Discord.js 检查角色是否存在

node.js - 如何通过node.js运行机器人的Kick命令?

javascript - 当定义了几行时,“未定义黑名单”

javascript - 如何提取参数的特定部分并将它们放入自己的变量中

javascript - 如何根据 ID 回复消息

javascript - Discord Bot - 我可以使用 guildMember 创建一个 'personal' 变量吗?

javascript - 如何获取客户姓名并将其放入字符串中?