Search in sources :

Example 16 with JDAImpl

use of net.dv8tion.jda.internal.JDAImpl in project JDA by DV8FromTheWorld.

the class AudioConnection method prepareReady.

/* Used by AudioWebSocket */
protected void prepareReady() {
    Thread readyThread = new Thread(() -> {
        getJDA().setContext();
        final long timeout = getGuild().getAudioManager().getConnectTimeout();
        final long started = System.currentTimeMillis();
        while (!webSocket.isReady()) {
            if (timeout > 0 && System.currentTimeMillis() - started > timeout)
                break;
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                LOG.error("AudioConnection ready thread got interrupted while sleeping", e);
                Thread.currentThread().interrupt();
            }
        }
        if (webSocket.isReady()) {
            setupSendSystem();
            setupReceiveSystem();
        } else {
            webSocket.close(ConnectionStatus.ERROR_CONNECTION_TIMEOUT);
        }
    });
    readyThread.setUncaughtExceptionHandler((thread, throwable) -> {
        LOG.error("Uncaught exception in Audio ready-thread", throwable);
        JDAImpl api = getJDA();
        api.handleEvent(new ExceptionEvent(api, throwable, true));
    });
    readyThread.setDaemon(true);
    readyThread.setName(threadIdentifier + " Ready Thread");
    readyThread.start();
}
Also used : ExceptionEvent(net.dv8tion.jda.api.events.ExceptionEvent) JDAImpl(net.dv8tion.jda.internal.JDAImpl)

Example 17 with JDAImpl

use of net.dv8tion.jda.internal.JDAImpl in project JDA by DV8FromTheWorld.

the class AudioConnection method setupCombinedExecutor.

