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
,EmoteManager
,GuildAction
,GuildManager
,InviteAction
,Manager<M>
,MemberAction
,MessageAction
,MessagePaginationAction
,OrderAction<T,M>
,PaginationAction<T,M>
,PermissionOverrideAction
,PermOverrideManager
,ReactionPaginationAction
,RoleAction
,RoleManager
,RoleOrderAction
,WebhookAction
,WebhookManager
- 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 onsubmit()
.
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)
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 bothqueue()
andcomplete()
versions that will be executed by aScheduledExecutorService
after a specified delay:queueAfter(long, TimeUnit)
Schedules a call toqueue()
with default callbackConsumers
to be executed after the specifieddelay
.
TheTimeUnit
is used to convert the provided long into a delay time.
Example:queueAfter(1, TimeUnit.SECONDS);
will callqueue()
1 second later.submitAfter(long, TimeUnit)
This returns aScheduledFuture
which can be joined into the current Thread usingFuture.get()
The blocking call tosubmitAfter(delay, unit).get()
will return the value processed by a call tocomplete()
completeAfter(long, TimeUnit)
This operation simply sleeps for the given delay and will callcomplete()
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. SpecificallyqueueAfter(long, TimeUnit)
has overloads to provide a success and/or failure callback due to the returnedScheduledFuture
not being able to provide the response values of thequeue()
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 asynchronousqueue()
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 asynchronouslySometimes 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 callbackConsumer
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 withqueue()
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
-
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Default Methods Modifier and Type Method Description default T
complete()
Blocks the current Thread and awaits the completion of ansubmit()
request.T
complete(boolean shouldQueue)
Blocks the current Thread and awaits the completion of ansubmit()
request.default T
completeAfter(long delay, TimeUnit unit)
Blocks the current Thread for the specified delay and callscomplete()
when delay has been reached.static Consumer<? super Throwable>
getDefaultFailure()
The default failure callback used when none is provided inqueue(Consumer, Consumer)
.static Consumer<Object>
getDefaultSuccess()
The default success callback used when none is provided inqueue(Consumer, Consumer)
orqueue(Consumer)
.JDA
getJDA()
The current JDA instancestatic boolean
isPassContext()
Whether RestActions will useContextException
automatically to keep track of the caller context.default void
queue()
Submits a Request for execution.default void
queue(Consumer<? super T> success)
Submits a Request for execution.void
queue(Consumer<? super T> success, Consumer<? super Throwable> failure)
Submits a Request for execution.default ScheduledFuture<?>
queueAfter(long delay, TimeUnit unit)
Schedules a call toqueue()
to be executed after the specifieddelay
.default ScheduledFuture<?>
queueAfter(long delay, TimeUnit unit, ScheduledExecutorService executor)
Schedules a call toqueue()
to be executed after the specifieddelay
.default ScheduledFuture<?>
queueAfter(long delay, TimeUnit unit, Consumer<? super T> success)
Schedules a call toqueue(java.util.function.Consumer)
to be executed after the specifieddelay
.default ScheduledFuture<?>
queueAfter(long delay, TimeUnit unit, Consumer<? super T> success, ScheduledExecutorService executor)
Schedules a call toqueue(java.util.function.Consumer)
to be executed after the specifieddelay
.default ScheduledFuture<?>
queueAfter(long delay, TimeUnit unit, Consumer<? super T> success, Consumer<? super Throwable> failure)
Schedules a call toqueue(java.util.function.Consumer, java.util.function.Consumer)
to be executed after the specifieddelay
.default ScheduledFuture<?>
queueAfter(long delay, TimeUnit unit, Consumer<? super T> success, Consumer<? super Throwable> failure, ScheduledExecutorService executor)
Schedules a call toqueue(java.util.function.Consumer, java.util.function.Consumer)
to be executed after the specifieddelay
.RestAction<T>
setCheck(BooleanSupplier checks)
Sets the last-second checks before finally executing the http request in the queue.static void
setDefaultFailure(Consumer<? super Throwable> callback)
The default failure callback used when none is provided inqueue(Consumer, Consumer)
.static void
setDefaultSuccess(Consumer<Object> callback)
The default success callback used when none is provided inqueue(Consumer, Consumer)
orqueue(Consumer)
.static void
setPassContext(boolean enable)
If enabled this will pass aContextException
as root-cause to all failure consumers.default CompletableFuture<T>
submit()
Submits a Request for execution and provides aCompletableFuture
representing its completion task.CompletableFuture<T>
submit(boolean shouldQueue)
Submits a Request for execution and provides aCompletableFuture
representing its completion task.default DelayedCompletableFuture<T>
submitAfter(long delay, TimeUnit unit)
Schedules a call toqueue()
to be executed after the specifieddelay
.default DelayedCompletableFuture<T>
submitAfter(long delay, TimeUnit unit, ScheduledExecutorService executor)
Schedules a call toqueue()
to be executed after the specifieddelay
.
-
-
-
Method Detail
-
setPassContext
static void setPassContext(boolean enable)
If enabled this will pass aContextException
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 useContextException
automatically to keep track of the caller context.
If set totrue
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 Consumer<? super Throwable> callback)
The default failure callback used when none is provided inqueue(Consumer, Consumer)
.- Parameters:
callback
- The fallback to use, or null to ignore failures (not recommended)
-
setDefaultSuccess
static void setDefaultSuccess(@Nullable Consumer<Object> callback)
The default success callback used when none is provided inqueue(Consumer, Consumer)
orqueue(Consumer)
.- Parameters:
callback
- The fallback to use, or null to ignore success
-
getDefaultFailure
@Nonnull static Consumer<? super Throwable> getDefaultFailure()
The default failure callback used when none is provided inqueue(Consumer, Consumer)
.- Returns:
- The fallback consumer
-
getDefaultSuccess
@Nonnull static Consumer<Object> getDefaultSuccess()
The default success callback used when none is provided inqueue(Consumer, Consumer)
orqueue(Consumer)
.- Returns:
- The fallback consumer
-
setCheck
@Nonnull RestAction<T> setCheck(@Nullable BooleanSupplier checks)
Sets the last-second checks before finally executing the http request in the queue.
If the provided supplier evaluates tofalse
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, ornull
to run no checks- Returns:
- The current RestAction for chaining convenience
-
queue
default void queue()
Submits a Request for execution.
Using the default callback functions:setDefaultSuccess(Consumer)
andsetDefaultFailure(Consumer)
To access the response you can use
queue(java.util.function.Consumer)
and to handle failures usequeue(java.util.function.Consumer, java.util.function.Consumer)
.This method is asynchronous
Example
public static void sendMessage(MessageChannel channel, String content) { // sendMessage returns "MessageAction" which is a specialization for "RestAction<Message>" RestAction<Message> action = channel.sendMessage(content); // call queue() to send the message off to discord. action.queue(); }
-
queue
default void queue(@Nullable 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)- See Also:
queue(Consumer, Consumer)
-
queue
void queue(@Nullable Consumer<? super T> success, @Nullable Consumer<? super 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)- See Also:
submit()
-
complete
default T complete()
Blocks the current Thread and awaits the completion of ansubmit()
request.
Used for synchronous logic.This might throw
RuntimeExceptions
- Returns:
- The response value
- Throws:
IllegalStateException
- If used within aqueue(...)
callback
-
complete
T complete(boolean shouldQueue) throws RateLimitedException
Blocks the current Thread and awaits the completion of ansubmit()
request.
Used for synchronous logic.- Parameters:
shouldQueue
- Whether this should automatically handle rate limitations (default true)- Returns:
- The response value
- Throws:
IllegalStateException
- If used within aqueue(...)
callbackRateLimitedException
- If we were rate limited and theshouldQueue
is false. Usecomplete()
to avoid this Exception.
-
submit
@Nonnull default CompletableFuture<T> submit()
Submits a Request for execution and provides aCompletableFuture
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
-
submit
@Nonnull CompletableFuture<T> submit(boolean shouldQueue)
Submits a Request for execution and provides aCompletableFuture
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
-
submitAfter
@Nonnull default DelayedCompletableFuture<T> submitAfter(long delay, @Nonnull TimeUnit unit)
Schedules a call toqueue()
to be executed after the specifieddelay
.
This is an asynchronous operation that will return aCompletableFuture
representing the task.Similar to
queueAfter(long, TimeUnit)
but does not require callbacks to be passed. Continuations ofCompletableFuture
can be used instead.The global JDA RateLimit
ScheduledExecutorService
is used for this operation.
You can provide your own Executor usingsubmitAfter(long, java.util.concurrent.TimeUnit, java.util.concurrent.ScheduledExecutorService)
!- Parameters:
delay
- The delay after which this computation should be executed, negative to execute immediatelyunit
- TheTimeUnit
to convert the specifieddelay
- Returns:
DelayedCompletableFuture
representing the delayed operation- Throws:
IllegalArgumentException
- If the provided TimeUnit isnull
-
submitAfter
@Nonnull default DelayedCompletableFuture<T> submitAfter(long delay, @Nonnull TimeUnit unit, @Nullable ScheduledExecutorService executor)
Schedules a call toqueue()
to be executed after the specifieddelay
.
This is an asynchronous operation that will return aCompletableFuture
representing the task.Similar to
queueAfter(long, TimeUnit)
but does not require callbacks to be passed. Continuations ofCompletableFuture
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 immediatelyunit
- TheTimeUnit
to convert the specifieddelay
executor
- TheScheduledExecutorService
that should be used to schedule this operation, or null to use the default- Returns:
DelayedCompletableFuture
representing the delayed operation- Throws:
IllegalArgumentException
- If the provided TimeUnit isnull
-
completeAfter
default T completeAfter(long delay, @Nonnull TimeUnit unit)
Blocks the current Thread for the specified delay and callscomplete()
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 tocomplete()
unit
- TheTimeUnit
which should be used (this will useunit.sleep(delay)
)- Returns:
- The response value
- Throws:
IllegalArgumentException
- If the specifiedTimeUnit
isnull
RuntimeException
- If the sleep operation is interrupted
-
queueAfter
@Nonnull default ScheduledFuture<?> queueAfter(long delay, @Nonnull TimeUnit unit)
Schedules a call toqueue()
to be executed after the specifieddelay
.
This is an asynchronous operation that will return aScheduledFuture
representing the task.This operation gives no access to the response value.
UsequeueAfter(long, java.util.concurrent.TimeUnit, java.util.function.Consumer)
to access the success consumer forqueue(java.util.function.Consumer)
!The global JDA
ScheduledExecutorService
is used for this operation.
You can provide your own Executor withqueueAfter(long, java.util.concurrent.TimeUnit, java.util.concurrent.ScheduledExecutorService)
- Parameters:
delay
- The delay after which this computation should be executed, negative to execute immediatelyunit
- TheTimeUnit
to convert the specifieddelay
- Returns:
ScheduledFuture
representing the delayed operation- Throws:
IllegalArgumentException
- If the provided TimeUnit isnull
-
queueAfter
@Nonnull default ScheduledFuture<?> queueAfter(long delay, @Nonnull TimeUnit unit, @Nullable Consumer<? super T> success)
Schedules a call toqueue(java.util.function.Consumer)
to be executed after the specifieddelay
.
This is an asynchronous operation that will return aScheduledFuture
representing the task.This operation gives no access to the failure callback.
UsequeueAfter(long, java.util.concurrent.TimeUnit, java.util.function.Consumer, java.util.function.Consumer)
to access the failure consumer forqueue(java.util.function.Consumer, java.util.function.Consumer)
!The global JDA
ScheduledExecutorService
is used for this operation.
You can provide your own Executor withqueueAfter(long, java.util.concurrent.TimeUnit, java.util.function.Consumer, java.util.concurrent.ScheduledExecutorService)
- Parameters:
delay
- The delay after which this computation should be executed, negative to execute immediatelyunit
- TheTimeUnit
to convert the specifieddelay
success
- The successConsumer
that should be called once thequeue(java.util.function.Consumer)
operation completes successfully.- Returns:
ScheduledFuture
representing the delayed operation- Throws:
IllegalArgumentException
- If the provided TimeUnit isnull
-
queueAfter
@Nonnull default ScheduledFuture<?> queueAfter(long delay, @Nonnull TimeUnit unit, @Nullable Consumer<? super T> success, @Nullable Consumer<? super Throwable> failure)
Schedules a call toqueue(java.util.function.Consumer, java.util.function.Consumer)
to be executed after the specifieddelay
.
This is an asynchronous operation that will return aScheduledFuture
representing the task.The global JDA
ScheduledExecutorService
is used for this operation.
You provide your own Executor withqueueAfter(long, java.util.concurrent.TimeUnit, java.util.function.Consumer, java.util.function.Consumer, java.util.concurrent.ScheduledExecutorService)
- Parameters:
delay
- The delay after which this computation should be executed, negative to execute immediatelyunit
- TheTimeUnit
to convert the specifieddelay
success
- The successConsumer
that should be called once thequeue(java.util.function.Consumer, java.util.function.Consumer)
operation completes successfully.failure
- The failureConsumer
that should be called in case of an error of thequeue(java.util.function.Consumer, java.util.function.Consumer)
operation.- Returns:
ScheduledFuture
representing the delayed operation- Throws:
IllegalArgumentException
- If the provided TimeUnit isnull
-
queueAfter
@Nonnull default ScheduledFuture<?> queueAfter(long delay, @Nonnull TimeUnit unit, @Nullable ScheduledExecutorService executor)
Schedules a call toqueue()
to be executed after the specifieddelay
.
This is an asynchronous operation that will return aScheduledFuture
representing the task.This operation gives no access to the response value.
UsequeueAfter(long, java.util.concurrent.TimeUnit, java.util.function.Consumer)
to access the success consumer forqueue(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 immediatelyunit
- TheTimeUnit
to convert the specifieddelay
executor
- The Non-nullScheduledExecutorService
that should be used to schedule this operation- Returns:
ScheduledFuture
representing the delayed operation- Throws:
IllegalArgumentException
- If the provided TimeUnit or ScheduledExecutorService isnull
-
queueAfter
@Nonnull default ScheduledFuture<?> queueAfter(long delay, @Nonnull TimeUnit unit, @Nullable Consumer<? super T> success, @Nullable ScheduledExecutorService executor)
Schedules a call toqueue(java.util.function.Consumer)
to be executed after the specifieddelay
.
This is an asynchronous operation that will return aScheduledFuture
representing the task.This operation gives no access to the failure callback.
UsequeueAfter(long, java.util.concurrent.TimeUnit, java.util.function.Consumer, java.util.function.Consumer)
to access the failure consumer forqueue(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 immediatelyunit
- TheTimeUnit
to convert the specifieddelay
success
- The successConsumer
that should be called once thequeue(java.util.function.Consumer)
operation completes successfully.executor
- The Non-nullScheduledExecutorService
that should be used to schedule this operation- Returns:
ScheduledFuture
representing the delayed operation- Throws:
IllegalArgumentException
- If the provided TimeUnit or ScheduledExecutorService isnull
-
queueAfter
@Nonnull default ScheduledFuture<?> queueAfter(long delay, @Nonnull TimeUnit unit, @Nullable Consumer<? super T> success, @Nullable Consumer<? super Throwable> failure, @Nullable ScheduledExecutorService executor)
Schedules a call toqueue(java.util.function.Consumer, java.util.function.Consumer)
to be executed after the specifieddelay
.
This is an asynchronous operation that will return aScheduledFuture
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 immediatelyunit
- TheTimeUnit
to convert the specifieddelay
success
- The successConsumer
that should be called once thequeue(java.util.function.Consumer, java.util.function.Consumer)
operation completes successfully.failure
- The failureConsumer
that should be called in case of an error of thequeue(java.util.function.Consumer, java.util.function.Consumer)
operation.executor
- The Non-nullScheduledExecutorService
that should be used to schedule this operation- Returns:
ScheduledFuture
representing the delayed operation- Throws:
IllegalArgumentException
- If the provided TimeUnit or ScheduledExecutorService isnull
-
-