Search in sources :

Example 26 with VoiceChannel

use of net.dv8tion.jda.core.entities.VoiceChannel in project MantaroBot by Mantaro.

the class AudioCmdUtils method connectToVoiceChannel.

static boolean connectToVoiceChannel(GuildMessageReceivedEvent event) {
    VoiceChannel userChannel = event.getMember().getVoiceState().getChannel();
    if (userChannel == null) {
        event.getChannel().sendMessage("❌ **Please join a voice channel!**").queue();
        return false;
    }
    if (!event.getGuild().getMember(event.getJDA().getSelfUser()).hasPermission(userChannel, Permission.VOICE_CONNECT)) {
        event.getChannel().sendMessage(":heavy_multiplication_x: I cannot connect to this channel due to the lack of permission.").queue();
        return false;
    }
    VoiceChannel guildMusicChannel = null;
    if (MantaroData.db().getGuild(event.getGuild()).getData().getMusicChannel() != null) {
        guildMusicChannel = event.getGuild().getVoiceChannelById(MantaroData.db().getGuild(event.getGuild()).getData().getMusicChannel());
    }
    AudioManager audioManager = event.getGuild().getAudioManager();
    if (guildMusicChannel != null) {
        if (!userChannel.equals(guildMusicChannel)) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "I can only play music on channel **" + guildMusicChannel.getName() + "**!").queue();
            return false;
        }
        if (!audioManager.isConnected() && !audioManager.isAttemptingToConnect()) {
            audioManager.openAudioConnection(userChannel);
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Connected to channel **" + userChannel.getName() + "**!").queue();
        }
        return true;
    }
    if (audioManager.isConnected() && !audioManager.getConnectedChannel().equals(userChannel)) {
        event.getChannel().sendMessage(String.format(EmoteReference.WARNING + "I'm already connected on channel **%s**! (Use the `move` command to move me to another channel)", audioManager.getConnectedChannel().getName())).queue();
        return false;
    }
    if (audioManager.isAttemptingToConnect() && !audioManager.getQueuedAudioConnection().equals(userChannel)) {
        event.getChannel().sendMessage(String.format(EmoteReference.ERROR + "I'm already trying to connect to channel **%s**! (Use the `move` command to move me to another channel)", audioManager.getQueuedAudioConnection().getName())).queue();
        return false;
    }
    if (!audioManager.isConnected() && !audioManager.isAttemptingToConnect()) {
        openAudioConnection(event, audioManager, userChannel);
    }
    return true;
}
Also used : AudioManager(net.dv8tion.jda.core.managers.AudioManager) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel)

Example 27 with VoiceChannel

use of net.dv8tion.jda.core.entities.VoiceChannel in project MantaroBot by Mantaro.

the class VoiceLeave method run.

@Override
public void run() {
    MantaroBot.getInstance().getAudioManager().getMusicManagers().forEach((guildId, manager) -> {
        try {
            Guild guild = MantaroBot.getInstance().getGuildById(guildId);
            if (guild == null)
                return;
            GuildVoiceState voiceState = guild.getSelfMember().getVoiceState();
            if (voiceState == null)
                return;
            if (voiceState.inVoiceChannel()) {
                TextChannel channel = guild.getPublicChannel();
                if (channel != null) {
                    if (channel.canTalk()) {
                        VoiceChannel voiceChannel = voiceState.getChannel();
                        AudioPlayer player = manager.getAudioPlayer();
                        GuildMusicManager mm = MantaroBot.getInstance().getAudioManager().getMusicManager(guild);
                        if (player == null || mm == null || voiceChannel == null)
                            return;
                        if (mm.getTrackScheduler().getCurrentTrack().getRequestedChannel() != null) {
                            channel = mm.getTrackScheduler().getCurrentTrack().getRequestedChannel();
                        }
                        if (voiceState.isGuildMuted()) {
                            channel.sendMessage(EmoteReference.SAD + "Pausing player because I got muted :(").queue();
                            player.setPaused(true);
                        }
                        if (voiceChannel.getMembers().size() == 1) {
                            channel.sendMessage(EmoteReference.THINKING + "I decided to leave **" + voiceChannel.getName() + "** " + "because I was left all " + "alone :<").queue();
                            if (mm.getTrackScheduler().getAudioPlayer().getPlayingTrack() != null) {
                                mm.getTrackScheduler().getAudioPlayer().getPlayingTrack().stop();
                                mm.getTrackScheduler().getQueue().clear();
                                mm.getTrackScheduler().next(true);
                            } else {
                                guild.getAudioManager().closeAudioConnection();
                            }
                        }
                    }
                }
            }
        } catch (Exception ignored) {
        }
    });
}
Also used : TextChannel(net.dv8tion.jda.core.entities.TextChannel) GuildMusicManager(net.kodehawa.mantarobot.commands.music.GuildMusicManager) AudioPlayer(com.sedmelluq.discord.lavaplayer.player.AudioPlayer) GuildVoiceState(net.dv8tion.jda.core.entities.GuildVoiceState) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) Guild(net.dv8tion.jda.core.entities.Guild)

