【问题标题】:How to reconnect to a VC if the bot gets disconnected?如果机器人断开连接,如何重新连接到 VC?
【发布时间】:2021-04-15 23:12:01
【问题描述】:
client.on("ready", () => {
    console.log(`Logged in as ${client.user.tag}`)
    const voiceChannel = client.channels.cache.get(channel_id)
    voiceChannel.join().then(connection => {
        console.log("Joined voice channel")
        function play(connection) {
            const stream = ytdl(video_urls[Math.floor(Math.random() * video_urls.length)], { filter: "audioonly" })
            const dispatcher = connection.play(stream)
            dispatcher.on("finish", () => {
                play(connection)
            })
        }

        play(connection)
    })
})

这是音乐机器人的基本代码。如果有人断开了语音通道,如何使其重新连接到语音通道? 我见过这样的代码

setInterval(async function() {
  if(!client.voice.connections.get(SERVER)) {
    let channel = client.channels.cache.get(CHANNEL) || await client.channels.fetch(CHANNEL)
    if(!channel) return;

    const connection = await channel.join()
    connection.play(ytdl(LIVE))
  }
}, 20000)

如何在我的实现?

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    您可以使用事件来代替setInterval()。它们的效率要高得多。

    例如你可以使用这个:

    const connection = client.voice.connections.get(SERVER)
    connection.on("disconnect", () => {
      let channel = client.channels.cache.get(CHANNEL) || await client.channels.fetch(CHANNEL)
      const dispatcher = channel.join()
      dispatcher.play(ytdl(LIVE))
    })
    

    如果您有任何其他问题,请随时发表评论!

    编码愉快! :)

    【讨论】:

    • 如何在我的代码中实现这种断开连接?我想不通。
    • 嗨!当你连接到频道时,比如const connection = channel.join(),然后你会输入connection.on("disconnect")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多