Search in sources :

Example 31 with JDAImpl

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

the class MessageChannel method retrievePinnedMessages.

/**
 * Retrieves a List of {@link net.dv8tion.jda.api.entities.Message Messages} that have been pinned in this channel.
 * <br>If no messages have been pinned, this retrieves an empty List.
 *
 * <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#UNKNOWN_CHANNEL UNKNOWN_CHANNEL}
 *     <br>The request was attempted after the channel was deleted.</li>
 * </ul>
 *
 * @throws net.dv8tion.jda.api.exceptions.InsufficientPermissionException
 *         If this is a TextChannel and this account does not have
 *         {@link net.dv8tion.jda.api.Permission#VIEW_CHANNEL Permission.VIEW_CHANNEL}
 *
 * @return {@link net.dv8tion.jda.api.requests.RestAction RestAction} - Type: List{@literal <}{@link net.dv8tion.jda.api.entities.Message}{@literal >}
 *         <br>Retrieves an immutable list of pinned messages
 */
@Nonnull
@CheckReturnValue
default RestAction<List<Message>> retrievePinnedMessages() {
    JDAImpl jda = (JDAImpl) getJDA();
    Route.CompiledRoute route = Route.Messages.GET_PINNED_MESSAGES.compile(getId());
    return new RestActionImpl<>(jda, route, (response, request) -> {
        LinkedList<Message> pinnedMessages = new LinkedList<>();
        EntityBuilder builder = jda.getEntityBuilder();
        DataArray pins = response.getArray();
        for (int i = 0; i < pins.length(); i++) {
            pinnedMessages.add(builder.createMessageWithChannel(pins.getObject(i), MessageChannel.this, false));
        }
        return Collections.unmodifiableList(pinnedMessages);
    });
}
Also used : RestActionImpl(net.dv8tion.jda.internal.requests.RestActionImpl) AuditableRestActionImpl(net.dv8tion.jda.internal.requests.restaction.AuditableRestActionImpl) JDAImpl(net.dv8tion.jda.internal.JDAImpl) EntityBuilder(net.dv8tion.jda.internal.entities.EntityBuilder) Route(net.dv8tion.jda.internal.requests.Route) DataArray(net.dv8tion.jda.api.utils.data.DataArray) CheckReturnValue(javax.annotation.CheckReturnValue) Nonnull(javax.annotation.Nonnull)

Example 32 with JDAImpl

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

the class MessageChannel method retrieveMessageById.

/**
 * Attempts to get a {@link net.dv8tion.jda.api.entities.Message Message} from the Discord's servers that has
 * the same id as the id provided.
 * <br>Note: when retrieving a Message, you must retrieve it from the channel it was sent in!
 *
 * <p>The {@link Message#getMember() Message.getMember()} method will always return null for the resulting message.
 * To retrieve the member you can use {@code getGuild().retrieveMember(message.getAuthor())}.
 *
 * <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 provided {@code id} does not refer to a message sent in this channel or 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  messageId
 *         The id of the sought after Message
 *
 * @throws net.dv8tion.jda.api.exceptions.AccountTypeException
 *         If the currently logged in account is not from {@link net.dv8tion.jda.api.AccountType#BOT AccountType.BOT}
 * @throws IllegalArgumentException
 *         if the provided {@code messageId} is null or empty.
 * @throws net.dv8tion.jda.api.exceptions.InsufficientPermissionException
 *         If this is 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>
 *
 * @return {@link net.dv8tion.jda.api.requests.RestAction RestAction} - Type: Message
 *         <br>The Message defined by the provided id.
 */
@Nonnull
@CheckReturnValue
default RestAction<Message> retrieveMessageById(@Nonnull String messageId) {
    AccountTypeException.check(getJDA().getAccountType(), AccountType.BOT);
    Checks.isSnowflake(messageId, "Message ID");
    JDAImpl jda = (JDAImpl) getJDA();
    Route.CompiledRoute route = Route.Messages.GET_MESSAGE.compile(getId(), messageId);
    return new RestActionImpl<>(jda, route, (response, request) -> jda.getEntityBuilder().createMessageWithChannel(response.getObject(), MessageChannel.this, false));
}
Also used : RestActionImpl(net.dv8tion.jda.internal.requests.RestActionImpl) AuditableRestActionImpl(net.dv8tion.jda.internal.requests.restaction.AuditableRestActionImpl) JDAImpl(net.dv8tion.jda.internal.JDAImpl) Route(net.dv8tion.jda.internal.requests.Route) CheckReturnValue(javax.annotation.CheckReturnValue) Nonnull(javax.annotation.Nonnull)

Example 33 with JDAImpl

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

the class MessageHistory method retrievePast.