Example 28 with VoiceChannel

use of net.dv8tion.jda.core.entities.VoiceChannel in project FredBoat by Frederikam.

the class MusicPersistenceHandler method persist.

private void persist(int code) {
    File dir = new File("music_persistence");
    if (!dir.exists()) {
        boolean created = dir.mkdir();
        if (!created) {
            log.error("Failed to create music persistence directory");
            return;
        }
    }
    Map<Long, GuildPlayer> reg = playerRegistry.getRegistry();
    boolean isUpdate = code == ExitCodes.EXIT_CODE_UPDATE;
    boolean isRestart = code == ExitCodes.EXIT_CODE_RESTART;
    for (long gId : reg.keySet()) {
        try {
            GuildPlayer player = reg.get(gId);
            String msg;
            if (isUpdate) {
                msg = I18n.get(player.getGuild()).getString("shutdownUpdating");
            } else if (isRestart) {
                msg = I18n.get(player.getGuild()).getString("shutdownRestarting");
            } else {
                msg = I18n.get(player.getGuild()).getString("shutdownIndef");
            }
            TextChannel activeTextChannel = player.getActiveTextChannel();
            List<CompletableFuture> announcements = new ArrayList<>();
            if (activeTextChannel != null && player.isPlaying()) {
                announcements.add(CentralMessaging.message(activeTextChannel, msg).send(null));
            }
            for (Future announcement : announcements) {
                try {
                    // 30 seconds is enough on patron boat
                    announcement.get(30, TimeUnit.SECONDS);
                } catch (Exception ignored) {
                }
            }
            JSONObject data = new JSONObject();
            VoiceChannel vc = player.getCurrentVoiceChannel();
            data.put("vc", vc != null ? vc.getId() : "0");
            data.put("tc", activeTextChannel != null ? activeTextChannel.getId() : "");
            data.put("isPaused", player.isPaused());
            data.put("volume", Float.toString(player.getVolume()));
            data.put("repeatMode", player.getRepeatMode());
            data.put("shuffle", player.isShuffle());
            if (player.getPlayingTrack() != null) {
                data.put("position", player.getPosition());
            }
            ArrayList<JSONObject> identifiers = new ArrayList<>();
            for (AudioTrackContext atc : player.getRemainingTracks()) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                audioPlayerManager.encodeTrack(new MessageOutput(baos), atc.getTrack());
                JSONObject ident = new JSONObject().put("message", Base64.encodeBase64String(baos.toByteArray())).put("user", atc.getUserId());
                if (atc instanceof SplitAudioTrackContext) {
                    JSONObject split = new JSONObject();
                    SplitAudioTrackContext c = (SplitAudioTrackContext) atc;
                    split.put("title", c.getEffectiveTitle()).put("startPos", c.getStartPosition()).put("endPos", c.getStartPosition() + c.getEffectiveDuration());
                    ident.put("split", split);
                }
                identifiers.add(ident);
            }
            data.put("sources", identifiers);
            try {
                FileUtils.writeStringToFile(new File(dir, Long.toString(gId)), data.toString(), Charset.forName("UTF-8"));
            } catch (IOException ex) {
                if (activeTextChannel != null) {
                    CentralMessaging.message(activeTextChannel, MessageFormat.format(I18n.get(player.getGuild()).getString("shutdownPersistenceFail"), ex.getMessage())).send(null);
                }
            }
        } catch (Exception ex) {
            log.error("Error when saving persistence file", ex);
        }
    }
}
Also used : MessageOutput(com.sedmelluq.discord.lavaplayer.tools.io.MessageOutput) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) SplitAudioTrackContext(fredboat.audio.queue.SplitAudioTrackContext) IOException(java.io.IOException) TextChannel(net.dv8tion.jda.core.entities.TextChannel) CompletableFuture(java.util.concurrent.CompletableFuture) JSONObject(org.json.JSONObject) GuildPlayer(fredboat.audio.player.GuildPlayer) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) AudioTrackContext(fredboat.audio.queue.AudioTrackContext) SplitAudioTrackContext(fredboat.audio.queue.SplitAudioTrackContext) File(java.io.File)

