【问题标题】:Play audio file when someone joins voice channel当有人加入语音频道时播放音频文件
【发布时间】:2019-04-07 22:13:25
【问题描述】:

我遵循了一些教程并获得了一些帮助,但无论我尝试什么,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.");
}
});

【问题讨论】:

    标签: discord.js


    【解决方案1】:

    旁注:您使用的是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);
    

    【讨论】:

    • 非常感谢。您昨天也帮助了我,但是当机器人本身离开时,我似乎对机器人有问题。控制台显示 botChannel = botMember 有问题? botMember.voiceChannel.id:空;它指向的。标识部分
    • 让 conn = bot.voiceConnections.get(Message.guild.id);有一个错误提示消息未定义
    • 第一条评论:如果有错误,说明机器人不在任何语音频道。第二条评论:不是Message,是message;变量区分大小写
    • @Waldre 我没有看到它在voiceStateUpdate,我的错。我已经编辑了我的答案
    • 哦,谢谢,现在完美运行。它还有一个问题,当机器人离开语音通道时它停止工作并说它有问题 'botChannel = botMember ? botMember.voiceChannel.id : null;'并指向 .id 部分
    猜你喜欢
    • 2020-09-05
    • 2021-07-13
    • 2019-09-06
    • 2022-01-04
    • 2019-06-18
    • 2020-08-22
    • 2021-03-02
    • 1970-01-01
    • 2019-09-14
    相关资源
    最近更新 更多