/**
 * Retrieves messages from Discord that were sent before the oldest sent message in MessageHistory's history cache
 * ({@link #getRetrievedHistory()}).
 * <br>Can only retrieve a <b>maximum</b> of {@code 100} messages at a time.
 * <br>This method has 2 modes of operation: initial retrieval and additional retrieval.
 * <ul>
 *     <li><b>Initial Retrieval</b>
 *     <br>This mode is what is used when no {@link net.dv8tion.jda.api.entities.Message Messages} have been retrieved
 *         yet ({@link #getRetrievedHistory()}'s size is 0). Initial retrieval starts from the most recent message sent
 *         to the channel and retrieves backwards from there. So, if 50 messages are retrieved during this mode, the
 *         most recent 50 messages will be retrieved.</li>
 *
 *     <li><b>Additional Retrieval</b>
 *     <br>This mode is used once some {@link net.dv8tion.jda.api.entities.Message Messages} have already been retrieved
 *         from Discord and are stored in MessageHistory's history ({@link #getRetrievedHistory()}). When retrieving
 *         messages in this mode, MessageHistory will retrieve previous messages starting from the oldest message
 *         stored in MessageHistory.
 *     <br>E.g: If you initially retrieved 10 messages, the next call to this method to retrieve 10 messages would
 *         retrieve the <i>next</i> 10 messages, starting from the oldest message of the 10 previously retrieved messages.</li>
 * </ul>
 * <p>
 * Possible {@link net.dv8tion.jda.api.requests.ErrorResponse ErrorResponses} include:
 * <ul>
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_MESSAGE UNKNOWN_MESSAGE}
 *     <br>Can occur if retrieving in Additional Mode and the Message being used as the marker for the last retrieved
 *         Message was deleted. Currently, to fix this, you need to create a new
 *         {@link net.dv8tion.jda.api.entities.MessageHistory MessageHistory} instance.</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
 *     <br>Can occur if the request for history retrieval was executed <i>after</i> JDA lost access to the Channel,
 *         typically due to the account being removed from the {@link net.dv8tion.jda.api.entities.Guild Guild}.</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
 *     <br>Can occur if the request for history retrieval was executed <i>after</i> JDA lost the
 *         {@link net.dv8tion.jda.api.Permission#MESSAGE_HISTORY} permission.</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL}
 *     <br>The send request was attempted after the channel was deleted.</li>
 * </ul>
 *
 * @param  amount
 *         The amount of {@link net.dv8tion.jda.api.entities.Message Messages} to retrieve.
 *
 * @throws java.lang.IllegalArgumentException
 *         The the {@code amount} is less than {@code 1} or greater than {@code 100}.
 *
 * @return {@link net.dv8tion.jda.api.requests.RestAction RestAction} -
 *         Type: {@link java.util.List List}{@literal <}{@link net.dv8tion.jda.api.entities.Message Message}{@literal >}
 *         <br>Retrieved Messages are placed in a List and provided in order of most recent to oldest with most recent
 *         starting at index 0. If the list is empty, there were no more messages left to retrieve.
 */
@Nonnull
@CheckReturnValue
public RestAction<List<Message>> retrievePast(int amount) {
    if (amount > 100 || amount < 1)
        throw new IllegalArgumentException("Message retrieval limit is between 1 and 100 messages. No more, no less. Limit provided: " + amount);
    Route.CompiledRoute route = Route.Messages.GET_MESSAGE_HISTORY.compile(channel.getId()).withQueryParams("limit", Integer.toString(amount));
    if (!history.isEmpty())
        route = route.withQueryParams("before", String.valueOf(history.lastKey()));
    JDAImpl jda = (JDAImpl) getJDA();
    return new RestActionImpl<>(jda, route, (response, request) -> {
        EntityBuilder builder = jda.getEntityBuilder();
        LinkedList<Message> messages = new LinkedList<>();
        DataArray historyJson = response.getArray();
        for (int i = 0; i < historyJson.length(); i++) {
            try {
                messages.add(builder.createMessageWithChannel(historyJson.getObject(i), channel, false));
            } catch (Exception e) {
                LOG.warn("Encountered exception when retrieving messages ", e);
            }
        }
        messages.forEach(msg -> history.put(msg.getIdLong(), msg));
        return messages;
    });
}
Also used : RestActionImpl(net.dv8tion.jda.internal.requests.RestActionImpl) JDAImpl(net.dv8tion.jda.internal.JDAImpl) EntityBuilder(net.dv8tion.jda.internal.entities.EntityBuilder) Route(net.dv8tion.jda.internal.requests.Route) DataArray(net.dv8tion.jda.api.utils.data.DataArray) InsufficientPermissionException(net.dv8tion.jda.api.exceptions.InsufficientPermissionException) MissingAccessException(net.dv8tion.jda.api.exceptions.MissingAccessException) CheckReturnValue(javax.annotation.CheckReturnValue) Nonnull(javax.annotation.Nonnull)

