I'm coding a Discord Bot using JDA and i'm coding some audio stuff. I've already written all necessary classes regarding audio setups and commands. I have a play, join, skip and leave commands that work just fine, but I can't seem to figure out a way to make the bot check if it's already connected to a voice channel in the join method, i.e. when i first use the join command, it joins, but in the second try (even if the bot has already joined) it will say the same thing.
public static void joinVoiceChannel(TextChannel channel, Guild guild) {
GuildVoiceState voiceState = guild.getSelfMember().getVoiceState();
if (!voiceState.inAudioChannel()) {
channel.sendMessage("You must be in a voice channel to use this command.").queue();
return;
}
AudioChannel audioChannel = voiceState.getChannel();
if (audioChannel == null) {
channel.sendMessage("Failed to join voice channel.").queue();
return;
}
net.dv8tion.jda.api.managers.AudioManager audioManager = guild.getAudioManager();
audioManager.openAudioConnection(audioChannel);
channel.sendMessage("Joined voice channel: " + audioChannel.getName()).queue();
}
I've elaborated my thoughts around something like:
if (voiceState.inAudioChannel()) {
channel.sendMessage("I'm already in a voice channel!").queue();
return;
but it just doesn't make any sense, because the boolean will always be true if the user is in the audio channel.
I managed to do it by creating a flag "joined" and a counter.
private static boolean joined;
private static int counter;
public static void joinVoiceChannel(TextChannel channel, GuildVoiceState voiceState, Guild guild) {
if (voiceState.inAudioChannel()) {
net.dv8tion.jda.api.managers.AudioManager audioManager = guild.getAudioManager();
audioManager.openAudioConnection(audioChannel);
channel.sendMessage("Joining voice channel: " + audioChannel.getName()).queue();
joined = true;
counter += 1 ;
}
if (joined & counter == 2) {
channel.sendMessage("I'm already in the voice channel").queue();
counter = 0;
}
}
Basically, when Join command is triggered, the flag turns true and counter receives 1. If triggered again, the counter will become 2, the bot won't join and then reset both the flag and the counter.