Search in sources :

Example 11 with VoiceChannel

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

the class MusicPersistenceHandler method reloadPlaylists.

private void reloadPlaylists(JDA jda) {
    File dir = new File("music_persistence");
    if (appConfig.isMusicDistribution()) {
        log.warn("Music persistence loading is disabled on the MUSIC distribution! Use PATRON or DEVELOPMENT instead" + "How did this call end up in here anyways?");
        return;
    }
    log.info("Began reloading playlists for shard {}", jda.getShardInfo().getShardId());
    if (!dir.exists()) {
        log.info("No music persistence directory found.");
        return;
    }
    File[] files = dir.listFiles();
    if (files == null || files.length == 0) {
        log.info("No files present in music persistence directory");
        return;
    }
    for (File file : files) {
        try {
            Guild guild = jda.getGuildById(file.getName());
            if (guild == null) {
                // only load guilds that are part of this shard
                continue;
            }
            JSONObject data = new JSONObject(FileUtils.readFileToString(file, Charset.forName("UTF-8")));
            boolean isPaused = data.getBoolean("isPaused");
            final JSONArray sources = data.getJSONArray("sources");
            @Nullable VoiceChannel vc = jda.getVoiceChannelById(data.getString("vc"));
            @Nullable TextChannel tc = jda.getTextChannelById(data.getString("tc"));
            float volume = Float.parseFloat(data.getString("volume"));
            RepeatMode repeatMode = data.getEnum(RepeatMode.class, "repeatMode");
            boolean shuffle = data.getBoolean("shuffle");
            GuildPlayer player = playerRegistry.getOrCreate(guild);
            if (tc != null) {
                musicTextChannelProvider.setMusicChannel(tc);
            }
            if (appConfig.getDistribution().volumeSupported()) {
                player.setVolume(volume);
            }
            player.setRepeatMode(repeatMode);
            player.setShuffle(shuffle);
            final boolean[] isFirst = { true };
            List<AudioTrackContext> tracks = new ArrayList<>();
            sources.forEach((Object t) -> {
                JSONObject json = (JSONObject) t;
                byte[] message = Base64.decodeBase64(json.getString("message"));
                Member member = guild.getMemberById(json.getLong("user"));
                if (member == null)
                    // member left the guild meanwhile, set ourselves as the one who added the song
                    member = guild.getSelfMember();
                AudioTrack at;
                try {
                    ByteArrayInputStream bais = new ByteArrayInputStream(message);
                    at = audioPlayerManager.decodeTrack(new MessageInput(bais)).decodedTrack;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                if (at == null) {
                    log.error("Loaded track that was null! Skipping...");
                    return;
                }
                // Handle split tracks
                AudioTrackContext atc;
                JSONObject split = json.optJSONObject("split");
                if (split != null) {
                    atc = new SplitAudioTrackContext(jdaEntityProvider, at, member, split.getLong("startPos"), split.getLong("endPos"), split.getString("title"));
                    at.setPosition(split.getLong("startPos"));
                    if (isFirst[0]) {
                        isFirst[0] = false;
                        if (data.has("position")) {
                            at.setPosition(split.getLong("startPos") + data.getLong("position"));
                        }
                    }
                } else {
                    atc = new AudioTrackContext(jdaEntityProvider, at, member);
                    if (isFirst[0]) {
                        isFirst[0] = false;
                        if (data.has("position")) {
                            at.setPosition(data.getLong("position"));
                        }
                    }
                }
                tracks.add(atc);
            });
            player.loadAll(tracks);
            if (!isPaused) {
                if (vc != null) {
                    try {
                        player.joinChannel(vc);
                        player.play();
                    } catch (Exception ignored) {
                    }
                }
                if (tc != null) {
                    CentralMessaging.message(tc, MessageFormat.format(I18n.get(guild).getString("reloadSuccess"), sources.length())).send(null);
                }
            }
        } catch (Exception ex) {
            log.error("Error when loading persistence file", ex);
        }
        boolean deleted = file.delete();
        log.info(deleted ? "Deleted persistence file: " + file : "Failed to delete persistence file: " + file);
    }
}
Also used : ArrayList(java.util.ArrayList) MessageInput(com.sedmelluq.discord.lavaplayer.tools.io.MessageInput) Guild(net.dv8tion.jda.core.entities.Guild) SplitAudioTrackContext(fredboat.audio.queue.SplitAudioTrackContext) TextChannel(net.dv8tion.jda.core.entities.TextChannel) RepeatMode(fredboat.definitions.RepeatMode) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) Member(net.dv8tion.jda.core.entities.Member) JSONArray(org.json.JSONArray) IOException(java.io.IOException) IOException(java.io.IOException) JSONObject(org.json.JSONObject) GuildPlayer(fredboat.audio.player.GuildPlayer) ByteArrayInputStream(java.io.ByteArrayInputStream) AudioTrackContext(fredboat.audio.queue.AudioTrackContext) SplitAudioTrackContext(fredboat.audio.queue.SplitAudioTrackContext) JSONObject(org.json.JSONObject) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) File(java.io.File) Nullable(javax.annotation.Nullable)