Example 34 with JDAImpl

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

the class MessageHistory method retrieveFuture.

/**
 * Retrieves messages from Discord that were sent more recently than the most recently sent message in
 * MessageHistory's history cache ({@link #getRetrievedHistory()}).
 * Use case for this method is for getting more recent messages after jumping to a specific point in history
 * using something like {@link MessageChannel#getHistoryAround(String, int)}.
 * <br>This method works in the same way as {@link #retrievePast(int)}'s Additional Retrieval mode.
 * <p>
 * <b>Note:</b> This method can only be used after {@link net.dv8tion.jda.api.entities.Message Messages} have already
 * been retrieved from Discord.
 * <p>
 * Possible {@link net.dv8tion.jda.api.requests.ErrorResponse ErrorResponses} include:
 * <ul>
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_MESSAGE UNKNOWN_MESSAGE}
 *     <br>Can occur if retrieving in Additional Mode and the Message being used as the marker for the last retrieved
 *         Message was deleted. Currently, to fix this, you need to create a new
 *         {@link net.dv8tion.jda.api.entities.MessageHistory MessageHistory} instance.</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
 *     <br>Can occur if the request for history retrieval was executed <i>after</i> JDA lost access to the Channel,
 *         typically due to the account being removed from the {@link net.dv8tion.jda.api.entities.Guild Guild}.</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
 *     <br>Can occur if the request for history retrieval was executed <i>after</i> JDA lost the
 *         {@link net.dv8tion.jda.api.Permission#MESSAGE_HISTORY} permission.</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL}
 *     <br>The send request was attempted after the channel was deleted.</li>
 * </ul>
 *
 * @param  amount
 *         The amount of {@link net.dv8tion.jda.api.entities.Message Messages} to retrieve.
 *
 * @throws java.lang.IllegalArgumentException
 *         The the {@code amount} is less than {@code 1} or greater than {@code 100}.
 * @throws java.lang.IllegalStateException
 *         If no messages have been retrieved by this MessageHistory.
 *
 * @return {@link net.dv8tion.jda.api.requests.RestAction RestAction} -
 *         Type: {@link java.util.List List}{@literal <}{@link net.dv8tion.jda.api.entities.Message Message}{@literal >}
 *         <br>Retrieved Messages are placed in a List and provided in order of most recent to oldest with most recent
 *         starting at index 0. If the list is empty, there were no more messages left to retrieve.
 */
@Nonnull
@CheckReturnValue
public RestAction<List<Message>> retrieveFuture(int amount) {
    if (amount > 100 || amount < 1)
        throw new IllegalArgumentException("Message retrieval limit is between 1 and 100 messages. No more, no less. Limit provided: " + amount);
    if (history.isEmpty())
        throw new IllegalStateException("No messages have been retrieved yet, so there is no message to act as a marker to retrieve more recent messages based on.");
    Route.CompiledRoute route = Route.Messages.GET_MESSAGE_HISTORY.compile(channel.getId()).withQueryParams("limit", Integer.toString(amount), "after", String.valueOf(history.firstKey()));
    JDAImpl jda = (JDAImpl) getJDA();
    return new RestActionImpl<>(jda, route, (response, request) -> {
        EntityBuilder builder = jda.getEntityBuilder();
        LinkedList<Message> messages = new LinkedList<>();
        DataArray historyJson = response.getArray();
        for (int i = 0; i < historyJson.length(); i++) {
            try {
                messages.add(builder.createMessageWithChannel(historyJson.getObject(i), channel, false));
            } catch (Exception e) {
                LOG.warn("Encountered exception when retrieving messages ", e);
            }
        }
        for (Iterator<Message> it = messages.descendingIterator(); it.hasNext(); ) {
            Message m = it.next();
            history.put(0, m.getIdLong(), m);
        }
        return messages;
    });
}
Also used : JDAImpl(net.dv8tion.jda.internal.JDAImpl) EntityBuilder(net.dv8tion.jda.internal.entities.EntityBuilder) DataArray(net.dv8tion.jda.api.utils.data.DataArray) InsufficientPermissionException(net.dv8tion.jda.api.exceptions.InsufficientPermissionException) MissingAccessException(net.dv8tion.jda.api.exceptions.MissingAccessException) RestActionImpl(net.dv8tion.jda.internal.requests.RestActionImpl) Route(net.dv8tion.jda.internal.requests.Route) CheckReturnValue(javax.annotation.CheckReturnValue) Nonnull(javax.annotation.Nonnull)