private synchronized void setupCombinedExecutor() {
    if (combinedAudioExecutor == null) {
        combinedAudioExecutor = Executors.newSingleThreadScheduledExecutor((task) -> {
            final Thread t = new Thread(task, threadIdentifier + " Combined Thread");
            t.setDaemon(true);
            t.setUncaughtExceptionHandler((thread, throwable) -> {
                LOG.error("I have no idea how, but there was an uncaught exception in the combinedAudioExecutor", throwable);
                JDAImpl api = getJDA();
                api.handleEvent(new ExceptionEvent(api, throwable, true));
            });
            return t;
        });
        combinedAudioExecutor.scheduleAtFixedRate(() -> {
            getJDA().setContext();
            try {
                List<User> users = new LinkedList<>();
                List<short[]> audioParts = new LinkedList<>();
                if (receiveHandler != null && receiveHandler.canReceiveCombined()) {
                    long currentTime = System.currentTimeMillis();
                    for (Map.Entry<User, Queue<AudioData>> entry : combinedQueue.entrySet()) {
                        User user = entry.getKey();
                        Queue<AudioData> queue = entry.getValue();
                        if (queue.isEmpty())
                            continue;
                        AudioData audioData = queue.poll();
                        // Make sure the audio packet is younger than 100ms
                        while (audioData != null && currentTime - audioData.time > queueTimeout) {
                            audioData = queue.poll();
                        }
                        // If none of the audio packets were younger than 100ms, then there is nothing to add.
                        if (audioData == null) {
                            continue;
                        }
                        users.add(user);
                        audioParts.add(audioData.data);
                    }
                    if (!audioParts.isEmpty()) {
                        int audioLength = audioParts.stream().mapToInt(it -> it.length).max().getAsInt();
                        // 960 PCM samples for each channel
                        short[] mix = new short[1920];
                        int sample;
                        for (int i = 0; i < audioLength; i++) {
                            sample = 0;
                            for (Iterator<short[]> iterator = audioParts.iterator(); iterator.hasNext(); ) {
                                short[] audio = iterator.next();
                                if (i < audio.length)
                                    sample += audio[i];
                                else
                                    iterator.remove();
                            }
                            if (sample > Short.MAX_VALUE)
                                mix[i] = Short.MAX_VALUE;
                            else if (sample < Short.MIN_VALUE)
                                mix[i] = Short.MIN_VALUE;
                            else
                                mix[i] = (short) sample;
                        }
                        receiveHandler.handleCombinedAudio(new CombinedAudio(users, mix));
                    } else {
                        // No audio to mix, provide 20 MS of silence. (960 PCM samples for each channel)
                        receiveHandler.handleCombinedAudio(new CombinedAudio(Collections.emptyList(), new short[1920]));
                    }
                }
            } catch (Exception e) {
                LOG.error("There was some unexpected exception in the combinedAudioExecutor!", e);
            }
        }, 0, 20, TimeUnit.MILLISECONDS);
    }
}
Also used : ConnectionStatus(net.dv8tion.jda.api.audio.hooks.ConnectionStatus) TIntObjectHashMap(gnu.trove.map.hash.TIntObjectHashMap) java.util(java.util) TIntObjectMap(gnu.trove.map.TIntObjectMap) IAudioSendSystem(net.dv8tion.jda.api.audio.factory.IAudioSendSystem) IOUtil(net.dv8tion.jda.internal.utils.IOUtil) ShortBuffer(java.nio.ShortBuffer) TIntLongMap(gnu.trove.map.TIntLongMap) ByteBuffer(java.nio.ByteBuffer) User(net.dv8tion.jda.api.entities.User) Opus(tomp2p.opuswrapper.Opus) Guild(net.dv8tion.jda.api.entities.Guild) java.net(java.net) IntBuffer(java.nio.IntBuffer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JDAImpl(net.dv8tion.jda.internal.JDAImpl) Buffer(java.nio.Buffer) DataObject(net.dv8tion.jda.api.utils.data.DataObject) Nonnull(javax.annotation.Nonnull) IAudioSendFactory(net.dv8tion.jda.api.audio.factory.IAudioSendFactory) IPacketProvider(net.dv8tion.jda.api.audio.factory.IPacketProvider) AudioChannel(net.dv8tion.jda.api.entities.AudioChannel) Logger(org.slf4j.Logger) java.util.concurrent(java.util.concurrent) net.dv8tion.jda.api.audio(net.dv8tion.jda.api.audio) ExceptionEvent(net.dv8tion.jda.api.events.ExceptionEvent) PointerByReference(com.sun.jna.ptr.PointerByReference) AudioManagerImpl(net.dv8tion.jda.internal.managers.AudioManagerImpl) WebSocket(com.neovisionaries.ws.client.WebSocket) TweetNaclFast(com.iwebpp.crypto.TweetNaclFast) TIntLongHashMap(gnu.trove.map.hash.TIntLongHashMap) JDALogger(net.dv8tion.jda.internal.utils.JDALogger) ExceptionEvent(net.dv8tion.jda.api.events.ExceptionEvent) User(net.dv8tion.jda.api.entities.User) JDAImpl(net.dv8tion.jda.internal.JDAImpl) TIntObjectHashMap(gnu.trove.map.hash.TIntObjectHashMap) TIntObjectMap(gnu.trove.map.TIntObjectMap) TIntLongMap(gnu.trove.map.TIntLongMap) TIntLongHashMap(gnu.trove.map.hash.TIntLongHashMap)

Example 18 with JDAImpl

use of net.dv8tion.jda.internal.JDAImpl in project SkyBot by DuncteBot.

the class CommandManager method runCustomCommand.

private void runCustomCommand(ICommand cmd, String invoke, List<String> args, GuildMessageReceivedEvent event) {
    final CustomCommand cusomCommand = (CustomCommand) cmd;
    if (cusomCommand.getGuildId() != event.getGuild().getIdLong()) {
        return;
    }
    try {
        MDC.put("command.custom.message", cusomCommand.getMessage());
        final Parser parser = CommandUtils.getParser(new CommandContext(invoke, args, event, variables));
        final String message = parser.parse(cusomCommand.getMessage());
        final MessageConfig.Builder messageBuilder = MessageConfig.Builder.fromEvent(event);
        final DataObject object = parser.get("embed");
        boolean hasContent = false;
        if (!message.isEmpty()) {
            messageBuilder.setMessage("\u200B" + message);
            hasContent = true;
        }
        if (object != null) {
            final JDAImpl jda = (JDAImpl) event.getJDA();
            final EmbedBuilder embed = new EmbedBuilder(jda.getEntityBuilder().createMessageEmbed(object));
            messageBuilder.addEmbed(true, embed);
            hasContent = true;
        }
        if (hasContent) {
            sendMsg(messageBuilder.build());
        }
        parser.clear();
    } catch (Exception e) {
        sendMsg(MessageConfig.Builder.fromEvent(event).setMessage("Error with parsing custom command: " + e.getMessage()).build());
        Sentry.captureException(e);
    }
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) CustomCommand(ml.duncte123.skybot.objects.command.custom.CustomCommand) MessageConfig(me.duncte123.botcommons.messaging.MessageConfig) DataObject(net.dv8tion.jda.api.utils.data.DataObject) CommandContext(ml.duncte123.skybot.objects.command.CommandContext) JDAImpl(net.dv8tion.jda.internal.JDAImpl) Parser(com.jagrosh.jagtag.Parser)

Example 19 with JDAImpl

use of net.dv8tion.jda.internal.JDAImpl in project SkyBot by duncte123.

the class CommandManager method runCustomCommand.

private void runCustomCommand(ICommand cmd, String invoke, List<String> args, GuildMessageReceivedEvent event) {
    final CustomCommand cusomCommand = (CustomCommand) cmd;
    if (cusomCommand.getGuildId() != event.getGuild().getIdLong()) {
        return;
    }
    try {
        MDC.put("command.custom.message", cusomCommand.getMessage());
        final Parser parser = CommandUtils.getParser(new CommandContext(invoke, args, event, variables));
        final String message = parser.parse(cusomCommand.getMessage());
        final MessageConfig.Builder messageBuilder = MessageConfig.Builder.fromEvent(event);
        final DataObject object = parser.get("embed");
        boolean hasContent = false;
        if (!message.isEmpty()) {
            messageBuilder.setMessage("\u200B" + message);
            hasContent = true;
        }
        if (object != null) {
            final JDAImpl jda = (JDAImpl) event.getJDA();
            final EmbedBuilder embed = new EmbedBuilder(jda.getEntityBuilder().createMessageEmbed(object));
            messageBuilder.addEmbed(true, embed);
            hasContent = true;
        }
        if (hasContent) {
            sendMsg(messageBuilder.build());
        }
        parser.clear();
    } catch (Exception e) {
        sendMsg(MessageConfig.Builder.fromEvent(event).setMessage("Error with parsing custom command: " + e.getMessage()).build());
        Sentry.captureException(e);
    }
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) CustomCommand(ml.duncte123.skybot.objects.command.custom.CustomCommand) MessageConfig(me.duncte123.botcommons.messaging.MessageConfig) DataObject(net.dv8tion.jda.api.utils.data.DataObject) CommandContext(ml.duncte123.skybot.objects.command.CommandContext) JDAImpl(net.dv8tion.jda.internal.JDAImpl) Parser(com.jagrosh.jagtag.Parser)

Example 20 with JDAImpl

use of net.dv8tion.jda.internal.JDAImpl in project SkyBot by duncte123.

the class ChangeLogCommand method execute.

@Override
public void execute(@Nonnull CommandContext ctx) {
    if (embedJson == null || embedJson.isEmpty()) {
        fetchLatetstGitHubCommits(ctx);
        return;
    }
    final JDAImpl jda = (JDAImpl) ctx.getJDA();
    final MessageEmbed embed = jda.getEntityBuilder().createMessageEmbed(DataObject.fromJson(embedJson));
    sendEmbed(ctx, new EmbedBuilder(embed));
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) JDAImpl(net.dv8tion.jda.internal.JDAImpl)

Aggregations

JDAImpl (net.dv8tion.jda.internal.JDAImpl)43 Nonnull (javax.annotation.Nonnull)19 Route (net.dv8tion.jda.internal.requests.Route)12 RestActionImpl (net.dv8tion.jda.internal.requests.RestActionImpl)10 DataObject (net.dv8tion.jda.api.utils.data.DataObject)8 DataArray (net.dv8tion.jda.api.utils.data.DataArray)7 EntityBuilder (net.dv8tion.jda.internal.entities.EntityBuilder)6 CheckReturnValue (javax.annotation.CheckReturnValue)5 AuditableRestActionImpl (net.dv8tion.jda.internal.requests.restaction.AuditableRestActionImpl)5 ExceptionEvent (net.dv8tion.jda.api.events.ExceptionEvent)4 InsufficientPermissionException (net.dv8tion.jda.api.exceptions.InsufficientPermissionException)4 ArrayList (java.util.ArrayList)3 LoginException (javax.security.auth.login.LoginException)3 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)3 JDA (net.dv8tion.jda.api.JDA)3 WebSocketClient (net.dv8tion.jda.internal.requests.WebSocketClient)3 Parser (com.jagrosh.jagtag.Parser)2 ByteBuffer (java.nio.ByteBuffer)2 List (java.util.List)2 MessageConfig (me.duncte123.botcommons.messaging.MessageConfig)2