Example 29 with VoiceChannel

use of net.dv8tion.jda.core.entities.VoiceChannel in project FredBoat by Frederikam.

the class ShardReviveHandler method onShutdown.

@Override
public void onShutdown(ShutdownEvent event) {
    try {
        List<Long> channels = new ArrayList<>();
        int shardId = event.getJDA().getShardInfo().getShardId();
        playerRegistry.getPlayingPlayers().stream().filter(guildPlayer -> DiscordUtil.getShardId(guildPlayer.getGuildId(), credentials) == shardId).forEach(guildPlayer -> {
            VoiceChannel channel = guildPlayer.getCurrentVoiceChannel();
            if (channel != null)
                channels.add(channel.getIdLong());
        });
        channelsToRejoin.put(shardId, channels);
    } catch (Exception ex) {
        log.error("Caught exception while saving channels to revive shard {}", event.getJDA().getShardInfo(), ex);
    }
}
Also used : PlayerRegistry(fredboat.audio.player.PlayerRegistry) Credentials(fredboat.config.property.Credentials) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) ShutdownEvent(net.dv8tion.jda.core.events.ShutdownEvent) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ListenerAdapter(net.dv8tion.jda.core.hooks.ListenerAdapter) ArrayList(java.util.ArrayList) AudioConnectionFacade(fredboat.audio.player.AudioConnectionFacade) Component(org.springframework.stereotype.Component) List(java.util.List) GuildPlayer(fredboat.audio.player.GuildPlayer) Map(java.util.Map) DiscordUtil(fredboat.util.DiscordUtil) ReadyEvent(net.dv8tion.jda.core.events.ReadyEvent) ArrayList(java.util.ArrayList) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel)

Example 30 with VoiceChannel

use of net.dv8tion.jda.core.entities.VoiceChannel in project FredBoat by Frederikam.

the class ShardReviveHandler method onReady.

@Override
public void onReady(ReadyEvent event) {
    // Rejoin old channels if revived
    List<Long> channels = channelsToRejoin.computeIfAbsent(event.getJDA().getShardInfo().getShardId(), ArrayList::new);
    List<Long> toRejoin = new ArrayList<>(channels);
    // avoid situations where this method is called twice with the same channels
    channels.clear();
    toRejoin.forEach(vcid -> {
        VoiceChannel channel = event.getJDA().getVoiceChannelById(vcid);
        if (channel == null)
            return;
        GuildPlayer player = playerRegistry.getOrCreate(channel.getGuild());
        audioConnectionFacade.openConnection(channel, player);
    });
}
Also used : GuildPlayer(fredboat.audio.player.GuildPlayer) ArrayList(java.util.ArrayList) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel)

Aggregations

VoiceChannel (net.dv8tion.jda.core.entities.VoiceChannel)38 TextChannel (net.dv8tion.jda.core.entities.TextChannel)13 Guild (net.dv8tion.jda.core.entities.Guild)8 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)7 Message (net.dv8tion.jda.core.entities.Message)7 AudioManager (net.dv8tion.jda.core.managers.AudioManager)6 GuildPlayer (fredboat.audio.player.GuildPlayer)5 ArrayList (java.util.ArrayList)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 Collectors (java.util.stream.Collectors)3 Member (net.dv8tion.jda.core.entities.Member)3 Player (com.arsenarsen.lavaplayerbridge.player.Player)2 Track (com.arsenarsen.lavaplayerbridge.player.Track)2 AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)2 AudioTrackContext (fredboat.audio.queue.AudioTrackContext)2 SplitAudioTrackContext (fredboat.audio.queue.SplitAudioTrackContext)2 Consumer (java.util.function.Consumer)2 Nullable (javax.annotation.Nullable)2 User (net.dv8tion.jda.core.entities.User)2 JDAImpl (net.dv8tion.jda.core.entities.impl.JDAImpl)2