Example 35 with JDAImpl

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

the class JDABuilder method build.

/**
 * Builds a new {@link net.dv8tion.jda.api.JDA} instance and uses the provided token to start the login process.
 * <br>The login process runs in a different thread, so while this will return immediately, {@link net.dv8tion.jda.api.JDA} has not
 * finished loading, thus many {@link net.dv8tion.jda.api.JDA} methods have the chance to return incorrect information.
 * For example {@link JDA#getGuilds()} might return an empty list or {@link net.dv8tion.jda.api.JDA#getUserById(long)} might return null
 * for arbitrary user IDs.
 *
 * <p>If you wish to be sure that the {@link net.dv8tion.jda.api.JDA} information is correct, please use
 * {@link net.dv8tion.jda.api.JDA#awaitReady() JDA.awaitReady()} or register an
 * {@link net.dv8tion.jda.api.hooks.EventListener EventListener} to listen for the
 * {@link net.dv8tion.jda.api.events.ReadyEvent ReadyEvent}.
 *
 * @throws LoginException
 *         If the provided token is invalid.
 * @throws IllegalArgumentException
 *         If the provided token is empty or null. Or the provided intents/cache configuration is not possible.
 *
 * @return A {@link net.dv8tion.jda.api.JDA} instance that has started the login process. It is unknown as
 *         to whether or not loading has finished when this returns.
 *
 * @see    net.dv8tion.jda.api.JDA#awaitReady()
 */
@Nonnull
public JDA build() throws LoginException {
    checkIntents();
    OkHttpClient httpClient = this.httpClient;
    if (httpClient == null) {
        if (this.httpClientBuilder == null)
            this.httpClientBuilder = IOUtil.newHttpClientBuilder();
        httpClient = this.httpClientBuilder.build();
    }
    WebSocketFactory wsFactory = this.wsFactory == null ? new WebSocketFactory() : this.wsFactory;
    if (controller == null && shardInfo != null)
        controller = new ConcurrentSessionController();
    AuthorizationConfig authConfig = new AuthorizationConfig(token);
    ThreadingConfig threadingConfig = new ThreadingConfig();
    threadingConfig.setCallbackPool(callbackPool, shutdownCallbackPool);
    threadingConfig.setGatewayPool(mainWsPool, shutdownMainWsPool);
    threadingConfig.setRateLimitPool(rateLimitPool, shutdownRateLimitPool);
    threadingConfig.setEventPool(eventPool, shutdownEventPool);
    threadingConfig.setAudioPool(audioPool, shutdownAudioPool);
    SessionConfig sessionConfig = new SessionConfig(controller, httpClient, wsFactory, voiceDispatchInterceptor, flags, maxReconnectDelay, largeThreshold);
    MetaConfig metaConfig = new MetaConfig(maxBufferSize, contextMap, cacheFlags, flags);
    JDAImpl jda = new JDAImpl(authConfig, sessionConfig, threadingConfig, metaConfig);
    jda.setMemberCachePolicy(memberCachePolicy);
    // We can only do member chunking with the GUILD_MEMBERS intent
    if ((intents & GatewayIntent.GUILD_MEMBERS.getRawValue()) == 0)
        jda.setChunkingFilter(ChunkingFilter.NONE);
    else
        jda.setChunkingFilter(chunkingFilter);
    if (eventManager != null)
        jda.setEventManager(eventManager);
    if (audioSendFactory != null)
        jda.setAudioSendFactory(audioSendFactory);
    listeners.forEach(jda::addEventListener);
    // This is already set by JDA internally, but this is to make sure the listeners catch it.
    jda.setStatus(JDA.Status.INITIALIZED);
    // Set the presence information before connecting to have the correct information ready when sending IDENTIFY
    ((PresenceImpl) jda.getPresence()).setCacheActivity(activity).setCacheIdle(idle).setCacheStatus(status);
    jda.login(shardInfo, compression, true, intents, encoding);
    return jda;
}
Also used : ThreadingConfig(net.dv8tion.jda.internal.utils.config.ThreadingConfig) OkHttpClient(okhttp3.OkHttpClient) PresenceImpl(net.dv8tion.jda.internal.managers.PresenceImpl) AuthorizationConfig(net.dv8tion.jda.internal.utils.config.AuthorizationConfig) MetaConfig(net.dv8tion.jda.internal.utils.config.MetaConfig) WebSocketFactory(com.neovisionaries.ws.client.WebSocketFactory) SessionConfig(net.dv8tion.jda.internal.utils.config.SessionConfig) JDAImpl(net.dv8tion.jda.internal.JDAImpl) Nonnull(javax.annotation.Nonnull)

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