Search code examples
javaframeworksbotsdiscord-jda

JDA AudioChannel getManager doesn't always rename created voice-channel


I'm writing "join to create" function for my bot. This code creates new VC and move the member there when the member joins specific channel. The code works but sometimes it doesn't rename new created VC.

import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.channel.concrete.Category;
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel;
import net.dv8tion.jda.api.entities.channel.middleman.AudioChannel;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;

import java.util.List;

public class JoinToCreate extends ListenerAdapter {

    @Override
    public void onGuildVoiceUpdate(GuildVoiceUpdateEvent event) {
        AudioChannel audioChannel = event.getChannelJoined();
        Guild guild = event.getGuild();
        Member member = event.getMember();

        if (audioChannel != null) {
            long channelID = audioChannel.getIdLong();
            if (channelID == BotConfiguration.voiceChannelID) {
                long voiceChannelID = audioChannel.createCopy().complete().getIdLong();
                AudioChannel userVoice = guild.getVoiceChannelById(voiceChannelID);

                userVoice.getManager()
                    .setName("[\uD83E\uDD1D]" + member.getEffectiveName() + "'s Voice").complete();

                guild.moveVoiceMember(member, userVoice).queue();
            }
        } else {
            // REMOVE EMPTY VC
            Category category = event.getGuild().getCategoryById(BotConfiguration.customVCCategory);
            List<VoiceChannel> vcList = category.getVoiceChannels();
            for (int i = 1; i < vcList.size(); i++) {
                if (vcList.get(i).getMembers().size() == 0) {
                    long tempID = vcList.get(i).getIdLong();
                    guild.getVoiceChannelById(tempID).delete().queue();
                }
            }
        }
    }
}

I've tried to use different classes such as VoiceChannel/AudioChannel and I've tried to use another method onGenericGuildVoice.


Solution

  • You should set the name before creating it:

    channel.createCopy().setName("my new name").queue();
    

    You are running into a discord bug, where the update is being overwritten by a different update happening right after.

    Also, you should use the callback channel object:

    channel.createCopy().setName("my new name").queue((newChannel) -> {
      guild.moveVoiceMember(member, newChannel).queue();
    });