Search in sources :

Example 1 with GuildPlayer

use of fredboat.audio.player.GuildPlayer in project FredBoat by Frederikam.

the class AnnounceCommand method onInvoke.

@Override
public void onInvoke(@Nonnull CommandContext context) {
    List<GuildPlayer> players = Launcher.getBotController().getPlayerRegistry().getPlayingPlayers();
    if (players.isEmpty()) {
        context.reply("No currently playing players.");
        return;
    }
    if (!context.hasArguments()) {
        HelpCommand.sendFormattedCommandHelp(context);
        return;
    }
    String msg = HEAD + context.rawArgs;
    context.reply(String.format("[0/%d]", players.size()), // success handler
    status -> new Thread(() -> {
        Phaser phaser = new Phaser(players.size());
        for (GuildPlayer player : players) {
            TextChannel activeTextChannel = player.getActiveTextChannel();
            if (activeTextChannel != null) {
                CentralMessaging.message(activeTextChannel, msg).success(__ -> phaser.arrive()).failure(__ -> phaser.arriveAndDeregister()).send(// this message was not triggered by a user
                null);
            } else {
                phaser.arriveAndDeregister();
            }
        }
        new Thread(() -> {
            try {
                do {
                    try {
                        phaser.awaitAdvanceInterruptibly(0, 5, TimeUnit.SECONDS);
                        // Now all the parties have arrived, we can break out of the loop
                        break;
                    } catch (TimeoutException ex) {
                    // This is fine, this means that the required parties haven't arrived
                    }
                    printProgress(status, phaser.getArrivedParties(), players.size(), players.size() - phaser.getRegisteredParties());
                } while (true);
                printDone(status, // phaser wraps back to 0 on phase increment
                phaser.getRegisteredParties(), players.size() - phaser.getRegisteredParties());
            } catch (InterruptedException ex) {
                // restore interrupt flag
                Thread.currentThread().interrupt();
                log.error("interrupted", ex);
                throw new RuntimeException(ex);
            }
        }).start();
    }).start(), // failure handler
    throwable -> {
        log.error("Announcement failed!", throwable);
        TextUtils.handleException(throwable, context);
        throw new RuntimeException(throwable);
    });
}
Also used : Launcher(fredboat.main.Launcher) CentralMessaging(fredboat.messaging.CentralMessaging) Logger(org.slf4j.Logger) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Command(fredboat.commandmeta.abs.Command) ICommandRestricted(fredboat.commandmeta.abs.ICommandRestricted) LoggerFactory(org.slf4j.LoggerFactory) CommandContext(fredboat.commandmeta.abs.CommandContext) PermissionLevel(fredboat.definitions.PermissionLevel) TimeoutException(java.util.concurrent.TimeoutException) TextUtils(fredboat.util.TextUtils) Message(net.dv8tion.jda.core.entities.Message) MessageFormat(java.text.MessageFormat) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) GuildPlayer(fredboat.audio.player.GuildPlayer) Context(fredboat.messaging.internal.Context) Phaser(java.util.concurrent.Phaser) HelpCommand(fredboat.command.info.HelpCommand) Nonnull(javax.annotation.Nonnull) TextChannel(net.dv8tion.jda.core.entities.TextChannel) GuildPlayer(fredboat.audio.player.GuildPlayer) Phaser(java.util.concurrent.Phaser) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with GuildPlayer

use of fredboat.audio.player.GuildPlayer in project FredBoat by Frederikam.

the class AudioDebugCommand method handleLavaplayer.

private void handleLavaplayer(CommandContext context) {
    String msg = "";
    GuildPlayer guildPlayer = Launcher.getBotController().getPlayerRegistry().getExisting(context.guild);
    if (guildPlayer == null) {
        msg = msg + "No GuildPlayer found.\n";
    } else {
        int deficit = AudioLossCounter.EXPECTED_PACKET_COUNT_PER_MIN - (guildPlayer.getAudioLossCounter().getLastMinuteLoss() + guildPlayer.getAudioLossCounter().getLastMinuteSuccess());
        msg = msg + "Last minute's packet stats:\n" + TextUtils.asCodeBlock("Packets sent:   " + guildPlayer.getAudioLossCounter().getLastMinuteSuccess() + "\n" + "Null packets:   " + guildPlayer.getAudioLossCounter().getLastMinuteLoss() + "\n" + "Packet deficit: " + deficit);
    }
    context.replyWithName(msg);
}
Also used : GuildPlayer(fredboat.audio.player.GuildPlayer)