Example 12 with VoiceChannel

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

the class JoinCommand method onInvoke.

@Override
public void onInvoke(@Nonnull CommandContext context) {
    GuildPlayer player = Launcher.getBotController().getPlayerRegistry().getOrCreate(context.guild);
    VoiceChannel vc = player.getUserCurrentVoiceChannel(context.invoker);
    try {
        player.joinChannel(vc);
        if (vc != null) {
            context.reply(context.i18nFormat("joinJoining", vc.getName()));
        }
    } catch (IllegalStateException ex) {
        if (vc != null) {
            context.reply(context.i18nFormat("joinErrorAlreadyJoining", vc.getName()));
        } else {
            throw ex;
        }
    }
}
Also used : GuildPlayer(fredboat.audio.player.GuildPlayer) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel)

Example 13 with VoiceChannel

use of net.dv8tion.jda.core.entities.VoiceChannel in project DiscordBot by LXGaming.

the class JoinCommand method execute.

@Override
public void execute(TextChannel textChannel, Member member, Message message, List<String> arguments) {
    EmbedBuilder embedBuilder = new EmbedBuilder();
    embedBuilder.setAuthor(textChannel.getJDA().getSelfUser().getName(), null, textChannel.getJDA().getSelfUser().getEffectiveAvatarUrl());
    embedBuilder.setColor(DiscordUtil.DEFAULT);
    if (arguments == null || arguments.isEmpty()) {
        embedBuilder.setColor(DiscordUtil.ERROR);
        embedBuilder.setTitle("Invalid arguments!", null);
        DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
        return;
    }
    List<VoiceChannel> voiceChannels = member.getGuild().getVoiceChannelsByName(arguments.get(0), false);
    if (voiceChannels.size() < 1) {
        embedBuilder.setColor(DiscordUtil.ERROR);
        embedBuilder.setTitle("Unable to find specified voice channel!", null);
        DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
        return;
    }
    if (member.getGuild().getAudioManager().getConnectedChannel() != null) {
        member.getGuild().getAudioManager().closeAudioConnection();
    }
    try {
        member.getGuild().getAudioManager().openAudioConnection(voiceChannels.get(0));
        embedBuilder.setColor(DiscordUtil.SUCCESS);
        embedBuilder.setTitle("Joined channel '" + voiceChannels.get(0).getName() + "'.", null);
        DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
    } catch (RuntimeException ex) {
        embedBuilder.setColor(DiscordUtil.ERROR);
        embedBuilder.addField("Cannot join channel '" + voiceChannels.get(0).getName() + "'!", ex.getMessage(), false);
        DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
    }
}
Also used : EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel)

Example 14 with VoiceChannel

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

the class VoiceChannelCleanup method cleanupVoiceChannels.

