diff --git a/src/commands/join.mjs b/src/commands/join.mjs index b4e505e..3131e06 100644 --- a/src/commands/join.mjs +++ b/src/commands/join.mjs @@ -18,6 +18,15 @@ export default { let channel = client.channels.cache.get(guildData.home); if (!channel) return; + + // Get currently connected members + let humanMembers = channel.members.filter(member => !member.user.bot); + + // If no human members are left, destroy the connection + if (humanMembers.size === 0) { + console.log(`Did not join ${channel.name} as it is empty.`); + return; + } try { radio.playRadio(message, radioURL, channel, channel.guild); @@ -51,6 +60,15 @@ export default { if (!channel) return message.channel.send(L._U(guildData.locale, "no_find_voice")); + // Get currently connected members + let humanMembers = channel.members.filter(member => !member.user.bot); + + // If no human members are left, destroy the connection + if (humanMembers.size === 0) { + console.log(`Did not join ${channel.name} as it is empty.`); + return; + } + radioURL = guildData.url; voiceChannel = channel; } else if (args[0][0] === "test") { @@ -76,4 +94,4 @@ export default { message.channel.send(L._U(guildData.locale, "stream_error")); } }, -}; \ No newline at end of file +}; diff --git a/src/index.mjs b/src/index.mjs index 5481e30..ac4eab8 100644 --- a/src/index.mjs +++ b/src/index.mjs @@ -1,5 +1,6 @@ import dotenv from "dotenv"; import Discord from "discord.js"; +import { getVoiceConnection } from '@discordjs/voice'; import fs from "fs"; import * as Utils from "./utils/utils.mjs"; import * as GuildUtils from "./utils/guilds.mjs"; @@ -149,5 +150,27 @@ global.sleep = (ms) => { }); }; +client.on('voiceStateUpdate', (oldState, newState) => { + // Get the current voice connection for the guild + const connection = getVoiceConnection(oldState.guild.id); + if (!connection) return; // The bot is not connected to a voice channel -client.login(process.env.BOT_TOKEN); \ No newline at end of file + // Get the ID of the voice channel the bot is connected to + const botChannelId = connection.joinConfig.channelId; + + // Fetch the voice channel the bot is connected to + const botVoiceChannel = oldState.guild.channels.cache.get(botChannelId); + if (!botVoiceChannel) return; // Voice channel not found + + // Filter out bots from the member list + const humanMembers = botVoiceChannel.members.filter(member => !member.user.bot); + + // If no human members are left, destroy the connection + if (humanMembers.size === 0) { + connection.destroy(); + console.log(`Disconnected from voice channel ${botVoiceChannel.name} as it is now empty.`); + } +}); + + +client.login(process.env.BOT_TOKEN);