Class JDABuilder
JDA instances. This is also useful for making sure all of
your EventListeners are registered
before JDA attempts to log in.
A single JDABuilder can be reused multiple times. Each call to
build()
creates a new JDA instance using the same information.
This means that you can have listeners easily registered to multiple JDA instances.
-
Method Summary
Modifier and TypeMethodDescriptionaddEventListeners(Object... listeners) Adds all provided listeners to the list of listeners that will be used to populate theJDAobject.build()Builds a newJDAinstance and uses the provided token to start the login process.static JDABuildercreate(String token, Collection<GatewayIntent> intents) Creates a JDABuilder with the predefined token.static JDABuildercreate(String token, GatewayIntent intent, GatewayIntent... intents) Creates a JDABuilder with the predefined token.static JDABuildercreate(Collection<GatewayIntent> intents) Creates a completely empty JDABuilder with the predefined intents.static JDABuildercreate(GatewayIntent intent, GatewayIntent... intents) Creates a completely empty JDABuilder with the predefined intents.static JDABuildercreateDefault(String token) Creates a JDABuilder with recommended default settings.static JDABuildercreateDefault(String token, Collection<GatewayIntent> intents) Creates a JDABuilder with recommended default settings.static JDABuildercreateDefault(String token, GatewayIntent intent, GatewayIntent... intents) Creates a JDABuilder with recommended default settings.static JDABuildercreateLight(String token) Creates a JDABuilder with low memory profile settings.static JDABuildercreateLight(String token, Collection<GatewayIntent> intents) Creates a JDABuilder with low memory profile settings.static JDABuildercreateLight(String token, GatewayIntent intent, GatewayIntent... intents) Creates a JDABuilder with low memory profile settings.disableCache(Collection<CacheFlag> flags) Disable specific cache flags.disableCache(CacheFlag flag, CacheFlag... flags) Disable specific cache flags.disableIntents(Collection<GatewayIntent> intents) Disable the specifiedGatewayIntents.disableIntents(GatewayIntent intent, GatewayIntent... intents) Disable the specifiedGatewayIntents.enableCache(Collection<CacheFlag> flags) Enable specific cache flags.enableCache(CacheFlag flag, CacheFlag... flags) Enable specific cache flags.enableIntents(Collection<GatewayIntent> intents) Enable the specifiedGatewayIntents.enableIntents(GatewayIntent intent, GatewayIntent... intents) Enable the specifiedGatewayIntents.removeEventListeners(Object... listeners) Removes all provided listeners from the list of listeners.setActivity(Activity activity) Sets theActivityfor our session.Sets theScheduledExecutorServiceused by the audio WebSocket connection.setAudioPool(ScheduledExecutorService pool, boolean automaticShutdown) Sets theScheduledExecutorServiceused by the audio WebSocket connection.setAudioSendFactory(IAudioSendFactory factory) Changes the factory used to createIAudioSendSystemobjects which handle the sending loop for audio packets.setAutoReconnect(boolean autoReconnect) Sets whether or not JDA should try to reconnect if a connection-error is encountered.setBulkDeleteSplittingEnabled(boolean enabled) If enabled, JDA will separate the bulk delete event into individual delete events, but this isn't as efficient as handling a single event would be.setCallbackPool(ExecutorService executor) Sets theExecutorServicethat should be used in the JDA callback handler which mostly consists ofRestActioncallbacks.setCallbackPool(ExecutorService executor, boolean automaticShutdown) Sets theExecutorServicethat should be used in the JDA callback handler which mostly consists ofRestActioncallbacks.setChunkingFilter(ChunkingFilter filter) TheChunkingFilterto filter which guilds should use member chunking.setCompression(Compression compression) Sets the compression algorithm used with the gateway connection, this will decrease the amount of used bandwidth for the running bot instance for the cost of a few extra cycles for decompression.setContextEnabled(boolean enable) Whether JDA should use a synchronized MDC context for all of its controlled threads.Sets theMDCmappings to use in JDA.setDisabledIntents(Collection<GatewayIntent> intents) Configures which events will be disabled.setDisabledIntents(GatewayIntent intent, GatewayIntent... intents) Configures which events will be disabled.setEnabledIntents(Collection<GatewayIntent> intents) Configures which events will be enabled.setEnabledIntents(GatewayIntent intent, GatewayIntent... intents) Configures which events will be enabled.setEnableShutdownHook(boolean enable) Enables/Disables the use of a Shutdown hook to clean up JDA.setEventManager(IEventManager manager) Changes the internally used EventManager.setEventPassthrough(boolean enable) Whether JDA should store the rawDataObjectfor every discord event, accessible throughgetRawData().setEventPool(ExecutorService executor) Sets theExecutorServicethat should be used by the event proxy to schedule events.setEventPool(ExecutorService executor, boolean automaticShutdown) Sets theExecutorServicethat should be used by the event proxy to schedule events.setGatewayEncoding(GatewayEncoding encoding) Choose whichGatewayEncodingJDA should use.Sets theScheduledExecutorServiceused by the main WebSocket connection for workers.setGatewayPool(ScheduledExecutorService pool, boolean automaticShutdown) Sets theScheduledExecutorServiceused by the main WebSocket connection for workers.setHttpClient(okhttp3.OkHttpClient client) Sets theOkHttpClientthat will be used by JDAs requester.setHttpClientBuilder(okhttp3.OkHttpClient.Builder builder) Sets theBuilderthat will be used by JDAs requester.setIdle(boolean idle) Sets whether or not we should mark our session as afk
This value can be changed at any time in thePresencefrom a JDA instance.setLargeThreshold(int threshold) Decides the total number of members at which a guild should start to use lazy loading.setMaxBufferSize(int bufferSize) The maximum size, in bytes, of the buffer used for decompressing discord payloads.setMaxReconnectDelay(int maxReconnectDelay) Sets the maximum amount of time that JDA will back off to wait when attempting to reconnect the MainWebsocket.Configure the member caching policy.Sets theExecutorServicethat should be used in the JDA request handler.setRateLimitElastic(ExecutorService pool, boolean automaticShutdown) Sets theExecutorServicethat should be used in the JDA request handler.Sets theScheduledExecutorServicethat should be used in the JDA rate-limit handler.setRateLimitScheduler(ScheduledExecutorService pool, boolean automaticShutdown) Sets theScheduledExecutorServicethat should be used in the JDA rate-limit handler.setRawEventsEnabled(boolean enable) Whether JDA should fireRawGatewayEventfor every discord event.setRequestTimeoutRetry(boolean retryOnTimeout) Whether the Requester should retry when aSocketTimeoutExceptionoccurs.setRestConfig(RestConfig config) CustomRestConfigto use for this JDA instance.setSessionController(SessionController controller) Sets theSessionControllerfor this JDABuilder instance.setStatus(OnlineStatus status) Sets theOnlineStatusour connection will display.setVoiceDispatchInterceptor(VoiceDispatchInterceptor interceptor) Configures a custom voice dispatch handler which handles audio connections.setWebsocketFactory(WebSocketFactory factory) Sets theWebSocketFactorythat will be used by JDA's websocket client.useSharding(int shardId, int shardTotal) This will enable sharding mode for JDA.
-
Method Details
-
createDefault
Creates a JDABuilder with recommended default settings.
Note that these defaults can potentially change in the future.setMemberCachePolicy(MemberCachePolicy)is set toMemberCachePolicy.DEFAULTsetChunkingFilter(ChunkingFilter)is set toChunkingFilter.NONEsetEnabledIntents(Collection)is set toGatewayIntent.DEFAULT- This disables
CacheFlag.ACTIVITYandCacheFlag.CLIENT_STATUS
- Parameters:
token- The bot token to use- Returns:
- The new JDABuilder
- See Also:
-
createDefault
@Nonnull @CheckReturnValue public static JDABuilder createDefault(@Nullable String token, @Nonnull GatewayIntent intent, @Nonnull GatewayIntent... intents) Creates a JDABuilder with recommended default settings.
Note that these defaults can potentially change in the future.setMemberCachePolicy(MemberCachePolicy)is set toMemberCachePolicy.DEFAULTsetChunkingFilter(ChunkingFilter)is set toChunkingFilter.NONE- This disables
CacheFlag.ACTIVITYandCacheFlag.CLIENT_STATUS
You can omit intents in this method to use
GatewayIntent.DEFAULTand enable additional intents withenableIntents(Collection).If you don't enable certain intents, the cache will be disabled. For instance, if the
GUILD_MEMBERSintent is disabled, then members will only be cached when a voice state is available. If bothGUILD_MEMBERSandGUILD_VOICE_STATESare disabled then no members will be cached.The individual
CacheFlagswill also be disabled if therequired intentis not enabled.- Parameters:
token- The bot token to useintent- The intent to enableintents- Any other intents to enable- Returns:
- The new JDABuilder
- Throws:
IllegalArgumentException- If provided with null intents
-
createDefault
@Nonnull @CheckReturnValue public static JDABuilder createDefault(@Nullable String token, @Nonnull Collection<GatewayIntent> intents) Creates a JDABuilder with recommended default settings.
Note that these defaults can potentially change in the future.setMemberCachePolicy(MemberCachePolicy)is set toMemberCachePolicy.DEFAULTsetChunkingFilter(ChunkingFilter)is set toChunkingFilter.NONE- This disables
CacheFlag.ACTIVITYandCacheFlag.CLIENT_STATUS
You can omit intents in this method to use
GatewayIntent.DEFAULTand enable additional intents withenableIntents(Collection).If you don't enable certain intents, the cache will be disabled. For instance, if the
GUILD_MEMBERSintent is disabled, then members will only be cached when a voice state is available. If bothGUILD_MEMBERSandGUILD_VOICE_STATESare disabled then no members will be cached.The individual
CacheFlagswill also be disabled if therequired intentis not enabled.- Parameters:
token- The bot token to useintents- The intents to enable- Returns:
- The new JDABuilder
- Throws:
IllegalArgumentException- If provided with null intents
-
createLight
Creates a JDABuilder with low memory profile settings.
Note that these defaults can potentially change in the future.setEnabledIntents(Collection)is set toGatewayIntent.DEFAULTsetMemberCachePolicy(MemberCachePolicy)is set toMemberCachePolicy.NONEsetChunkingFilter(ChunkingFilter)is set toChunkingFilter.NONE- This disables all existing
CacheFlags
- Parameters:
token- The bot token to use- Returns:
- The new JDABuilder
- See Also:
-
createLight
@Nonnull @CheckReturnValue public static JDABuilder createLight(@Nullable String token, @Nonnull GatewayIntent intent, @Nonnull GatewayIntent... intents) Creates a JDABuilder with low memory profile settings.
Note that these defaults can potentially change in the future.setMemberCachePolicy(MemberCachePolicy)is set toMemberCachePolicy.NONEsetChunkingFilter(ChunkingFilter)is set toChunkingFilter.NONE- This disables all existing
CacheFlags
You can omit intents in this method to use
GatewayIntent.DEFAULTand enable additional intents withenableIntents(Collection).If you don't enable certain intents, the cache will be disabled. For instance, if the
GUILD_MEMBERSintent is disabled, then members will only be cached when a voice state is available. If bothGUILD_MEMBERSandGUILD_VOICE_STATESare disabled then no members will be cached.The individual
CacheFlagswill also be disabled if therequired intentis not enabled.- Parameters:
token- The bot token to useintent- The first intent to useintents- The other gateway intents to use- Returns:
- The new JDABuilder
-
createLight
@Nonnull @CheckReturnValue public static JDABuilder createLight(@Nullable String token, @Nonnull Collection<GatewayIntent> intents) Creates a JDABuilder with low memory profile settings.
Note that these defaults can potentially change in the future.setMemberCachePolicy(MemberCachePolicy)is set toMemberCachePolicy.NONEsetChunkingFilter(ChunkingFilter)is set toChunkingFilter.NONE- This disables all existing
CacheFlags
You can omit intents in this method to use
GatewayIntent.DEFAULTand enable additional intents withenableIntents(Collection).If you don't enable certain intents, the cache will be disabled. For instance, if the
GUILD_MEMBERSintent is disabled, then members will only be cached when a voice state is available. If bothGUILD_MEMBERSandGUILD_VOICE_STATESare disabled then no members will be cached.The individual
CacheFlagswill also be disabled if therequired intentis not enabled.- Parameters:
token- The bot token to useintents- The gateway intents to use- Returns:
- The new JDABuilder
-
create
@Nonnull @CheckReturnValue public static JDABuilder create(@Nonnull GatewayIntent intent, @Nonnull GatewayIntent... intents) Creates a completely empty JDABuilder with the predefined intents.
You can useJDABuilder.create(EnumSet.noneOf(GatewayIntent.class))to disable all intents.
If you use this, you need to set the token usingsetToken(String)before callingbuild()If you don't enable certain intents, the cache will be disabled. For instance, if the
GUILD_MEMBERSintent is disabled, then members will only be cached when a voice state is available. If bothGUILD_MEMBERSandGUILD_VOICE_STATESare disabled then no members will be cached.The individual
CacheFlagswill also be disabled if therequired intentis not enabled.- Parameters:
intent- The first intentintents- The gateway intents to use- Returns:
- The JDABuilder instance
- Throws:
IllegalArgumentException- If the provided intents are null- See Also:
-
create
@Nonnull @CheckReturnValue public static JDABuilder create(@Nonnull Collection<GatewayIntent> intents) Creates a completely empty JDABuilder with the predefined intents.
If you use this, you need to set the token usingsetToken(String)before callingbuild()If you don't enable certain intents, the cache will be disabled. For instance, if the
GUILD_MEMBERSintent is disabled, then members will only be cached when a voice state is available. If bothGUILD_MEMBERSandGUILD_VOICE_STATESare disabled then no members will be cached.The individual
CacheFlagswill also be disabled if therequired intentis not enabled.- Parameters:
intents- The gateway intents to use- Returns:
- The JDABuilder instance
- Throws:
IllegalArgumentException- If the provided intents are null- See Also:
-
create
@Nonnull @CheckReturnValue public static JDABuilder create(@Nullable String token, @Nonnull GatewayIntent intent, @Nonnull GatewayIntent... intents) Creates a JDABuilder with the predefined token.
You can useJDABuilder.create(token, EnumSet.noneOf(GatewayIntent.class))to disable all intents.If you don't enable certain intents, the cache will be disabled. For instance, if the
GUILD_MEMBERSintent is disabled, then members will only be cached when a voice state is available. If bothGUILD_MEMBERSandGUILD_VOICE_STATESare disabled then no members will be cached.The individual
CacheFlagswill also be disabled if therequired intentis not enabled.- Parameters:
token- The bot token to useintent- The first gateway intent to useintents- Additional gateway intents to use- Returns:
- The JDABuilder instance
- Throws:
IllegalArgumentException- If the provided intents are null- See Also:
-
create
@Nonnull @CheckReturnValue public static JDABuilder create(@Nullable String token, @Nonnull Collection<GatewayIntent> intents) Creates a JDABuilder with the predefined token.If you don't enable certain intents, the cache will be disabled. For instance, if the
GUILD_MEMBERSintent is disabled, then members will only be cached when a voice state is available. If bothGUILD_MEMBERSandGUILD_VOICE_STATESare disabled then no members will be cached.The individual
CacheFlagswill also be disabled if therequired intentis not enabled.- Parameters:
token- The bot token to useintents- The gateway intents to use- Returns:
- The JDABuilder instance
- Throws:
IllegalArgumentException- If the provided intents are null- See Also:
-
setGatewayEncoding
Choose whichGatewayEncodingJDA should use.- Parameters:
encoding- TheGatewayEncoding(default: JSON)- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If null is provided- Since:
- 4.2.1
-
setRawEventsEnabled
- Parameters:
enable- True, if JDA should fireRawGatewayEvent.- Returns:
- The JDABuilder instance. Useful for chaining.
- Since:
- 4.0.0
-
setEventPassthrough
Whether JDA should store the rawDataObjectfor every discord event, accessible throughgetRawData().
You can expect to receive the full gateway message payload, including sequence, event name and dispatch type of the events
You can read more about payloads here and the different events here.
Warning: be aware that enabling this could consume a lot of memory if your event objects have a long lifetime.
Default:false- Parameters:
enable- True, if JDA should add the rawDataObjectto every discord event.- Returns:
- The JDABuilder instance. Useful for chaining.
- See Also:
-
setRestConfig
CustomRestConfigto use for this JDA instance.
This can be used to customize how rate-limits are handled and configure a custom http proxy.- Parameters:
config- TheRestConfigto use- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If null is provided
-
enableCache
Enable specific cache flags.
This will not disable any currently set cache flags.- Parameters:
flags- TheCacheFlagsto enable- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If provided with null- See Also:
-
enableCache
Enable specific cache flags.
This will not disable any currently set cache flags.- Parameters:
flag-CacheFlagto enableflags- Other flags to enable- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If provided with null- See Also:
-
disableCache
Disable specific cache flags.
This will not enable any currently unset cache flags.- Parameters:
flags- TheCacheFlagsto disable- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If provided with null- See Also:
-
disableCache
Disable specific cache flags.
This will not enable any currently unset cache flags.- Parameters:
flag-CacheFlagto disableflags- Other flags to disable- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If provided with null- See Also:
-
setMemberCachePolicy
Configure the member caching policy. This will decide whether to cache a member (and its respective user).
All members are cached by default. If a guild is enabled for chunking, all members will be cached for it.You can use this to define a custom caching policy that will greatly improve memory usage.
It is not recommended to disable
GatewayIntent.GUILD_MEMBERSwhen usingMemberCachePolicy.ALLas the members cannot be removed from cache by a leave event without this intent.Example
public void configureCache(JDABuilder builder) { // Cache members who are in a voice channel MemberCachePolicy policy = MemberCachePolicy.VOICE; // Cache members who are in a voice channel // AND are also online policy = policy.and(MemberCachePolicy.ONLINE); // Cache members who are in a voice channel // AND are also online // OR are the owner of the guild policy = policy.or(MemberCachePolicy.OWNER); builder.setMemberCachePolicy(policy); }- Parameters:
policy- TheMemberCachePolicyor null to use defaultMemberCachePolicy.ALL- Returns:
- The JDABuilder instance. Useful for chaining.
- Since:
- 4.2.0
- See Also:
-
setContextMap
Sets theMDCmappings to use in JDA.
If sharding is enabled JDA will automatically add ajda.shardcontext with the format[SHARD_ID / TOTAL]whereSHARD_IDandTOTALare the shard configuration. Additionally it will provide context for the id viajda.shard.idand the total viajda.shard.total.If provided with non-null map this automatically enables MDC context using
setContextEnable(true)!- Parameters:
map- The modifiable context map to use in JDA, ornullto reset- Returns:
- The JDABuilder instance. Useful for chaining.
- See Also:
-
setContextEnabled
Whether JDA should use a synchronized MDC context for all of its controlled threads.
Default:true- Parameters:
enable- True, if JDA should provide an MDC context map- Returns:
- The JDABuilder instance. Useful for chaining.
- See Also:
-
setCompression
Sets the compression algorithm used with the gateway connection, this will decrease the amount of used bandwidth for the running bot instance for the cost of a few extra cycles for decompression. Compression can be entirely disabled by setting this toCompression.NONE.
Default:Compression.ZLIBWe recommend to keep this on the default unless you have issues with the decompression.
This mode might become obligatory in a future version, do not rely on this switch to stay.- Parameters:
compression- The compression algorithm to use with the gateway connection- Returns:
- The JDABuilder instance. Useful for chaining
- Throws:
IllegalArgumentException- If provided with null- See Also:
-
setRequestTimeoutRetry
Whether the Requester should retry when aSocketTimeoutExceptionoccurs.
Default:trueThis value can be changed at any time with
JDA.setRequestTimeoutRetry(boolean)!- Parameters:
retryOnTimeout- True, if the Request should retry once on a socket timeout- Returns:
- The JDABuilder instance. Useful for chaining.
-
setToken
Sets the token that will be used by theJDAinstance to log in whenbuild()is called.To get a bot token:
- Go to your Discord Applications
- Create or select an already existing application
- Verify that it has already been turned into a Bot. If you see the "Create a Bot User" button, click it.
- Click the click to reveal link beside the Token label to show your Bot's
token
- Parameters:
token- The token of the account that you would like to login with.- Returns:
- The JDABuilder instance. Useful for chaining.
-
setHttpClientBuilder
Sets theBuilderthat will be used by JDAs requester.
This can be used to set things such as connection timeout and proxy.- Parameters:
builder- The newBuilderto use- Returns:
- The JDABuilder instance. Useful for chaining.
-
setHttpClient
Sets theOkHttpClientthat will be used by JDAs requester.
This can be used to set things such as connection timeout and proxy.- Parameters:
client- The newOkHttpClientto use- Returns:
- The JDABuilder instance. Useful for chaining.
-
setWebsocketFactory
Sets theWebSocketFactorythat will be used by JDA's websocket client. This can be used to set things such as connection timeout and proxy.- Parameters:
factory- The newWebSocketFactoryto use.- Returns:
- The JDABuilder instance. Useful for chaining.
-
setRateLimitScheduler
Sets theScheduledExecutorServicethat should be used in the JDA rate-limit handler. Changing this can drastically change the JDA behavior for RestAction execution and should be handled carefully. Only change this pool if you know what you're doing.
This automatically disables the automatic shutdown of the rate-limit pool, you can enable it usingsetRateLimitScheduler(executor, true)This is used mostly by the Rate-Limiter to handle backoff delays by using scheduled executions. Besides that it is also used by planned execution for
RestAction.queueAfter(long, TimeUnit)and similar methods. Requests are handed off to theelastic poolfor blocking execution.Default:
ScheduledThreadPoolExecutorwith 2 threads.- Parameters:
pool- The thread-pool to use for rate-limit handling- Returns:
- The JDABuilder instance. Useful for chaining.
-
setRateLimitScheduler
@Nonnull public JDABuilder setRateLimitScheduler(@Nullable ScheduledExecutorService pool, boolean automaticShutdown) Sets theScheduledExecutorServicethat should be used in the JDA rate-limit handler. Changing this can drastically change the JDA behavior for RestAction execution and should be handled carefully. Only change this pool if you know what you're doing.This is used mostly by the Rate-Limiter to handle backoff delays by using scheduled executions. Besides that it is also used by planned execution for
RestAction.queueAfter(long, TimeUnit)and similar methods. Requests are handed off to theelastic poolfor blocking execution.Default:
ScheduledThreadPoolExecutorwith 2 threads.- Parameters:
pool- The thread-pool to use for rate-limit handlingautomaticShutdown- WhetherJDA.shutdown()should shutdown this pool- Returns:
- The JDABuilder instance. Useful for chaining.
-
setRateLimitElastic
Sets theExecutorServicethat should be used in the JDA request handler. Changing this can drastically change the JDA behavior for RestAction execution and should be handled carefully. Only change this pool if you know what you're doing.
This automatically disables the automatic shutdown of the rate-limit elastic pool, you can enable it usingsetRateLimitElastic(executor, true)This is used mostly by the Rate-Limiter to execute the blocking HTTP requests at runtime.
Default:
Executors.newCachedThreadPool().- Parameters:
pool- The thread-pool to use for executing http requests- Returns:
- The JDABuilder instance. Useful for chaining.
-
setRateLimitElastic
@Nonnull public JDABuilder setRateLimitElastic(@Nullable ExecutorService pool, boolean automaticShutdown) Sets theExecutorServicethat should be used in the JDA request handler. Changing this can drastically change the JDA behavior for RestAction execution and should be handled carefully. Only change this pool if you know what you're doing.This is used mostly by the Rate-Limiter to execute the blocking HTTP requests at runtime.
Default:
Executors.newCachedThreadPool().- Parameters:
pool- The thread-pool to use for executing http requestsautomaticShutdown- WhetherJDA.shutdown()should shutdown this pool- Returns:
- The JDABuilder instance. Useful for chaining.
-
setGatewayPool
Sets theScheduledExecutorServiceused by the main WebSocket connection for workers. These workers spend most of their lifetime sleeping because they only activate for sending messages over the gateway.
Only change this pool if you know what you're doing.
This automatically disables the automatic shutdown of the main-ws pool, you can enable it usingsetGatewayPool(pool, true)This is used to send various forms of session updates such as:
- Voice States - (Dis-)Connecting from channels
- Presence - Changing current activity or online status
- Guild Setup - Requesting Members of newly joined guilds
- Heartbeats - Regular updates to keep the connection alive (usually once a minute)
Default:
ScheduledThreadPoolExecutorwith 1 thread- Parameters:
pool- The thread-pool to use for WebSocket workers- Returns:
- The JDABuilder instance. Useful for chaining.
-
setGatewayPool
@Nonnull public JDABuilder setGatewayPool(@Nullable ScheduledExecutorService pool, boolean automaticShutdown) Sets theScheduledExecutorServiceused by the main WebSocket connection for workers. These workers spend most of their lifetime sleeping because they only activate for sending messages over the gateway.
Only change this pool if you know what you're doing.This is used to send various forms of session updates such as:
- Voice States - (Dis-)Connecting from channels
- Presence - Changing current activity or online status
- Guild Setup - Requesting Members of newly joined guilds
- Heartbeats - Regular updates to keep the connection alive (usually once a minute)
Default:
ScheduledThreadPoolExecutorwith 1 thread- Parameters:
pool- The thread-pool to use for WebSocket workersautomaticShutdown- WhetherJDA.shutdown()should shutdown this pool- Returns:
- The JDABuilder instance. Useful for chaining.
-
setCallbackPool
Sets theExecutorServicethat should be used in the JDA callback handler which mostly consists ofRestActioncallbacks. By default JDA will useForkJoinPool.commonPool()
Only change this pool if you know what you're doing.
This automatically disables the automatic shutdown of the callback pool, you can enable it usingsetCallbackPool(executor, true)This is used to handle callbacks of
RestAction.queue(), similarly it is used to finishRestAction.submit()andRestAction.complete()tasks which build on queue.Default:
ForkJoinPool.commonPool()- Parameters:
executor- The thread-pool to use for callback handling- Returns:
- The JDABuilder instance. Useful for chaining.
-
setCallbackPool
@Nonnull public JDABuilder setCallbackPool(@Nullable ExecutorService executor, boolean automaticShutdown) Sets theExecutorServicethat should be used in the JDA callback handler which mostly consists ofRestActioncallbacks. By default JDA will useForkJoinPool.commonPool()
Only change this pool if you know what you're doing.This is used to handle callbacks of
RestAction.queue(), similarly it is used to finishRestAction.submit()andRestAction.complete()tasks which build on queue.Default:
ForkJoinPool.commonPool()- Parameters:
executor- The thread-pool to use for callback handlingautomaticShutdown- WhetherJDA.shutdown()should shutdown this executor- Returns:
- The JDABuilder instance. Useful for chaining.
-
setEventPool
Sets theExecutorServicethat should be used by the event proxy to schedule events. This will be done on the calling thread by default.The executor will not be shutdown automatically when JDA is shutdown. To shut it down automatically use
setEventPool(ExecutorService, boolean).- Parameters:
executor- The executor for the event proxy, or null to use calling thread- Returns:
- The JDABuilder instance. Useful for chaining.
- Since:
- 4.2.0
-
setEventPool
@Nonnull public JDABuilder setEventPool(@Nullable ExecutorService executor, boolean automaticShutdown) Sets theExecutorServicethat should be used by the event proxy to schedule events. This will be done on the calling thread by default.- Parameters:
executor- The executor for the event proxy, or null to use calling threadautomaticShutdown- True, if the executor should be shutdown when JDA shuts down- Returns:
- The JDABuilder instance. Useful for chaining.
- Since:
- 4.2.0
-
setAudioPool
Sets theScheduledExecutorServiceused by the audio WebSocket connection. Used for sending keepalives and closing the connection.
Only change this pool if you know what you're doing.Default:
ScheduledThreadPoolExecutorwith 1 thread- Parameters:
pool- The thread-pool to use for the audio WebSocket- Returns:
- The JDABuilder instance. Useful for chaining.
- Since:
- 4.2.1
-
setAudioPool
@Nonnull public JDABuilder setAudioPool(@Nullable ScheduledExecutorService pool, boolean automaticShutdown) Sets theScheduledExecutorServiceused by the audio WebSocket connection. Used for sending keepalives and closing the connection.
Only change this pool if you know what you're doing.Default:
ScheduledThreadPoolExecutorwith 1 thread- Parameters:
pool- The thread-pool to use for the audio WebSocketautomaticShutdown- WhetherJDA.shutdown()should shutdown this pool- Returns:
- The JDABuilder instance. Useful for chaining.
- Since:
- 4.2.1
-
setBulkDeleteSplittingEnabled
If enabled, JDA will separate the bulk delete event into individual delete events, but this isn't as efficient as handling a single event would be. It is recommended that BulkDelete Splitting be disabled and that the developer should instead handle theMessageBulkDeleteEventDefault: true (enabled)
- Parameters:
enabled- True - The MESSAGE_DELETE_BULK will be split into multiple individual MessageDeleteEvents.- Returns:
- The JDABuilder instance. Useful for chaining.
-
setEnableShutdownHook
Enables/Disables the use of a Shutdown hook to clean up JDA.
When the Java program closes shutdown hooks are run. This is used as a last-second cleanup attempt by JDA to properly close connections.Default: true (enabled)
- Parameters:
enable- True (default) - use shutdown hook to clean up JDA if the Java program is closed.- Returns:
- Return the
JDABuilderinstance. Useful for chaining.
-
setAutoReconnect
Sets whether or not JDA should try to reconnect if a connection-error is encountered.
This will use an incremental reconnect (timeouts are increased each time an attempt fails).Default: true (enabled)
- Parameters:
autoReconnect- If true - enables autoReconnect- Returns:
- The JDABuilder instance. Useful for chaining.
-
setEventManager
Changes the internally used EventManager.
There are 2 provided Implementations:InterfacedEventManagerwhich uses the InterfaceEventListener(tip: use theListenerAdapter).
This is the default EventManager.AnnotatedEventManagerwhich uses the Annotation@SubscribeEventto mark the methods that listen for events.
You can also create your own EventManager (SeeIEventManager).- Parameters:
manager- The newIEventManagerto use.- Returns:
- The JDABuilder instance. Useful for chaining.
-
setAudioSendFactory
Changes the factory used to createIAudioSendSystemobjects which handle the sending loop for audio packets.
By default, JDA usesDefaultSendFactory.- Parameters:
factory- The newIAudioSendFactoryto be used when creating newIAudioSendSystemobjects.- Returns:
- The JDABuilder instance. Useful for chaining.
-
setIdle
Sets whether or not we should mark our session as afk
This value can be changed at any time in thePresencefrom a JDA instance.- Parameters:
idle- boolean value that will be provided with our IDENTIFY package to mark our session as afk or not. (default false)- Returns:
- The JDABuilder instance. Useful for chaining.
- See Also:
-
setActivity
Sets theActivityfor our session.
This value can be changed at any time in thePresencefrom a JDA instance.Hint: You can create an
Activityobject usingActivity.playing(String)orActivity.streaming(String, String).- Parameters:
activity- An instance ofActivity(null allowed)- Returns:
- The JDABuilder instance. Useful for chaining.
- See Also:
-
setStatus
Sets theOnlineStatusour connection will display.
This value can be changed at any time in thePresencefrom a JDA instance.- Parameters:
status- Not-null OnlineStatus (default online)- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- if the provided OnlineStatus is null orUNKNOWN- See Also:
-
addEventListeners
Adds all provided listeners to the list of listeners that will be used to populate theJDAobject.
This uses theInterfacedEventListenerby default.
To switch to theAnnotatedEventManager, usesetEventManager(new AnnotatedEventManager()).Note: When using the
InterfacedEventListener(default), given listener(s) must be instance ofEventListener!- Parameters:
listeners- The listener(s) to add to the list.- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If either listeners or one of it's objects isnull.- See Also:
-
removeEventListeners
Removes all provided listeners from the list of listeners.- Parameters:
listeners- The listener(s) to remove from the list.- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If either listeners or one of it's objects isnull.- See Also:
-
setMaxReconnectDelay
Sets the maximum amount of time that JDA will back off to wait when attempting to reconnect the MainWebsocket.
Provided value must be 32 or greater.Default:
900- Parameters:
maxReconnectDelay- The maximum amount of time that JDA will wait between reconnect attempts in seconds.- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- Thrown if the providedmaxReconnectDelayis less than 32.
-
useSharding
This will enable sharding mode for JDA.
In sharding mode, guilds are split up and assigned one of multiple shards (clients).
The shardId that receives all stuff related to given bot is calculated as follows: shardId == (guildId >> 22) % shardTotal;
PMs are only sent to shard 0.Please note, that a shard will not know about guilds which are not assigned to it.
- Parameters:
shardId- The id of this shard (starting at 0).shardTotal- The number of overall shards.- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If the provided shard configuration is invalid (0 <= shardId < shardTotalwithshardTotal > 0)- See Also:
-
setSessionController
Sets theSessionControllerfor this JDABuilder instance. This can be used to sync behaviour and state between shards of a bot and should be one and the same instance on all builders for the shards.
WhenuseSharding(int, int)is enabled, this is set by default.When set, this allows the builder to build shards with respect to the login ratelimit automatically.
- Parameters:
controller- TheSessionControllerto use- Returns:
- The JDABuilder instance. Useful for chaining.
- See Also:
-
setVoiceDispatchInterceptor
@Nonnull public JDABuilder setVoiceDispatchInterceptor(@Nullable VoiceDispatchInterceptor interceptor) Configures a custom voice dispatch handler which handles audio connections.- Parameters:
interceptor- The new voice dispatch handler, or null to use the default- Returns:
- The JDABuilder instance. Useful for chaining.
- Since:
- 4.0.0
- See Also:
-
setChunkingFilter
TheChunkingFilterto filter which guilds should use member chunking.Use
setMemberCachePolicy(MemberCachePolicy)to configure which members to keep in cache from chunking.- Parameters:
filter- The filter to apply- Returns:
- The JDABuilder instance. Useful for chaining.
- Since:
- 4.1.0
- See Also:
-
setDisabledIntents
@Nonnull public JDABuilder setDisabledIntents(@Nonnull GatewayIntent intent, @Nonnull GatewayIntent... intents) Configures which events will be disabled. Bots which did not enable presence/member updates in the developer dashboard are required to disableGatewayIntent.GUILD_PRESENCESandGatewayIntent.GUILD_MEMBERS!It is not recommended to disable
GatewayIntent.GUILD_MEMBERSwhen usingMemberCachePolicy.ALLas the members cannot be removed from cache by a leave event without this intent.If you disable certain intents you also have to disable related
CacheFlags. This can be achieved usingdisableCache(CacheFlag, CacheFlag...). The required intents for each flag are documented in theCacheFlagenum.- Parameters:
intent- The first intent to disableintents- Any other intents to disable- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If null is provided- Since:
- 4.2.0
- See Also:
-
setDisabledIntents
Configures which events will be disabled. Bots which did not enable presence/member updates in the developer dashboard are required to disableGatewayIntent.GUILD_PRESENCESandGatewayIntent.GUILD_MEMBERS!It is not recommended to disable
GatewayIntent.GUILD_MEMBERSwhen usingMemberCachePolicy.ALLas the members cannot be removed from cache by a leave event without this intent.If you disable certain intents you also have to disable related
CacheFlags. This can be achieved usingdisableCache(CacheFlag, CacheFlag...). The required intents for each flag are documented in theCacheFlagenum.- Parameters:
intents- The intents to disable (default: none)- Returns:
- The JDABuilder instance. Useful for chaining.
- Since:
- 4.2.0
- See Also:
-
disableIntents
Disable the specifiedGatewayIntents.
This will not enable any currently unset intents.If you disable certain intents you also have to disable related
CacheFlags. This can be achieved usingdisableCache(CacheFlag, CacheFlag...). The required intents for each flag are documented in theCacheFlagenum.- Parameters:
intents- The intents to disable- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If provided with null- See Also:
-
disableIntents
@Nonnull public JDABuilder disableIntents(@Nonnull GatewayIntent intent, @Nonnull GatewayIntent... intents) Disable the specifiedGatewayIntents.
This will not enable any currently unset intents.If you disable certain intents you also have to disable related
CacheFlags. This can be achieved usingdisableCache(CacheFlag, CacheFlag...). The required intents for each flag are documented in theCacheFlagenum.- Parameters:
intent- The intent to disableintents- Other intents to disable- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If provided with null- See Also:
-
setEnabledIntents
@Nonnull public JDABuilder setEnabledIntents(@Nonnull GatewayIntent intent, @Nonnull GatewayIntent... intents) Configures which events will be enabled. Bots which did not enable presence/member updates in the developer dashboard are required to disableGatewayIntent.GUILD_PRESENCESandGatewayIntent.GUILD_MEMBERS!It is not recommended to disable
GatewayIntent.GUILD_MEMBERSwhen usingMemberCachePolicy.ALLas the members cannot be removed from cache by a leave event without this intent.If you disable certain intents you also have to disable related
CacheFlags. This can be achieved usingdisableCache(CacheFlag, CacheFlag...). The required intents for each flag are documented in theCacheFlagenum.- Parameters:
intent- The intent to enableintents- Any other intents to enable- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If null is provided- Since:
- 4.2.0
- See Also:
-
setEnabledIntents
Configures which events will be enabled. Bots which did not enable presence/member updates in the developer dashboard are required to disableGatewayIntent.GUILD_PRESENCESandGatewayIntent.GUILD_MEMBERS!It is not recommended to disable
GatewayIntent.GUILD_MEMBERSwhen usingMemberCachePolicy.ALLas the members cannot be removed from cache by a leave event without this intent.If you disable certain intents you also have to disable related
CacheFlags. This can be achieved usingdisableCache(CacheFlag, CacheFlag...). The required intents for each flag are documented in theCacheFlagenum.- Parameters:
intents- The intents to enable (default: all)- Returns:
- The JDABuilder instance. Useful for chaining.
- Since:
- 4.2.0
- See Also:
-
enableIntents
Enable the specifiedGatewayIntents.
This will not disable any currently set intents.- Parameters:
intents- The intents to enable- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If provided with null- See Also:
-
enableIntents
@Nonnull public JDABuilder enableIntents(@Nonnull GatewayIntent intent, @Nonnull GatewayIntent... intents) Enable the specifiedGatewayIntents.
This will not disable any currently set intents.- Parameters:
intent- The intent to enableintents- Other intents to enable- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If provided with null- See Also:
-
setLargeThreshold
Decides the total number of members at which a guild should start to use lazy loading.
This is limited to a number between 50 and 250 (inclusive). If thechunking filteris set toChunkingFilter.ALLthis should be set to250(default) to minimize the amount of guilds that need to request members.- Parameters:
threshold- The threshold in[50, 250]- Returns:
- The JDABuilder instance. Useful for chaining.
- Since:
- 4.1.0
-
setMaxBufferSize
The maximum size, in bytes, of the buffer used for decompressing discord payloads.
If the maximum buffer size is exceeded a new buffer will be allocated instead.
Setting this toInteger.MAX_VALUEwould imply the buffer will never be resized unless memory starvation is imminent.
Setting this to0would imply the buffer would need to be allocated again for every payload (not recommended).Default:
2048- Parameters:
bufferSize- The maximum size the buffer should allow to retain- Returns:
- The JDABuilder instance. Useful for chaining.
- Throws:
IllegalArgumentException- If the provided buffer size is negative
-
build
Builds a newJDAinstance and uses the provided token to start the login process.
The login process runs in a different thread, so while this will return immediately,JDAhas not finished loading, thus manyJDAmethods have the chance to return incorrect information. For exampleJDA.getGuilds()might return an empty list orJDA.getUserById(long)might return null for arbitrary user IDs.If you wish to be sure that the
JDAinformation is correct, please useJDA.awaitReady()or register anEventListenerto listen for theReadyEvent.- Returns:
- A
JDAinstance that has started the login process. It is unknown as to whether or not loading has finished when this returns. - Throws:
InvalidTokenException- If the provided token is invalid.IllegalArgumentException- If the provided token is empty or null. Or the provided intents/cache configuration is not possible.- See Also:
-