Example 3 with GuildPlayer

use of fredboat.audio.player.GuildPlayer in project FredBoat by Frederikam.

the class EvalCommand method onInvoke.

@Override
public void onInvoke(@Nonnull CommandContext context) {
    final long started = System.currentTimeMillis();
    String source = context.rawArgs;
    if (context.hasArguments() && (context.args[0].equals("-k") || context.args[0].equals("kill"))) {
        if (this.lastTask != null) {
            if (this.lastTask.isDone() || this.lastTask.isCancelled()) {
                context.reply("Task isn't running.");
            } else {
                this.lastTask.cancel(true);
                context.reply("Task killed.");
            }
        } else {
            context.reply("No task found to kill.");
        }
        return;
    }
    context.sendTyping();
    final int timeOut;
    if (context.args.length > 1 && (context.args[0].equals("-t") || context.args[0].equals("timeout"))) {
        timeOut = Integer.parseInt(context.args[1]);
        source = source.replaceFirst(context.args[0], "");
        source = source.replaceFirst(context.args[1], "");
    } else
        timeOut = -1;
    final String finalSource = source.trim();
    Guild guild = context.guild;
    JDA jda = guild.getJDA();
    engine.put("jda", jda);
    engine.put("api", jda);
    engine.put("channel", context.channel);
    GuildPlayer player = Launcher.getBotController().getPlayerRegistry().getExisting(guild);
    engine.put("vc", player != null ? player.getCurrentVoiceChannel() : null);
    engine.put("author", context.msg.getAuthor());
    engine.put("invoker", context.invoker);
    engine.put("bot", jda.getSelfUser());
    engine.put("member", guild.getSelfMember());
    engine.put("message", context.msg);
    engine.put("guild", guild);
    engine.put("player", player);
    engine.put("pm", Launcher.getBotController().getAudioPlayerManager());
    engine.put("context", context);
    ScheduledExecutorService service = Executors.newScheduledThreadPool(1, r -> new Thread(r, "Eval comm execution"));
    Future<?> future = service.submit(() -> {
        Object out;
        try {
            out = engine.eval("(function() {" + "with (imports) {\n" + finalSource + "\n}" + "})();");
        } catch (Exception ex) {
            context.reply(String.format("`%s`\n\n`%sms`", ex.getMessage(), System.currentTimeMillis() - started));
            log.info("Error occurred in eval", ex);
            return;
        }
        String outputS;
        if (out == null) {
            outputS = ":ok_hand::skin-tone-3:";
        } else if (out.toString().contains("\n")) {
            outputS = "\nEval: " + TextUtils.asCodeBlock(out.toString());
        } else {
            outputS = "\nEval: `" + out.toString() + "`";
        }
        context.reply(String.format("```java\n%s```\n%s\n`%sms`", finalSource, outputS, System.currentTimeMillis() - started));
    });
    this.lastTask = future;
    Thread script = new Thread("Eval comm waiter") {

        @Override
        public void run() {
            try {
                if (timeOut > -1) {
                    future.get(timeOut, TimeUnit.SECONDS);
                }
            } catch (final TimeoutException ex) {
                future.cancel(true);
                context.reply("Task exceeded time limit of " + timeOut + " seconds.");
            } catch (final Exception ex) {
                context.reply(String.format("`%s`\n\n`%sms`", ex.getMessage(), System.currentTimeMillis() - started));
            }
        }
    };
    script.start();
}
Also used : GuildPlayer(fredboat.audio.player.GuildPlayer) JDA(net.dv8tion.jda.core.JDA) Guild(net.dv8tion.jda.core.entities.Guild) ScriptException(javax.script.ScriptException)

Example 4 with GuildPlayer

use of fredboat.audio.player.GuildPlayer in project FredBoat by Frederikam.

the class PlayerDebugCommand method onInvoke.

