Search in sources :

Example 36 with JDAImpl

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

the class MessageReference method resolve.

/**
 * Retrieves the referenced message for this message.
 * <br>If the message already exists, it will be returned immediately.
 *
 * <p>The following {@link net.dv8tion.jda.api.requests.ErrorResponse ErrorResponses} are possible:
 * <ul>
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
 *     <br>The request was attempted after the account lost access to the {@link net.dv8tion.jda.api.entities.Guild Guild}
 *         typically due to being kicked or removed, or after {@link net.dv8tion.jda.api.Permission#VIEW_CHANNEL Permission.VIEW_CHANNEL}
 *         was revoked in the {@link net.dv8tion.jda.api.entities.TextChannel TextChannel}</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
 *     <br>The request was attempted after the account lost {@link net.dv8tion.jda.api.Permission#MESSAGE_HISTORY Permission.MESSAGE_HISTORY}
 *         in the {@link net.dv8tion.jda.api.entities.TextChannel TextChannel}.</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_MESSAGE UNKNOWN_MESSAGE}
 *     <br>The message has already been deleted.</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL}
 *     <br>The request was attempted after the channel was deleted.</li>
 * </ul>
 *
 * @param  update
 *         Whether to update the already stored message
 *
 * @throws net.dv8tion.jda.api.exceptions.InsufficientPermissionException
 *         If this reference refers to a {@link net.dv8tion.jda.api.entities.TextChannel TextChannel} and the logged in account does not have
 *         <ul>
 *             <li>{@link net.dv8tion.jda.api.Permission#VIEW_CHANNEL Permission.VIEW_CHANNEL}</li>
 *             <li>{@link net.dv8tion.jda.api.Permission#MESSAGE_HISTORY Permission.MESSAGE_HISTORY}</li>
 *         </ul>
 *
 * @throws java.lang.IllegalStateException
 *         If this message reference does not have a channel
 *
 * @return {@link net.dv8tion.jda.api.requests.RestAction RestAction} - Type: {@link net.dv8tion.jda.api.entities.Message}
 */
@Nonnull
public RestAction<Message> resolve(boolean update) {
    checkPermission(Permission.VIEW_CHANNEL);
    checkPermission(Permission.MESSAGE_HISTORY);
    if (channel == null)
        throw new IllegalStateException("Cannot resolve a message without a channel present.");
    JDAImpl jda = (JDAImpl) getJDA();
    Message referenced = getMessage();
    if (referenced != null && !update)
        return new CompletedRestAction<>(jda, referenced);
    Route.CompiledRoute route = Route.Messages.GET_MESSAGE.compile(getChannelId(), getMessageId());
    return new RestActionImpl<>(jda, route, (response, request) -> {
        // channel can be null for MessageReferences, but we've already checked for that above, so it is nonnull here
        Message created = jda.getEntityBuilder().createMessageWithChannel(response.getObject(), channel, false);
        this.referencedMessage = created;
        return created;
    });
}
Also used : RestActionImpl(net.dv8tion.jda.internal.requests.RestActionImpl) JDAImpl(net.dv8tion.jda.internal.JDAImpl) Route(net.dv8tion.jda.internal.requests.Route) Nonnull(javax.annotation.Nonnull)

Example 37 with JDAImpl

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

the class Template method resolve.

/**
 * Retrieves a new {@link net.dv8tion.jda.api.entities.templates.Template Template} instance for the given template code.
 *
 * <p>Possible {@link net.dv8tion.jda.api.requests.ErrorResponse ErrorResponses} include:
 * <ul>
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_GUILD_TEMPLATE Unknown Guild Template}
 *     <br>The template doesn't exist.</li>
 * </ul>
 *
 * @param  api
 *         The JDA instance
 * @param  code
 *         A valid template code
 *
 * @throws java.lang.IllegalArgumentException
 *         <ul>
 *             <li>If the provided code is null or empty</li>
 *             <li>If the provided code contains a whitespace</li>
 *             <li>If the provided JDA object is null</li>
 *         </ul>
 *
 * @return {@link net.dv8tion.jda.api.requests.RestAction RestAction} - Type: {@link net.dv8tion.jda.api.entities.templates.Template Template}
 *         <br>The Template object
 */
@Nonnull
public static RestAction<Template> resolve(final JDA api, final String code) {
    Checks.notEmpty(code, "code");
    Checks.noWhitespace(code, "code");
    Checks.notNull(api, "api");
    Route.CompiledRoute route = Route.Templates.GET_TEMPLATE.compile(code);
    JDAImpl jda = (JDAImpl) api;
    return new RestActionImpl<>(api, route, (response, request) -> jda.getEntityBuilder().createTemplate(response.getObject()));
}
Also used : RestActionImpl(net.dv8tion.jda.internal.requests.RestActionImpl) JDAImpl(net.dv8tion.jda.internal.JDAImpl) Route(net.dv8tion.jda.internal.requests.Route) Nonnull(javax.annotation.Nonnull)

Example 38 with JDAImpl

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

the class DefaultShardManager method processQueue.