private void cleanupVoiceChannels() {
    closedConnections.set(0);
    logger.info("Checking for guilds with an inactive voice channel");
    final AtomicInteger totalGuilds = new AtomicInteger(0);
    final AtomicInteger totalVcs = new AtomicInteger(0);
    final AtomicInteger killedVcs = new AtomicInteger(0);
    Getters.getGuildCache().forEach(guild -> {
        try {
            totalGuilds.incrementAndGet();
            if (guild != null && guild.getSelfMember() != null && guild.getSelfMember().getVoiceState() != null && guild.getSelfMember().getVoiceState().getChannel() != null) {
                totalVcs.incrementAndGet();
                VoiceChannel vc = guild.getSelfMember().getVoiceState().getChannel();
                if (getHumansInChannel(vc) == 0) {
                    killedVcs.incrementAndGet();
                    cleanup(guild, FlareBot.instance().getMusicManager().getPlayer(guild.getId()), vc.getIdLong());
                } else if (isPlayingMusic(vc)) {
                    VC_LAST_USED.put(vc.getIdLong(), System.currentTimeMillis());
                } else {
                    if (!VC_LAST_USED.containsKey(vc.getIdLong())) {
                        VC_LAST_USED.put(vc.getIdLong(), System.currentTimeMillis());
                        return;
                    }
                    long lastUsed = VC_LAST_USED.get(vc.getIdLong());
                    if (System.currentTimeMillis() - lastUsed >= CLEANUP_THRESHOLD) {
                        killedVcs.incrementAndGet();
                        cleanup(guild, FlareBot.instance().getMusicManager().getPlayer(guild.getId()), vc.getIdLong());
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Failed to check {} for inactive voice connection!", guild.getIdLong(), e);
        }
    });
    logger.info("Checked {} guilds for inactive voice channels.", totalGuilds.get());
    logger.info("Killed {} out of {} voice connections!", killedVcs.get(), totalVcs.get());
    Metrics.voiceChannelsCleanedUp.inc(killedVcs.get());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel)

Example 15 with VoiceChannel

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

the class VoiceChannelCleanup method cleanupPlayers.

private void cleanupPlayers() {
    closedConnections.set(0);
    logger.info("Checking for players which are inactive");
    final AtomicInteger totalPlayers = new AtomicInteger(0);
    final AtomicInteger killedPlayers = new AtomicInteger(0);
    final AtomicInteger songsCleared = new AtomicInteger(0);
    FlareBot.instance().getMusicManager().getPlayers().forEach(player -> {
        try {
            totalPlayers.incrementAndGet();
            long guildId = Long.parseLong(player.getGuildId());
            Guild g = Getters.getGuildById(guildId);
            if (g == null) {
                cleanup(null, player, guildId);
                songsCleared.set(songsCleared.addAndGet(player.getPlaylist().size()));
                killedPlayers.incrementAndGet();
                return;
            }
            if (g.getSelfMember().getVoiceState() == null || g.getSelfMember().getVoiceState().getChannel() == null) {
                if (!VC_LAST_USED.containsKey(guildId)) {
                    VC_LAST_USED.put(guildId, System.currentTimeMillis());
                    return;
                }
                if (System.currentTimeMillis() - VC_LAST_USED.get(guildId) >= CLEANUP_THRESHOLD) {
                    killedPlayers.incrementAndGet();
                    songsCleared.set(songsCleared.addAndGet(player.getPlaylist().size()));
                    cleanup(g, player, guildId);
                    return;
                }
                return;
            }
            VoiceChannel vc = g.getSelfMember().getVoiceState().getChannel();
            if (!isPlayingMusic(vc)) {
                if (!VC_LAST_USED.containsKey(guildId)) {
                    VC_LAST_USED.put(guildId, System.currentTimeMillis());
                    return;
                }
                if (System.currentTimeMillis() - VC_LAST_USED.get(guildId) >= CLEANUP_THRESHOLD) {
                    killedPlayers.incrementAndGet();
                    songsCleared.set(songsCleared.addAndGet(player.getPlaylist().size()));
                    cleanup(g, player, guildId);
                }
            } else {
                VC_LAST_USED.remove(guildId);
            }
        } catch (Exception e) {
            logger.error("Failed to check {} for inactive player!", player.getGuildId(), e);
        }
    });
    logger.info("Checked {} players for inactivity.", totalPlayers.get());
    logger.info("Killed {} out of {} players!", killedPlayers.get(), totalPlayers.get());
    logger.info("Cleaned {} songs from players", songsCleared.get());
    Metrics.playersCleanedUp.inc(killedPlayers.get());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) Guild(net.dv8tion.jda.core.entities.Guild)

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