@Override
public void onInvoke(@Nonnull CommandContext context) {
    JSONArray a = new JSONArray();
    for (GuildPlayer gp : Launcher.getBotController().getPlayerRegistry().getRegistry().values()) {
        JSONObject data = new JSONObject();
        data.put("name", gp.getGuild().getName());
        data.put("id", gp.getGuild().getId());
        data.put("users", gp.getCurrentVoiceChannel().getMembers().toString());
        data.put("isPlaying", gp.isPlaying());
        data.put("isPaused", gp.isPaused());
        data.put("songCount", gp.getTrackCount());
        a.put(data);
    }
    TextUtils.postToPasteService(a.toString()).thenApply(pasteUrl -> pasteUrl.orElse("Failed to upload to any pasteservice.")).thenAccept(context::reply);
}
Also used : Launcher(fredboat.main.Launcher) JSONObject(org.json.JSONObject) GuildPlayer(fredboat.audio.player.GuildPlayer) Context(fredboat.messaging.internal.Context) Command(fredboat.commandmeta.abs.Command) ICommandRestricted(fredboat.commandmeta.abs.ICommandRestricted) CommandContext(fredboat.commandmeta.abs.CommandContext) PermissionLevel(fredboat.definitions.PermissionLevel) TextUtils(fredboat.util.TextUtils) Nonnull(javax.annotation.Nonnull) JSONArray(org.json.JSONArray) JSONObject(org.json.JSONObject) GuildPlayer(fredboat.audio.player.GuildPlayer) JSONArray(org.json.JSONArray)

Example 5 with GuildPlayer

use of fredboat.audio.player.GuildPlayer in project FredBoat by Frederikam.

the class EventListenerBoat method checkForAutoPause.

private void checkForAutoPause(VoiceChannel channelLeft) {
    if (appConfig.getContinuePlayback())
        return;
    Guild guild = channelLeft.getGuild();
    GuildPlayer player = playerRegistry.getExisting(guild);
    if (player == null) {
        return;
    }
    // should take care of destroying stuff
    if (!guild.isMember(guild.getJDA().getSelfUser())) {
        log.warn("onGuildVoiceLeave called for a guild where we aren't a member. This line should only ever be " + "reached if we are getting kicked from that guild while in a voice channel. Investigate if not.");
        return;
    }
    // are we in the channel that someone left from?
    VoiceChannel currentVc = player.getCurrentVoiceChannel();
    if (currentVc != null && currentVc.getIdLong() != channelLeft.getIdLong()) {
        return;
    }
    if (player.getHumanUsersInVC(currentVc).isEmpty() && !player.isPaused()) {
        player.pause();
        TextChannel activeTextChannel = player.getActiveTextChannel();
        if (activeTextChannel != null) {
            CentralMessaging.message(activeTextChannel, I18n.get(guild).getString("eventUsersLeftVC")).send(null);
        }
    }
}
Also used : GuildPlayer(fredboat.audio.player.GuildPlayer)

Aggregations

GuildPlayer (fredboat.audio.player.GuildPlayer)29 AudioTrackContext (fredboat.audio.queue.AudioTrackContext)9 ArrayList (java.util.ArrayList)5 Member (net.dv8tion.jda.core.entities.Member)5 VoiceChannel (net.dv8tion.jda.core.entities.VoiceChannel)5 AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)4 TextChannel (net.dv8tion.jda.core.entities.TextChannel)4 Command (fredboat.commandmeta.abs.Command)3 CommandContext (fredboat.commandmeta.abs.CommandContext)3 Launcher (fredboat.main.Launcher)3 Context (fredboat.messaging.internal.Context)3 TextUtils (fredboat.util.TextUtils)3 Nonnull (javax.annotation.Nonnull)3 Guild (net.dv8tion.jda.core.entities.Guild)3 JSONObject (org.json.JSONObject)3 PlayerRegistry (fredboat.audio.player.PlayerRegistry)2 SplitAudioTrackContext (fredboat.audio.queue.SplitAudioTrackContext)2 MessagingException (fredboat.commandmeta.MessagingException)2 ICommandRestricted (fredboat.commandmeta.abs.ICommandRestricted)2 PermissionLevel (fredboat.definitions.PermissionLevel)2