Interface RestAction<T>

  • Type Parameters:
    T - The generic response type for this RestAction
    All Known Subinterfaces:
    AccountManager, AuditableRestAction<T>, AuditLogPaginationAction, CategoryOrderAction, ChannelAction<T>, ChannelManager, ChannelOrderAction, CommandCreateAction, CommandEditAction, CommandListUpdateAction, EmoteManager, GuildAction, GuildManager, InteractionCallbackAction, InviteAction, Manager<M>, MemberAction, MessageAction, MessagePaginationAction, OrderAction<T,​M>, PaginationAction<T,​M>, PermissionOverrideAction, PermOverrideManager, ReactionPaginationAction, ReplyAction, RoleAction, RoleManager, RoleOrderAction, StageInstanceAction, StageInstanceManager, TemplateManager, UpdateInteractionAction, WebhookAction, WebhookManager, WebhookMessageAction<T>, WebhookMessageUpdateAction<T>
    All Known Implementing Classes:
    MessageHistory.MessageRetrieveAction, net.dv8tion.jda.internal.requests.RestActionImpl

    public interface RestAction<T>
    A class representing a terminal between the user and the discord API.
    This is used to offer users the ability to decide how JDA should limit a Request.

    Methods that return an instance of RestAction require an additional step to complete the execution. Thus the user needs to append a follow-up method.

    A default RestAction is issued with the following operations:

    • queue(), queue(Consumer), queue(Consumer, Consumer)
      The fastest and most simplistic way to execute a RestAction is to queue it.
      This method has two optional callback functions, one with the generic type and another with a failure exception.
    • submit(), submit(boolean)
      Provides a Future representing the pending request.
      An optional parameter of type boolean can be passed to disable automated rate limit handling. (not recommended)
    • complete(), complete(boolean)
      Blocking execution building up on submit().
      This will simply block the thread and return the Request result, or throw an exception.
      An optional parameter of type boolean can be passed to disable automated rate limit handling. (not recommended)
    The most efficient way to use a RestAction is by using the asynchronous queue() operations.
    These allow users to provide success and failure callbacks which will be called at a convenient time.

    Planning Execution

    To schedule a RestAction we provide both queue() and complete() versions that will be executed by a ScheduledExecutorService after a specified delay:
    • queueAfter(long, TimeUnit)
      Schedules a call to queue() with default callback Consumers to be executed after the specified delay.
      The TimeUnit is used to convert the provided long into a delay time.
      Example: queueAfter(1, TimeUnit.SECONDS);
      will call queue() 1 second later.
    • submitAfter(long, TimeUnit)
      This returns a ScheduledFuture which can be joined into the current Thread using Future.get()
      The blocking call to submitAfter(delay, unit).get() will return the value processed by a call to complete()
    • completeAfter(long, TimeUnit)
      This operation simply sleeps for the given delay and will call complete() once finished sleeping.

    All of those operations provide overloads for optional parameters such as a custom ScheduledExecutorService instead of using the default global JDA executor. Specifically queueAfter(long, TimeUnit) has overloads to provide a success and/or failure callback due to the returned ScheduledFuture not being able to provide the response values of the queue() callbacks.

    Using RestActions

    The most common way to use a RestAction is not using the returned value.
    For instance sending messages usually means you will not require to view the message once it was sent. Thus we can simply use the asynchronous queue() operation which will be executed on a rate limit worker thread in the background, without blocking your current thread:
    
          MessageChannel channel = event.getChannel();
         RestAction<Message> action = channel.sendMessage("Hello World");
          action.queue(); // Execute the rest action asynchronously
     

    Sometimes it is important to access the response value, possibly to modify it later.
    Now we have two options to actually access the response value, either using an asynchronous callback Consumer or the (not recommended) complete() which will block the current thread until the response has been processed and joins with the current thread.

    Example Queue: (recommended)

    
         MessageChannel channel = event.getChannel();
         final long time = System.currentTimeMillis();
        RestAction<Message> action = channel.sendMessage("Calculating Response Time...");
         Consumer<Message> callback = (message) ->  {
            Message m = message; // ^This is a lambda parameter!^
            m.editMessage("Response Time: " + (System.currentTimeMillis() - time) + "ms").queue();
            // End with queue() to not block the callback thread!
          };
         // You can also inline this with the queue parameter: action.queue(m -> m.editMessage(...).queue());
         action.queue(callback);
     

    Example Complete:

    
         MessageChannel channel = event.getChannel();
         final long time = System.currentTimeMillis();
        RestAction<Message> action = channel.sendMessage("Calculating Response Time...");
         Message message = action.complete();
         message.editMessage("Response Time: " + (System.currentTimeMillis() - time) + "ms").queue();
         // End with queue() to not block the callback thread!
     

    Example Planning:

    
         MessageChannel channel = event.getChannel();
        RestAction<Message> action = channel.sendMessage("This message will destroy itself in 5 seconds!");
         action.queue((message) -> message.delete().queueAfter(5, TimeUnit.SECONDS));
     

    Developer Note: It is generally a good practice to use asynchronous logic because blocking threads requires resources which can be avoided by using callbacks over blocking operations:
    queue(Consumer) > complete()

    There is a dedicated wiki page for RestActions that can be useful for learning.

    Since:
    3.0
    See Also:
    ErrorHandler, ErrorResponseException
    • Method Summary

      All Methods Static Methods Instance Methods Abstract Methods Default Methods 
      Modifier and Type Method Description
      static <E,​A,​O>
      RestAction<O>
      accumulate​(java.util.Collection<? extends RestAction<? extends E>> actions, java.util.stream.Collector<? super E,​A,​? extends O> collector)
      Creates a RestAction instance which accumulates all results of the provided actions.
      default RestAction<T> addCheck​(java.util.function.BooleanSupplier checks)
      Shortcut for setCheck(() -> getCheck().getAsBoolean() && checks.getAsBoolean()).
      static <E> RestAction<java.util.List<E>> allOf​(java.util.Collection<? extends RestAction<? extends E>> actions)
      Creates a RestAction instance which accumulates all results of the provided actions.
      static <E> RestAction<java.util.List<E>> allOf​(RestAction<? extends E> first, RestAction<? extends E>... others)
      Creates a RestAction instance which accumulates all results of the provided actions.
      default <U> RestAction<java.lang.Void> and​(RestAction<U> other)
      Combines this RestAction with the provided action.
      default <U,​O>
      RestAction<O>
      and​(RestAction<U> other, java.util.function.BiFunction<? super T,​? super U,​? extends O> accumulator)
      Combines this RestAction with the provided action.
      default T complete()
      Blocks the current Thread and awaits the completion of an submit() request.
      T complete​(boolean shouldQueue)
      Blocks the current Thread and awaits the completion of an submit() request.
      default T completeAfter​(long delay, java.util.concurrent.TimeUnit unit)
      Blocks the current Thread for the specified delay and calls complete() when delay has been reached.
      default RestAction<T> deadline​(long timestamp)
      Similar to timeout(long, TimeUnit) but schedules a deadline at which the request has to be completed.
      default RestAction<T> delay​(long delay, java.util.concurrent.TimeUnit unit)
      Intermediate operator that returns a modified RestAction.
      default RestAction<T> delay​(long delay, java.util.concurrent.TimeUnit unit, java.util.concurrent.ScheduledExecutorService scheduler)
      Intermediate operator that returns a modified RestAction.
      default RestAction<T> delay​(java.time.Duration duration)
      Intermediate operator that returns a modified RestAction.
      default RestAction<T> delay​(java.time.Duration duration, java.util.concurrent.ScheduledExecutorService scheduler)
      Intermediate operator that returns a modified RestAction.
      default <O> RestAction<O> flatMap​(java.util.function.Function<? super T,​? extends RestAction<O>> flatMap)
      Intermediate operator that returns a modified RestAction.
      default <O> RestAction<O> flatMap​(java.util.function.Predicate<? super T> condition, java.util.function.Function<? super T,​? extends RestAction<O>> flatMap)
      Intermediate operator that returns a modified RestAction.
      default java.util.function.BooleanSupplier getCheck()
      The current checks for this RestAction.
      static java.util.function.Consumer<? super java.lang.Throwable> getDefaultFailure()
      The default failure callback used when none is provided in queue(Consumer, Consumer).
      static java.util.function.Consumer<java.lang.Object> getDefaultSuccess()
      The default success callback used when none is provided in queue(Consumer, Consumer) or queue(Consumer).
      static long getDefaultTimeout()
      The default timeout to apply to every RestAction in milliseconds.
      JDA getJDA()
      The current JDA instance
      static boolean isPassContext()
      Whether RestActions will use ContextException automatically to keep track of the caller context.
      default <O> RestAction<O> map​(java.util.function.Function<? super T,​? extends O> map)
      Intermediate operator that returns a modified RestAction.
      default RestAction<Result<T>> mapToResult()
      Converts the success and failure callbacks into a Result.
      default RestAction<T> onErrorFlatMap​(java.util.function.Function<? super java.lang.Throwable,​? extends RestAction<? extends T>> map)
      Supply a fallback value when the RestAction fails for a any reason.
      default RestAction<T> onErrorFlatMap​(java.util.function.Predicate<? super java.lang.Throwable> condition, java.util.function.Function<? super java.lang.Throwable,​? extends RestAction<? extends T>> map)
      Supply a fallback value when the RestAction fails for a specific reason.
      default RestAction<T> onErrorMap​(java.util.function.Function<? super java.lang.Throwable,​? extends T> map)
      Supply a fallback value when the RestAction fails for any reason.
      default RestAction<T> onErrorMap​(java.util.function.Predicate<? super java.lang.Throwable> condition, java.util.function.Function<? super java.lang.Throwable,​? extends T> map)
      Supply a fallback value when the RestAction fails for a specific reason.
      default void queue()
      Submits a Request for execution.
      default void queue​(java.util.function.Consumer<? super T> success)
      Submits a Request for execution.
      void queue​(java.util.function.Consumer<? super T> success, java.util.function.Consumer<? super java.lang.Throwable> failure)
      Submits a Request for execution.
      default java.util.concurrent.ScheduledFuture<?> queueAfter​(long delay, java.util.concurrent.TimeUnit unit)
      Schedules a call to queue() to be executed after the specified delay.
      default java.util.concurrent.ScheduledFuture<?> queueAfter​(long delay, java.util.concurrent.TimeUnit unit, java.util.concurrent.ScheduledExecutorService executor)
      Schedules a call to queue() to be executed after the specified delay.
      default java.util.concurrent.ScheduledFuture<?> queueAfter​(long delay, java.util.concurrent.TimeUnit unit, java.util.function.Consumer<? super T> success)
      Schedules a call to queue(java.util.function.Consumer) to be executed after the specified delay.
      default java.util.concurrent.ScheduledFuture<?> queueAfter​(long delay, java.util.concurrent.TimeUnit unit, java.util.function.Consumer<? super T> success, java.util.concurrent.ScheduledExecutorService executor)
      Schedules a call to queue(java.util.function.Consumer) to be executed after the specified delay.
      default java.util.concurrent.ScheduledFuture<?> queueAfter​(long delay, java.util.concurrent.TimeUnit unit, java.util.function.Consumer<? super T> success, java.util.function.Consumer<? super java.lang.Throwable> failure)
      Schedules a call to queue(java.util.function.Consumer, java.util.function.Consumer) to be executed after the specified delay.
      default java.util.concurrent.ScheduledFuture<?> queueAfter​(long delay, java.util.concurrent.TimeUnit unit, java.util.function.Consumer<? super T> success, java.util.function.Consumer<? super java.lang.Throwable> failure, java.util.concurrent.ScheduledExecutorService executor)
      Schedules a call to queue(java.util.function.Consumer, java.util.function.Consumer) to be executed after the specified delay.
      RestAction<T> setCheck​(java.util.function.BooleanSupplier checks)
      Sets the last-second checks before finally executing the http request in the queue.
      static void setDefaultFailure​(java.util.function.Consumer<? super java.lang.Throwable> callback)
      The default failure callback used when none is provided in queue(Consumer, Consumer).
      static void setDefaultSuccess​(java.util.function.Consumer<java.lang.Object> callback)
      The default success callback used when none is provided in queue(Consumer, Consumer) or queue(Consumer).
      static void setDefaultTimeout​(long timeout, java.util.concurrent.TimeUnit unit)
      Default timeout to apply to every RestAction.
      static void setPassContext​(boolean enable)
      If enabled this will pass a ContextException as root-cause to all failure consumers.
      default java.util.concurrent.CompletableFuture<T> submit()
      Submits a Request for execution and provides a CompletableFuture representing its completion task.
      java.util.concurrent.CompletableFuture<T> submit​(boolean shouldQueue)
      Submits a Request for execution and provides a CompletableFuture representing its completion task.
      default DelayedCompletableFuture<T> submitAfter​(long delay, java.util.concurrent.TimeUnit unit)
      Schedules a call to queue() to be executed after the specified delay.
      default DelayedCompletableFuture<T> submitAfter​(long delay, java.util.concurrent.TimeUnit unit, java.util.concurrent.ScheduledExecutorService executor)
      Schedules a call to queue() to be executed after the specified delay.
      default RestAction<T> timeout​(long timeout, java.util.concurrent.TimeUnit unit)
      Timeout for this RestAction instance.
      default RestAction<java.util.List<T>> zip​(RestAction<? extends T> first, RestAction<? extends T>... other)
      Accumulates this RestAction with the provided actions into a List.
    • Method Detail

      • setPassContext

        static void setPassContext​(boolean enable)
        If enabled this will pass a ContextException as root-cause to all failure consumers.
        This might cause performance decrease due to the creation of exceptions for every execution.

        It is recommended to pass a context consumer as failure manually using queue(success, ContextException.here(failure))

        Parameters:
        enable - True, if context should be passed to all failure consumers
      • isPassContext

        static boolean isPassContext()
        Whether RestActions will use ContextException automatically to keep track of the caller context.
        If set to true this can cause performance drops due to the creation of stack-traces on execution.
        Returns:
        True, if RestActions will keep track of context automatically
        See Also:
        setPassContext(boolean)
      • setDefaultFailure

        static void setDefaultFailure​(@Nullable
                                      java.util.function.Consumer<? super java.lang.Throwable> callback)
        The default failure callback used when none is provided in queue(Consumer, Consumer).
        Parameters:
        callback - The fallback to use, or null to ignore failures (not recommended)
      • setDefaultSuccess

        static void setDefaultSuccess​(@Nullable
                                      java.util.function.Consumer<java.lang.Object> callback)
        The default success callback used when none is provided in queue(Consumer, Consumer) or queue(Consumer).
        Parameters:
        callback - The fallback to use, or null to ignore success
      • setDefaultTimeout

        static void setDefaultTimeout​(long timeout,
                                      @Nonnull
                                      java.util.concurrent.TimeUnit unit)
        Default timeout to apply to every RestAction.
        This will use no timeout unless specified otherwise.
        If the request doesn't get executed within the specified timeout it will fail.

        When a RestAction times out, it will fail with a TimeoutException.

        Parameters:
        timeout - The default timeout to use
        unit - Unit for the timeout value
        Throws:
        java.lang.IllegalArgumentException - If the provided unit is null
      • getDefaultTimeout

        static long getDefaultTimeout()
        The default timeout to apply to every RestAction in milliseconds.
        If no timeout has been configured, this will return 0.

        When a RestAction times out, it will fail with a TimeoutException.

        Returns:
        The default timeout in milliseconds, or 0
      • getDefaultFailure

        @Nonnull
        static java.util.function.Consumer<? super java.lang.Throwable> getDefaultFailure()
        The default failure callback used when none is provided in queue(Consumer, Consumer).
        Returns:
        The fallback consumer
      • getDefaultSuccess

        @Nonnull
        static java.util.function.Consumer<java.lang.Object> getDefaultSuccess()
        The default success callback used when none is provided in queue(Consumer, Consumer) or queue(Consumer).
        Returns:
        The fallback consumer
      • allOf

        @Nonnull
        @SafeVarargs
        @CheckReturnValue
        static <E> RestAction<java.util.List<E>> allOf​(@Nonnull
                                                       RestAction<? extends E> first,
                                                       @Nonnull
                                                       RestAction<? extends E>... others)
        Creates a RestAction instance which accumulates all results of the provided actions.
        If one action fails, all others will be cancelled. To handle failures individually instead of cancelling you can use mapToResult().
        Type Parameters:
        E - The result type
        Parameters:
        first - The initial RestAction starting point
        others - The remaining actions to accumulate
        Returns:
        RestAction - Type: List of the results
        Throws:
        java.lang.IllegalArgumentException - If null is provided
        Since:
        4.2.1
        See Also:
        and(RestAction, BiFunction), zip(RestAction, RestAction[])
      • allOf

        @Nonnull
        @CheckReturnValue
        static <E> RestAction<java.util.List<E>> allOf​(@Nonnull
                                                       java.util.Collection<? extends RestAction<? extends E>> actions)
        Creates a RestAction instance which accumulates all results of the provided actions.
        If one action fails, all others will be cancelled. To handle failures individually instead of cancelling you can use mapToResult().
        Type Parameters:
        E - The result type
        Parameters:
        actions - Non-empty collection of RestActions to accumulate
        Returns:
        RestAction - Type: List of the results
        Throws:
        java.lang.IllegalArgumentException - If null is provided or the collection is empty
        Since:
        4.2.1
        See Also:
        and(RestAction, BiFunction), zip(RestAction, RestAction[])
      • accumulate

        @Nonnull
        @CheckReturnValue
        static <E,​A,​O> RestAction<O> accumulate​(@Nonnull
                                                            java.util.Collection<? extends RestAction<? extends E>> actions,
                                                            @Nonnull
                                                            java.util.stream.Collector<? super E,​A,​? extends O> collector)
        Creates a RestAction instance which accumulates all results of the provided actions.
        If one action fails, all others will be cancelled. To handle failures individually instead of cancelling you can use mapToResult().
        Type Parameters:
        E - The input type
        A - The accumulator type
        O - The output type
        Parameters:
        actions - Non-empty collection of RestActions to accumulate
        collector - The Collector to use
        Returns:
        RestAction - Type: List of the results
        Throws:
        java.lang.IllegalArgumentException - If null is provided or the collection is empty
        Since:
        4.2.1
        See Also:
        and(RestAction, BiFunction), zip(RestAction, RestAction[])
      • getJDA

        @Nonnull
        JDA getJDA()
        The current JDA instance
        Returns:
        The corresponding JDA instance
      • setCheck

        @Nonnull
        RestAction<T> setCheck​(@Nullable
                               java.util.function.BooleanSupplier checks)
        Sets the last-second checks before finally executing the http request in the queue.
        If the provided supplier evaluates to false or throws an exception this will not be finished. When an exception is thrown from the supplier it will be provided to the failure callback.
        Parameters:
        checks - The checks to run before executing the request, or null to run no checks
        Returns:
        The current RestAction for chaining convenience
        See Also:
        getCheck(), addCheck(BooleanSupplier)
      • getCheck

        @Nullable
        default java.util.function.BooleanSupplier getCheck()
        The current checks for this RestAction.
        Returns:
        The current checks, or null if none were set
        Since:
        4.2.1
        See Also:
        setCheck(BooleanSupplier)
      • addCheck

        @Nonnull
        @CheckReturnValue
        default RestAction<T> addCheck​(@Nonnull
                                       java.util.function.BooleanSupplier checks)
        Shortcut for setCheck(() -> getCheck().getAsBoolean() && checks.getAsBoolean()).
        Parameters:
        checks - Other checks to run
        Returns:
        The current RestAction for chaining convenience
        Throws:
        java.lang.IllegalArgumentException - If the provided checks are null
        Since:
        4.2.1
        See Also:
        setCheck(BooleanSupplier)
      • timeout

        @Nonnull
        default RestAction<T> timeout​(long timeout,
                                      @Nonnull
                                      java.util.concurrent.TimeUnit unit)
        Timeout for this RestAction instance.
        If the request doesn't get executed within the timeout it will fail.

        When a RestAction times out, it will fail with a TimeoutException. This is the same as deadline(System.currentTimeMillis() + unit.toMillis(timeout)).

        Example

        
         action.timeout(10, TimeUnit.SECONDS) // 10 seconds from now
               .queueAfter(20, SECONDS); // request will not be executed within deadline and timeout immediately after 20 seconds
         
        Parameters:
        timeout - The timeout to use
        unit - Unit for the timeout value
        Returns:
        The same RestAction instance with the applied timeout
        Throws:
        java.lang.IllegalArgumentException - If the provided unit is null
        See Also:
        setDefaultTimeout(long, TimeUnit)
      • deadline

        @Nonnull
        default RestAction<T> deadline​(long timestamp)
        Similar to timeout(long, TimeUnit) but schedules a deadline at which the request has to be completed.
        If the deadline is reached, the request will fail with a TimeoutException.

        This does not mean that the request will immediately timeout when the deadline is reached. JDA will check the deadline right before executing the request or within intervals in a worker thread. This only means the request will timeout if the deadline has passed.

        Example

        
         action.deadline(System.currentTimeMillis() + 10000) // 10 seconds from now
               .queueAfter(20, SECONDS); // request will not be executed within deadline and timeout immediately after 20 seconds
         
        Parameters:
        timestamp - Millisecond timestamp at which the request will timeout
        Returns:
        The same RestAction with the applied deadline
        See Also:
        timeout(long, TimeUnit), setDefaultTimeout(long, TimeUnit)
      • queue

        default void queue​(@Nullable
                           java.util.function.Consumer<? super T> success)
        Submits a Request for execution.
        Using the default failure callback function.

        To handle failures use queue(java.util.function.Consumer, java.util.function.Consumer).

        This method is asynchronous

        Example

        
         public static void sendPrivateMessage(User user, String content)
         {
             // The "<PrivateChannel>" is the response type for the parameter in the success callback
             RestAction<PrivateChannel> action = user.openPrivateChannel();
             // "channel" is the identifier we use to access the channel of the response
             // this is like the "user" we declared above, just a name for the function parameter
             action.queue((channel) -> channel.sendMessage(content).queue());
         }
         
        Parameters:
        success - The success callback that will be called at a convenient time for the API. (can be null)
        Throws:
        java.util.concurrent.RejectedExecutionException - If the requester has been shutdown by JDA.shutdown() or JDA.shutdownNow()
        See Also:
        queue(Consumer, Consumer)
      • queue

        void queue​(@Nullable
                   java.util.function.Consumer<? super T> success,
                   @Nullable
                   java.util.function.Consumer<? super java.lang.Throwable> failure)
        Submits a Request for execution.

        This method is asynchronous

        Example

        
         public static void sendPrivateMessage(JDA jda, String userId, String content)
         {
             // Retrieve the user by their id
             RestAction<User> action = jda.retrieveUserById(userId);
             action.queue(
                 // Handle success if the user exists
                 (user) -> user.openPrivateChannel().queue(
                     (channel) -> channel.sendMessage(content).queue()),
        
                 // Handle failure if the user does not exist (or another issue appeared)
                 (error) -> error.printStackTrace()
             );
        
             // Alternatively use submit() to remove nested callbacks
         }
         
        Parameters:
        success - The success callback that will be called at a convenient time for the API. (can be null to use default)
        failure - The failure callback that will be called if the Request encounters an exception at its execution point. (can be null to use default)
        Throws:
        java.util.concurrent.RejectedExecutionException - If the requester has been shutdown by JDA.shutdown() or JDA.shutdownNow()
        See Also:
        submit(), ErrorHandler
      • complete

        default T complete()
        Blocks the current Thread and awaits the completion of an submit() request.
        Used for synchronous logic.

        This might throw RuntimeExceptions

        Returns:
        The response value
        Throws:
        java.util.concurrent.RejectedExecutionException - If the requester has been shutdown by JDA.shutdown() or JDA.shutdownNow()
        java.lang.IllegalStateException - If used within a queue(...) callback
      • complete

        T complete​(boolean shouldQueue)
            throws RateLimitedException
        Blocks the current Thread and awaits the completion of an submit() request.
        Used for synchronous logic.
        Parameters:
        shouldQueue - Whether this should automatically handle rate limitations (default true)
        Returns:
        The response value
        Throws:
        java.util.concurrent.RejectedExecutionException - If the requester has been shutdown by JDA.shutdown() or JDA.shutdownNow()
        java.lang.IllegalStateException - If used within a queue(...) callback
        RateLimitedException - If we were rate limited and the shouldQueue is false. Use complete() to avoid this Exception.
      • submit

        @Nonnull
        default java.util.concurrent.CompletableFuture<T> submit()
        Submits a Request for execution and provides a CompletableFuture representing its completion task.
        Cancelling the returned Future will result in the cancellation of the Request!

        Example

        
         public static void sendPrivateMessage(JDA jda, String userId, String content)
         {
             // Retrieve the user by their id
             RestAction<User> action = jda.retrieveUserById(userId);
             action.submit() // CompletableFuture<User>
                   // Handle success if the user exists
                   .thenCompose((user) -> user.openPrivateChannel().submit()) // CompletableFuture<PrivateChannel>
                   .thenCompose((channel) -> channel.sendMessage(content).submit()) // CompletableFuture<Void>
                   .whenComplete((v, error) -> {
                       // Handle failure if the user does not exist (or another issue appeared)
                       if (error != null) error.printStackTrace();
                   });
         }
         
        Returns:
        Never-null CompletableFuture representing the completion promise
        Throws:
        java.util.concurrent.RejectedExecutionException - If the requester has been shutdown by JDA.shutdown() or JDA.shutdownNow()
      • submit

        @Nonnull
        java.util.concurrent.CompletableFuture<T> submit​(boolean shouldQueue)
        Submits a Request for execution and provides a CompletableFuture representing its completion task.
        Cancelling the returned Future will result in the cancellation of the Request!
        Parameters:
        shouldQueue - Whether the Request should automatically handle rate limitations. (default true)
        Returns:
        Never-null CompletableFuture task representing the completion promise
        Throws:
        java.util.concurrent.RejectedExecutionException - If the requester has been shutdown by JDA.shutdown() or JDA.shutdownNow()
      • map

        @Nonnull
        @CheckReturnValue
        default <O> RestAction<O> map​(@Nonnull
                                      java.util.function.Function<? super T,​? extends O> map)
        Intermediate operator that returns a modified RestAction.

        This does not modify this instance but returns a new RestAction which will apply the map function on successful execution.

        Example

        
         public RestAction<String> retrieveMemberNickname(Guild guild, String userId) {
             return guild.retrieveMemberById(userId)
                         .map(Member::getNickname);
         }
         
        Type Parameters:
        O - The target output type
        Parameters:
        map - The mapping function to apply to the action result
        Returns:
        RestAction for the mapped type
        Since:
        4.1.1
      • onErrorMap

        @Nonnull
        @CheckReturnValue
        default RestAction<T> onErrorMap​(@Nonnull
                                         java.util.function.Function<? super java.lang.Throwable,​? extends T> map)
        Supply a fallback value when the RestAction fails for any reason.

        This does not modify this instance but returns a new RestAction which will apply the map function on failed execution.

        Example

        
         public RestAction<String> sendMessage(User user, String content) {
             return user.openPrivateChannel() // RestAction<PrivateChannel>
                 .flatMap((channel) -> channel.sendMessage(content)) // RestAction<Message>
                 .map(Message::getContentRaw) // RestAction<String>
                 .onErrorMap(Throwable::getMessage); // RestAction<String> (must be the same as above)
         }
         
        Parameters:
        map - The mapping function which provides the fallback value to use
        Returns:
        RestAction with fallback handling
        Throws:
        java.lang.IllegalArgumentException - If the mapping function is null
        Since:
        4.2.0
      • onErrorMap

        @Nonnull
        @CheckReturnValue
        default RestAction<T> onErrorMap​(@Nullable
                                         java.util.function.Predicate<? super java.lang.Throwable> condition,
                                         @Nonnull
                                         java.util.function.Function<? super java.lang.Throwable,​? extends T> map)
        Supply a fallback value when the RestAction fails for a specific reason.

        This does not modify this instance but returns a new RestAction which will apply the map function on failed execution.

        Example

        
         public RestAction<String> sendMessage(User user, String content) {
             return user.openPrivateChannel() // RestAction<PrivateChannel>
                 .flatMap((channel) -> channel.sendMessage(content)) // RestAction<Message>
                 .map(Message::getContentRaw) // RestAction<String>
                 .onErrorMap(CANNOT_SEND_TO_USER::test, Throwable::getMessage); // RestAction<String> (must be the same as above)
         }
         
        Parameters:
        condition - A condition that must return true to apply this fallback
        map - The mapping function which provides the fallback value to use
        Returns:
        RestAction with fallback handling
        Throws:
        java.lang.IllegalArgumentException - If the mapping function is null
        Since:
        4.2.0
        See Also:
        ErrorResponse.test(Throwable), ErrorResponse.test(ErrorResponse...)
      • onErrorFlatMap

        @Nonnull
        @CheckReturnValue
        default RestAction<T> onErrorFlatMap​(@Nonnull
                                             java.util.function.Function<? super java.lang.Throwable,​? extends RestAction<? extends T>> map)
        Supply a fallback value when the RestAction fails for a any reason.

        This does not modify this instance but returns a new RestAction which will apply the map function on failed execution.

        Example

        
         public RestAction<Message> sendMessage(User user, TextChannel context, String content) {
             return user.openPrivateChannel() // RestAction<PrivateChannel>
                 .flatMap((channel) -> channel.sendMessage(content)) // RestAction<Message>
                 .onErrorFlatMap(
                     (error) -> context.sendMessage("Failed to send direct message to " + user.getAsMention() + " Reason: " + error)
                 ); // RestAction<Message> (must be the same as above)
         }
         
        Parameters:
        map - The mapping function which provides the fallback action to use
        Returns:
        RestAction with fallback handling
        Throws:
        java.lang.IllegalArgumentException - If the mapping function is null
        Since:
        4.2.0
      • onErrorFlatMap

        @Nonnull
        @CheckReturnValue
        default RestAction<T> onErrorFlatMap​(@Nullable
                                             java.util.function.Predicate<? super java.lang.Throwable> condition,
                                             @Nonnull
                                             java.util.function.Function<? super java.lang.Throwable,​? extends RestAction<? extends T>> map)
        Supply a fallback value when the RestAction fails for a specific reason.

        This does not modify this instance but returns a new RestAction which will apply the map function on failed execution.

        Example

        
         public RestAction<Message> sendMessage(User user, TextChannel context, String content) {
             return user.openPrivateChannel() // RestAction<PrivateChannel>
                 .flatMap((channel) -> channel.sendMessage(content)) // RestAction<Message>
                 .onErrorFlatMap(CANNOT_SEND_TO_USER::test,
                     (error) -> context.sendMessage("Cannot send direct message to " + user.getAsMention())
                 ); // RestAction<Message> (must be the same as above)
         }
         
        Parameters:
        condition - A condition that must return true to apply this fallback
        map - The mapping function which provides the fallback action to use
        Returns:
        RestAction with fallback handling
        Throws:
        java.lang.IllegalArgumentException - If the mapping function is null
        Since:
        4.2.0
        See Also:
        ErrorResponse.test(Throwable), ErrorResponse.test(ErrorResponse...)
      • flatMap

        @Nonnull
        @CheckReturnValue
        default <O> RestAction<O> flatMap​(@Nonnull
                                          java.util.function.Function<? super T,​? extends RestAction<O>> flatMap)
        Intermediate operator that returns a modified RestAction.

        This does not modify this instance but returns a new RestAction which will apply the map function on successful execution. This will compute the result of both RestActions.
        The returned RestAction must not be null! To terminate the execution chain on a specific condition you can use flatMap(Predicate, Function).

        Example

        
         public RestAction<Void> initializeGiveaway(Guild guild, String channelName) {
             return guild.createTextChannel(channelName)
                  .addPermissionOverride(guild.getPublicRole(), null, EnumSet.of(Permission.MESSAGE_WRITE)) // deny write for everyone
                  .addPermissionOverride(guild.getSelfMember(), EnumSet.of(Permission.MESSAGE_WRITE), null) // allow for self user
                  .flatMap((channel) -> channel.sendMessage("React to enter giveaway!")) // send message
                  .flatMap((message) -> message.addReaction(REACTION)); // add reaction
         }
         
        Type Parameters:
        O - The target output type
        Parameters:
        flatMap - The mapping function to apply to the action result, must return a RestAction
        Returns:
        RestAction for the mapped type
        Since:
        4.1.1
      • flatMap

        @Nonnull
        @CheckReturnValue
        default <O> RestAction<O> flatMap​(@Nullable
                                          java.util.function.Predicate<? super T> condition,
                                          @Nonnull
                                          java.util.function.Function<? super T,​? extends RestAction<O>> flatMap)
        Intermediate operator that returns a modified RestAction.

        This does not modify this instance but returns a new RestAction which will apply the map function on successful execution. This will compute the result of both RestActions.
        The provided RestAction must not be null!

        Example

        
         private static final int MAX_COUNT = 1000;
         public void updateCount(MessageChannel channel, String messageId, int count) {
             channel.retrieveMessageById(messageId) // retrieve message for check
                 .map(Message::getContentRaw) // get content of the message
                 .map(Integer::parseInt) // convert it to an int
                 .flatMap(
                     (currentCount) -> currentCount + count <= MAX_COUNT, // Only edit if new count does not exceed maximum
                     (currentCount) -> channel.editMessageById(messageId, String.valueOf(currentCount + count)) // edit message
                 )
                 .map(Message::getContentRaw) // get content of the message
                 .map(Integer::parseInt) // convert it to an int
                 .queue((newCount) -> System.out.println("Updated count to " + newCount));
         }
         
        Type Parameters:
        O - The target output type
        Parameters:
        condition - A condition predicate that decides whether to apply the flat map operator or not
        flatMap - The mapping function to apply to the action result, must return a RestAction
        Returns:
        RestAction for the mapped type
        Since:
        4.1.1
        See Also:
        flatMap(Function), map(Function)
      • and

        @Nonnull
        @CheckReturnValue
        default <U,​O> RestAction<O> and​(@Nonnull
                                              RestAction<U> other,
                                              @Nonnull
                                              java.util.function.BiFunction<? super T,​? super U,​? extends O> accumulator)
        Combines this RestAction with the provided action.
        The result is computed by the provided BiFunction.

        If one of the actions fails, the other will be cancelled. To handle failures individually instead of cancelling you can use mapToResult().

        Type Parameters:
        U - The type of the other action
        O - The result type after applying the accumulator function
        Parameters:
        other - The action to combine
        accumulator - BiFunction to compute the result
        Returns:
        Combined RestAction
        Throws:
        java.lang.IllegalArgumentException - If null is provided or you tried to combine an action with itself
        Since:
        4.2.1
      • and

        @Nonnull
        @CheckReturnValue
        default <U> RestAction<java.lang.Void> and​(@Nonnull
                                                   RestAction<U> other)
        Combines this RestAction with the provided action.

        If one of the actions fails, the other will be cancelled. To handle failures individually instead of cancelling you can use mapToResult().

        Type Parameters:
        U - The type of the other action
        Parameters:
        other - The action to combine
        Returns:
        Combined RestAction with empty result
        Throws:
        java.lang.IllegalArgumentException - If null is provided or you tried to combine an action with itself
        Since:
        4.2.1
      • zip

        @Nonnull
        @CheckReturnValue
        default RestAction<java.util.List<T>> zip​(@Nonnull
                                                  RestAction<? extends T> first,
                                                  @Nonnull
                                                  RestAction<? extends T>... other)
        Accumulates this RestAction with the provided actions into a List.

        If one of the actions fails, the others will be cancelled. To handle failures individually instead of cancelling you can use mapToResult().

        Parameters:
        first - The first other action to accumulate into the list
        other - The other actions to accumulate into the list
        Returns:
        Combined RestAction with empty result
        Throws:
        java.lang.IllegalArgumentException - If null is provided or you tried to combine an action with itself
        Since:
        4.2.1
        See Also:
        allOf(RestAction, RestAction[]), and(RestAction, BiFunction)
      • delay

        @Nonnull
        @CheckReturnValue
        default RestAction<T> delay​(@Nonnull
                                    java.time.Duration duration)
        Intermediate operator that returns a modified RestAction.

        This does not modify this instance but returns a new RestAction which will delay its result by the provided delay.

        Example

        
         public RestAction<Void> selfDestruct(MessageChannel channel, String content) {
             return channel.sendMessage("The following message will destroy itself in 1 minute!")
                 .delay(Duration.ofSeconds(10)) // edit 10 seconds later
                 .flatMap((it) -> it.editMessage(content))
                 .delay(Duration.ofMinutes(1)) // delete 1 minute later
                 .flatMap(Message::delete);
         }
         
        Parameters:
        duration - The delay
        Returns:
        RestAction with delay
        Since:
        4.1.1
        See Also:
        queueAfter(long, TimeUnit)
      • delay

        @Nonnull
        @CheckReturnValue
        default RestAction<T> delay​(@Nonnull
                                    java.time.Duration duration,
                                    @Nullable
                                    java.util.concurrent.ScheduledExecutorService scheduler)
        Intermediate operator that returns a modified RestAction.

        This does not modify this instance but returns a new RestAction which will delay its result by the provided delay.

        Example

        
         public RestAction<Void> selfDestruct(MessageChannel channel, String content) {
             return channel.sendMessage("The following message will destroy itself in 1 minute!")
                 .delay(Duration.ofSeconds(10), scheduler) // edit 10 seconds later
                 .flatMap((it) -> it.editMessage(content))
                 .delay(Duration.ofMinutes(1), scheduler) // delete 1 minute later
                 .flatMap(Message::delete);
         }
         
        Parameters:
        duration - The delay
        scheduler - The scheduler to use, null to use JDA.getRateLimitPool()
        Returns:
        RestAction with delay
        Since:
        4.1.1
        See Also:
        queueAfter(long, TimeUnit, ScheduledExecutorService)
      • delay

        @Nonnull
        @CheckReturnValue
        default RestAction<T> delay​(long delay,
                                    @Nonnull
                                    java.util.concurrent.TimeUnit unit)
        Intermediate operator that returns a modified RestAction.

        This does not modify this instance but returns a new RestAction which will delay its result by the provided delay.

        Example

        
         public RestAction<Void> selfDestruct(MessageChannel channel, String content) {
             return channel.sendMessage("The following message will destroy itself in 1 minute!")
                 .delay(10, SECONDS) // edit 10 seconds later
                 .flatMap((it) -> it.editMessage(content))
                 .delay(1, MINUTES) // delete 1 minute later
                 .flatMap(Message::delete);
         }
         
        Parameters:
        delay - The delay value
        unit - The time unit for the delay value
        Returns:
        RestAction with delay
        Since:
        4.1.1
        See Also:
        queueAfter(long, TimeUnit)
      • delay

        @Nonnull
        @CheckReturnValue
        default RestAction<T> delay​(long delay,
                                    @Nonnull
                                    java.util.concurrent.TimeUnit unit,
                                    @Nullable
                                    java.util.concurrent.ScheduledExecutorService scheduler)
        Intermediate operator that returns a modified RestAction.

        This does not modify this instance but returns a new RestAction which will delay its result by the provided delay.

        Example

        
         public RestAction<Void> selfDestruct(MessageChannel channel, String content) {
             return channel.sendMessage("The following message will destroy itself in 1 minute!")
                 .delay(10, SECONDS, scheduler) // edit 10 seconds later
                 .flatMap((it) -> it.editMessage(content))
                 .delay(1, MINUTES, scheduler) // delete 1 minute later
                 .flatMap(Message::delete);
         }
         
        Parameters:
        delay - The delay value
        unit - The time unit for the delay value
        scheduler - The scheduler to use, null to use JDA.getRateLimitPool()
        Returns:
        RestAction with delay
        Since:
        4.1.1
        See Also:
        queueAfter(long, TimeUnit, ScheduledExecutorService)
      • submitAfter

        @Nonnull
        default DelayedCompletableFuture<T> submitAfter​(long delay,
                                                        @Nonnull
                                                        java.util.concurrent.TimeUnit unit)
        Schedules a call to queue() to be executed after the specified delay.
        This is an asynchronous operation that will return a CompletableFuture representing the task.

        Similar to queueAfter(long, TimeUnit) but does not require callbacks to be passed. Continuations of CompletableFuture can be used instead.

        The global JDA RateLimit ScheduledExecutorService is used for this operation.
        You can provide your own Executor using submitAfter(long, java.util.concurrent.TimeUnit, java.util.concurrent.ScheduledExecutorService)!

        Parameters:
        delay - The delay after which this computation should be executed, negative to execute immediately
        unit - The TimeUnit to convert the specified delay
        Returns:
        DelayedCompletableFuture representing the delayed operation
        Throws:
        java.lang.IllegalArgumentException - If the provided TimeUnit is null
      • submitAfter

        @Nonnull
        default DelayedCompletableFuture<T> submitAfter​(long delay,
                                                        @Nonnull
                                                        java.util.concurrent.TimeUnit unit,
                                                        @Nullable
                                                        java.util.concurrent.ScheduledExecutorService executor)
        Schedules a call to queue() to be executed after the specified delay.
        This is an asynchronous operation that will return a CompletableFuture representing the task.

        Similar to queueAfter(long, TimeUnit) but does not require callbacks to be passed. Continuations of CompletableFuture can be used instead.

        The specified ScheduledExecutorService is used for this operation.

        Parameters:
        delay - The delay after which this computation should be executed, negative to execute immediately
        unit - The TimeUnit to convert the specified delay
        executor - The ScheduledExecutorService that should be used to schedule this operation, or null to use the default
        Returns:
        DelayedCompletableFuture representing the delayed operation
        Throws:
        java.lang.IllegalArgumentException - If the provided TimeUnit is null
      • completeAfter

        default T completeAfter​(long delay,
                                @Nonnull
                                java.util.concurrent.TimeUnit unit)
        Blocks the current Thread for the specified delay and calls complete() when delay has been reached.
        If the specified delay is negative this action will execute immediately. (see: TimeUnit.sleep(long))
        Parameters:
        delay - The delay after which to execute a call to complete()
        unit - The TimeUnit which should be used (this will use unit.sleep(delay))
        Returns:
        The response value
        Throws:
        java.lang.IllegalArgumentException - If the specified TimeUnit is null
        java.lang.RuntimeException - If the sleep operation is interrupted
      • queueAfter

        @Nonnull
        default java.util.concurrent.ScheduledFuture<?> queueAfter​(long delay,
                                                                   @Nonnull
                                                                   java.util.concurrent.TimeUnit unit,
                                                                   @Nullable
                                                                   java.util.concurrent.ScheduledExecutorService executor)
        Schedules a call to queue() to be executed after the specified delay.
        This is an asynchronous operation that will return a ScheduledFuture representing the task.

        This operation gives no access to the response value.
        Use queueAfter(long, java.util.concurrent.TimeUnit, java.util.function.Consumer) to access the success consumer for queue(java.util.function.Consumer)!

        The specified ScheduledExecutorService is used for this operation.

        Parameters:
        delay - The delay after which this computation should be executed, negative to execute immediately
        unit - The TimeUnit to convert the specified delay
        executor - The Non-null ScheduledExecutorService that should be used to schedule this operation
        Returns:
        ScheduledFuture representing the delayed operation
        Throws:
        java.lang.IllegalArgumentException - If the provided TimeUnit or ScheduledExecutorService is null
      • queueAfter

        @Nonnull
        default java.util.concurrent.ScheduledFuture<?> queueAfter​(long delay,
                                                                   @Nonnull
                                                                   java.util.concurrent.TimeUnit unit,
                                                                   @Nullable
                                                                   java.util.function.Consumer<? super T> success,
                                                                   @Nullable
                                                                   java.util.concurrent.ScheduledExecutorService executor)
        Schedules a call to queue(java.util.function.Consumer) to be executed after the specified delay.
        This is an asynchronous operation that will return a ScheduledFuture representing the task.

        This operation gives no access to the failure callback.
        Use queueAfter(long, java.util.concurrent.TimeUnit, java.util.function.Consumer, java.util.function.Consumer) to access the failure consumer for queue(java.util.function.Consumer, java.util.function.Consumer)!

        The specified ScheduledExecutorService is used for this operation.

        Parameters:
        delay - The delay after which this computation should be executed, negative to execute immediately
        unit - The TimeUnit to convert the specified delay
        success - The success Consumer that should be called once the queue(java.util.function.Consumer) operation completes successfully.
        executor - The Non-null ScheduledExecutorService that should be used to schedule this operation
        Returns:
        ScheduledFuture representing the delayed operation
        Throws:
        java.lang.IllegalArgumentException - If the provided TimeUnit or ScheduledExecutorService is null
      • queueAfter

        @Nonnull
        default java.util.concurrent.ScheduledFuture<?> queueAfter​(long delay,
                                                                   @Nonnull
                                                                   java.util.concurrent.TimeUnit unit,
                                                                   @Nullable
                                                                   java.util.function.Consumer<? super T> success,
                                                                   @Nullable
                                                                   java.util.function.Consumer<? super java.lang.Throwable> failure,
                                                                   @Nullable
                                                                   java.util.concurrent.ScheduledExecutorService executor)
        Schedules a call to queue(java.util.function.Consumer, java.util.function.Consumer) to be executed after the specified delay.
        This is an asynchronous operation that will return a ScheduledFuture representing the task.

        The specified ScheduledExecutorService is used for this operation.

        Parameters:
        delay - The delay after which this computation should be executed, negative to execute immediately
        unit - The TimeUnit to convert the specified delay
        success - The success Consumer that should be called once the queue(java.util.function.Consumer, java.util.function.Consumer) operation completes successfully.
        failure - The failure Consumer that should be called in case of an error of the queue(java.util.function.Consumer, java.util.function.Consumer) operation.
        executor - The Non-null ScheduledExecutorService that should be used to schedule this operation
        Returns:
        ScheduledFuture representing the delayed operation
        Throws:
        java.lang.IllegalArgumentException - If the provided TimeUnit or ScheduledExecutorService is null
        See Also:
        ErrorHandler