protected void processQueue() {
    int shardId;
    if (this.shards == null) {
        shardId = 0;
    } else {
        Integer tmp = this.queue.peek();
        shardId = tmp == null ? -1 : tmp;
    }
    if (shardId == -1)
        return;
    JDAImpl api;
    try {
        api = this.shards == null ? null : (JDAImpl) this.shards.getElementById(shardId);
        if (api == null)
            api = this.buildInstance(shardId);
    } catch (CompletionException e) {
        if (e.getCause() instanceof InterruptedException)
            LOG.debug("The worker thread was interrupted");
        else
            LOG.error("Caught an exception in queue processing thread", e);
        return;
    } catch (LoginException e) {
        // this can only happen if the token has been changed
        // in this case the ShardManager will just shutdown itself as there currently is no way of hot-swapping the token on a running JDA instance.
        LOG.warn("The token has been invalidated and the ShardManager will shutdown!", e);
        this.shutdown();
        return;
    } catch (final Exception e) {
        LOG.error("Caught an exception in the queue processing thread", e);
        return;
    }
    try (UnlockHook hook = this.shards.writeLock()) {
        this.shards.getMap().put(shardId, api);
    }
    synchronized (queue) {
        this.queue.remove(shardId);
    }
}
Also used : UnlockHook(net.dv8tion.jda.internal.utils.UnlockHook) LoginException(javax.security.auth.login.LoginException) JDAImpl(net.dv8tion.jda.internal.JDAImpl) LoginException(javax.security.auth.login.LoginException)

Example 39 with JDAImpl

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

the class WebSocketClient method onDispatch.

protected void onDispatch(DataObject raw) {
    String type = raw.getString("t");
    long responseTotal = api.getResponseTotal();
    if (!raw.isType("d", DataType.OBJECT)) {
        // Needs special handling due to content of "d" being an array
        if (type.equals("PRESENCES_REPLACE")) {
            final DataArray payload = raw.getArray("d");
            final List<DataObject> converted = convertPresencesReplace(responseTotal, payload);
            final SocketHandler handler = getHandler("PRESENCE_UPDATE");
            LOG.trace("{} -> {}", type, payload);
            for (DataObject o : converted) {
                handler.handle(responseTotal, o);
                // Send raw event after cache has been updated - including comment
                if (api.isRawEvents())
                    api.handleEvent(new RawGatewayEvent(api, responseTotal, o));
            }
        } else {
            LOG.debug("Received event with unhandled body type JSON: {}", raw);
        }
        return;
    }
    DataObject content = raw.getObject("d");
    LOG.trace("{} -> {}", type, content);
    JDAImpl jda = (JDAImpl) getJDA();
    try {
        switch(type) {
            // INIT types
            case "READY":
                reconnectTimeoutS = 2;
                api.setStatus(JDA.Status.LOADING_SUBSYSTEMS);
                processingReady = true;
                handleIdentifyRateLimit = false;
                // first handle the ready payload before applying the session id
                // this prevents a possible race condition with the cache of the guild setup controller
                // otherwise the audio connection requests that are currently pending might be removed in the process
                handlers.get("READY").handle(responseTotal, raw);
                sessionId = content.getString("session_id");
                break;
            case "RESUMED":
                reconnectTimeoutS = 2;
                sentAuthInfo = true;
                if (!processingReady) {
                    initiating = false;
                    ready();
                } else {
                    LOG.debug("Resumed while still processing initial ready");
                    jda.setStatus(JDA.Status.LOADING_SUBSYSTEMS);
                }
                break;
            default:
                long guildId = content.getLong("guild_id", 0L);
                if (api.isUnavailable(guildId) && !type.equals("GUILD_CREATE") && !type.equals("GUILD_DELETE")) {
                    LOG.debug("Ignoring {} for unavailable guild with id {}. JSON: {}", type, guildId, content);
                    break;
                }
                SocketHandler handler = handlers.get(type);
                if (handler != null)
                    handler.handle(responseTotal, raw);
                else
                    LOG.debug("Unrecognized event:\n{}", raw);
        }
        // Send raw event after cache has been updated
        if (api.isRawEvents())
            api.handleEvent(new RawGatewayEvent(api, responseTotal, raw));
    } catch (ParsingException ex) {
        LOG.warn("Got an unexpected Json-parse error. Please redirect the following message to the devs:\n\tJDA {}\n\t{}\n\t{} -> {}", JDAInfo.VERSION, ex.getMessage(), type, content, ex);
    } catch (Exception ex) {
        LOG.error("Got an unexpected error. Please redirect the following message to the devs:\n\tJDA {}\n\t{} -> {}", JDAInfo.VERSION, type, content, ex);
    }
    if (responseTotal % EventCache.TIMEOUT_AMOUNT == 0)
        jda.getEventCache().timeout(responseTotal);
}
Also used : DataObject(net.dv8tion.jda.api.utils.data.DataObject) ParsingException(net.dv8tion.jda.api.exceptions.ParsingException) JDAImpl(net.dv8tion.jda.internal.JDAImpl) DataArray(net.dv8tion.jda.api.utils.data.DataArray) ParsingException(net.dv8tion.jda.api.exceptions.ParsingException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) DataFormatException(java.util.zip.DataFormatException) IOException(java.io.IOException)

Example 40 with JDAImpl

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

the class DirectAudioControllerImpl method update.

/**
 * Used to update the internal state of the voice request. When a connection
 * was successfully established JDA will stop sending requests for the initial connect.
 * <br>This is done to retry the voice updates in case of a partial service failure.
 *
 * <p>Should be called when:
 * <ol>
 *     <li>Receiving a Voice State Update for the current account and we were previously connected (moved or disconnected)</li>
 *     <li>Receiving a Voice Server Update (initial connect or region change)</li>
 * </ol>
 *
 * Note that the voice state update will always be received prior to a voice server update.
 * <br>The internal dispatch handlers already call this when needed, a library end-user never needs to call this method.
 *
 * @param guild
 *        The guild to update the state for
 * @param channel
 *        The new channel, or null to signal disconnect
 */
public void update(Guild guild, AudioChannel channel) {
    Checks.notNull(guild, "Guild");
    JDAImpl jda = getJDA();
    WebSocketClient client = jda.getClient();
    client.updateAudioConnection(guild.getIdLong(), channel);
}
Also used : JDAImpl(net.dv8tion.jda.internal.JDAImpl) WebSocketClient(net.dv8tion.jda.internal.requests.WebSocketClient)

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