【问题标题】:Bot plays same audio for joining and leaving the channelBot 在加入和离开频道时播放相同的音频
【发布时间】:2021-06-03 14:08:55
【问题描述】:

我的机器人正在播放相同的音频文件以加入和离开语音频道,我不知道如何解决:

client.on('voiceStateUpdate', (oldMember, newMember) => {
    let newUserChannel = newMember.voiceChannel
    let oldUserChannel = oldMember.voiceChannel
    const voiceChannel = client.channels.cache.get('807305239941480543')
    if(oldUserChannel === undefined && newUserChannel !== undefined && oldMember.member.user.bot === false && newMember.member.user.bot === false) {
        voiceChannel.join().then(connection => { connection.play("./a.mp3").on("finish", () => connection.disconnect())
        }); 
  
    } else if(newUserChannel === undefined && oldMember.member.user.bot === false && newMember.member.user.bot === false){
        voiceChannel.join().then(connection => { connection.play("./b.mp3").on("finish", () => connection.disconnect())
            });
  
    }
  })

我没有收到任何错误并且 Bot 可以正常工作,但 Bot 每次都在播放音频文件 ./b.mp3 而不是音频 ./a.mp3。

谢谢!

【问题讨论】:

    标签: javascript discord discord.js


    【解决方案1】:

    您已经走在正确的轨道上,但您对if 声明的考虑过多。

    首先,当voiceStateUpdate事件被触发时,可用的参数是voiceStates,所以我们将在这段代码中使用oldStatenewState

    当您检查用户是否是机器人时,您的想法是正确的,但您可以在单独的检查中做到这一点。

    if (oldState.member.user.bot) return;
    

    现在我们知道用户正在加入/离开,我们可以区分,但是我们需要检查三种情况:

    1. 用户加入新频道,此处为案例 A
    2. 用户离开频道,此处为案例 B
    3. 用户切换频道,此处为案例 C

    如果oldState.channelIDnullundefined,则表明加入。

    oldState.channelID === null || typeof oldState.channelID == 'undefined'
    

    如果newState.channelIDnullundefined,则表示离开。

    newState.channelID === null || typeof newState.channelID == 'undefined'
    

    如果以上都不符合我们简单地用else 覆盖,则表示切换。

    由于我没有您的 MP3 文件,我只是 console.log() 一个“正在播放 (A/B/C)”,您需要将其切换为您的音频文件。

    整个voiceStateUpdate 看起来像这样:

    client.on('voiceStateUpdate', (oldState, newState) => {
        if (oldState.member.user.bot) return;
        const voiceChannel = client.channels.cache.get('807305239941480543');
    
        if (oldState.channelID === null || typeof oldState.channelID == 'undefined') {
            voiceChannel.join().then(connection => {
                console.log("PLAYING (A)");
                connection.disconnect();
            });
        } else if (newState.channelID === null || typeof newState.channelID == 'undefined') {
            voiceChannel.join().then(connection => {
                console.log("PLAYING (B)");
                connection.disconnect();
            });
        } else {
            voiceChannel.join().then(connection => {
                console.log("PLAYING (C)");
                connection.disconnect();
            });
        }
    })
    

    ;

    【讨论】:

      猜你喜欢
      • 2018-11-19
      • 2020-07-14
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多