Class JDABuilder


  • public class JDABuilder
    extends java.lang.Object
    Used to create new 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.

    • Constructor Detail

      • JDABuilder

        public JDABuilder​(java.lang.String token)
        Creates a JDABuilder with the predefined token.
        Parameters:
        token - The bot token to use
        See Also:
        setToken(String)
      • JDABuilder

        @Incubating
        public JDABuilder​(AccountType accountType)
        Creates a completely empty JDABuilder.
        If you use this, you need to set the token using setToken(String) before calling build()
        Parameters:
        accountType - The AccountType.
        Throws:
        java.lang.IllegalArgumentException - If the given AccountType is null
        Incubating:
        Due to policy changes for the discord API this method may not be provided in a future version
    • Method Detail

      • setEnabledCacheFlags

        public JDABuilder setEnabledCacheFlags​(java.util.EnumSet<CacheFlag> flags)
        Flags used to enable selective parts of the JDA cache to reduce the runtime memory footprint.
        It is highly recommended to use setDisabledCacheFlags(EnumSet) instead for backwards compatibility. We might add more flags in the future which you then effectively disable when updating and not changing your setting here.
        Parameters:
        flags - EnumSet containing the flags for cache services that should be enabled
        Returns:
        The JDABuilder instance. Useful for chaining.
        See Also:
        setDisabledCacheFlags(EnumSet)
      • setDisabledCacheFlags

        public JDABuilder setDisabledCacheFlags​(java.util.EnumSet<CacheFlag> flags)
        Flags used to disable parts of the JDA cache to reduce the runtime memory footprint.
        Shortcut for setEnabledCacheFlags(EnumSet.complementOf(flags))
        Parameters:
        flags - EnumSet containing the flags for cache services that should be disabled
        Returns:
        The JDABuilder instance. Useful for chaining.
      • setContextMap

        public JDABuilder setContextMap​(java.util.concurrent.ConcurrentMap<java.lang.String,​java.lang.String> map)
        Sets the MDC mappings to use in JDA.
        If sharding is enabled JDA will automatically add a jda.shard context with the format [SHARD_ID / TOTAL] where SHARD_ID and TOTAL are the shard configuration. Additionally it will provide context for the id via jda.shard.id and the total via jda.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, or null to reset
        Returns:
        The JDABuilder instance. Useful for chaining.
        See Also:
        MDC Javadoc, setContextEnabled(boolean)
      • setContextEnabled

        public JDABuilder setContextEnabled​(boolean enable)
        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:
        MDC Javadoc, setContextMap(java.util.concurrent.ConcurrentMap)
      • setCompressionEnabled

        public JDABuilder setCompressionEnabled​(boolean enable)
        Enable stream-compression on 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.
        Default: true

        We recommend to keep this enabled 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:
        enable - True, if the gateway connection should use compression
        Returns:
        The JDABuilder instance. Useful for chaining
        See Also:
        Official Discord Documentation - Transport Compression
      • setRequestTimeoutRetry

        public JDABuilder setRequestTimeoutRetry​(boolean retryOnTimeout)
        Whether the Requester should retry when a SocketTimeoutException occurs.
        Default: true

        This 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

        public JDABuilder setToken​(java.lang.String token)
        Sets the token that will be used by the JDA instance to log in when build() is called.

        For AccountType.BOT

        1. Go to your Discord Applications
        2. Create or select an already existing application
        3. Verify that it has already been turned into a Bot. If you see the "Create a Bot User" button, click it.
        4. 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

        public JDABuilder setHttpClientBuilder​(okhttp3.OkHttpClient.Builder builder)
        Sets the Builder that will be used by JDAs requester.
        This can be used to set things such as connection timeout and proxy.
        Parameters:
        builder - The new Builder to use
        Returns:
        The JDABuilder instance. Useful for chaining.
      • setHttpClient

        public JDABuilder setHttpClient​(okhttp3.OkHttpClient client)
        Sets the OkHttpClient that will be used by JDAs requester.
        This can be used to set things such as connection timeout and proxy.
        Parameters:
        client - The new OkHttpClient to use
        Returns:
        The JDABuilder instance. Useful for chaining.
      • setWebsocketFactory

        public JDABuilder setWebsocketFactory​(com.neovisionaries.ws.client.WebSocketFactory factory)
        Sets the WebSocketFactory that will be used by JDA's websocket client. This can be used to set things such as connection timeout and proxy.
        Parameters:
        factory - The new WebSocketFactory to use.
        Returns:
        The JDABuilder instance. Useful for chaining.
      • setCorePoolSize

        public JDABuilder setCorePoolSize​(int size)
        Sets the core pool size for the global JDA ScheduledExecutorService which is used in various locations throughout the JDA instance created by this builder. (Default: 5)
        Note: This has no effect if you set a pool using setRateLimitPool(ScheduledExecutorService).
        Parameters:
        size - The core pool size for the global JDA executor
        Returns:
        The JDABuilder instance. Useful for chaining.
        Throws:
        java.lang.IllegalArgumentException - If the specified core pool size is not positive
      • setRateLimitPool

        public JDABuilder setRateLimitPool​(java.util.concurrent.ScheduledExecutorService pool)
        Sets the ScheduledExecutorService that 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 using setRateLimitPool(executor, true)
        Parameters:
        pool - The thread-pool to use for rate-limit handling
        Returns:
        The JDABuilder instance. Useful for chaining.
      • setRateLimitPool

        public JDABuilder setRateLimitPool​(java.util.concurrent.ScheduledExecutorService pool,
                                           boolean automaticShutdown)
        Sets the ScheduledExecutorService that 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.
        Parameters:
        pool - The thread-pool to use for rate-limit handling
        automaticShutdown - Whether JDA.shutdown() should shutdown this pool
        Returns:
        The JDABuilder instance. Useful for chaining.
      • setGatewayPool

        public JDABuilder setGatewayPool​(java.util.concurrent.ScheduledExecutorService pool)
        Sets the ScheduledExecutorService used 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 using setGatewayPool(pool, true)
        Parameters:
        pool - The thread-pool to use for WebSocket workers
        Returns:
        The JDABuilder instance. Useful for chaining.
      • setGatewayPool

        public JDABuilder setGatewayPool​(java.util.concurrent.ScheduledExecutorService pool,
                                         boolean automaticShutdown)
        Sets the ScheduledExecutorService used 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.
        Parameters:
        pool - The thread-pool to use for WebSocket workers
        automaticShutdown - Whether JDA.shutdown() should shutdown this pool
        Returns:
        The JDABuilder instance. Useful for chaining.
      • setCallbackPool

        public JDABuilder setCallbackPool​(java.util.concurrent.ExecutorService executor)
        Sets the ExecutorService that should be used in the JDA callback handler which mostly consists of RestAction callbacks. By default JDA will use ForkJoinPool.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 using setCallbackPool(executor, true)
        Parameters:
        executor - The thread-pool to use for callback handling
        Returns:
        The JDABuilder instance. Useful for chaining.
      • setCallbackPool

        public JDABuilder setCallbackPool​(java.util.concurrent.ExecutorService executor,
                                          boolean automaticShutdown)
        Sets the ExecutorService that should be used in the JDA callback handler which mostly consists of RestAction callbacks. By default JDA will use ForkJoinPool.commonPool()
        Only change this pool if you know what you're doing.
        Parameters:
        executor - The thread-pool to use for callback handling
        automaticShutdown - Whether JDA.shutdown() should shutdown this executor
        Returns:
        The JDABuilder instance. Useful for chaining.
      • setAudioEnabled

        public JDABuilder setAudioEnabled​(boolean enabled)
        Enables/Disables Voice functionality.
        This is useful, if your current system doesn't support Voice and you do not need it.

        Default: true (enabled)

        Parameters:
        enabled - True - enables voice support.
        Returns:
        The JDABuilder instance. Useful for chaining.
      • setBulkDeleteSplittingEnabled

        public JDABuilder 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. It is recommended that BulkDelete Splitting be disabled and that the developer should instead handle the MessageBulkDeleteEvent

        Default: true (enabled)

        Parameters:
        enabled - True - The MESSAGE_DELETE_BULK will be split into multiple individual MessageDeleteEvents.
        Returns:
        The JDABuilder instance. Useful for chaining.
      • setEnableShutdownHook

        public JDABuilder setEnableShutdownHook​(boolean enable)
        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 JDABuilder instance. Useful for chaining.
      • setAutoReconnect

        public JDABuilder setAutoReconnect​(boolean autoReconnect)
        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.
      • setIdle

        public JDABuilder setIdle​(boolean idle)
        Sets whether or not we should mark our session as afk
        This value can be changed at any time in the Presence from 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:
        Presence#setIdle(boolean)
      • setStatus

        public JDABuilder setStatus​(OnlineStatus status)
        Sets the OnlineStatus our connection will display.
        This value can be changed at any time in the Presence from a JDA instance.

        Note:This will not take affect for AccountType.CLIENT if the status specified in the user_settings is not "online" as it is overriding our identify status.

        Parameters:
        status - Not-null OnlineStatus (default online)
        Returns:
        The JDABuilder instance. Useful for chaining.
        Throws:
        java.lang.IllegalArgumentException - if the provided OnlineStatus is null or UNKNOWN
        See Also:
        Presence.setStatus(OnlineStatus)
      • removeEventListener

        public JDABuilder removeEventListener​(java.lang.Object... listeners)
        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:
        java.lang.IllegalArgumentException - If either listeners or one of it's objects is null.
        See Also:
        JDA.removeEventListener(Object...)
      • setMaxReconnectDelay

        public JDABuilder setMaxReconnectDelay​(int maxReconnectDelay)
        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.
        Parameters:
        maxReconnectDelay - The maximum amount of time that JDA will wait between reconnect attempts in seconds.
        Returns:
        The JDABuilder instance. Useful for chaining.
        Throws:
        java.lang.IllegalArgumentException - Thrown if the provided maxReconnectDelay is less than 32.
      • useSharding

        public JDABuilder useSharding​(int shardId,
                                      int shardTotal)
        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.

        It is not possible to use sharding with an account for AccountType.CLIENT!

        Parameters:
        shardId - The id of this shard (starting at 0).
        shardTotal - The number of overall shards.
        Returns:
        The JDABuilder instance. Useful for chaining.
        Throws:
        AccountTypeException - If this is used on a JDABuilder for AccountType.CLIENT
        java.lang.IllegalArgumentException - If the provided shard configuration is invalid (0 <= shardId < shardTotal with shardTotal > 0)
        See Also:
        JDA.getShardInfo(), ShardManager
      • setSessionController

        public JDABuilder setSessionController​(SessionController controller)
        Sets the SessionController for 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.
        When useSharding(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 - The SessionController to use
        Returns:
        The JDABuilder instance. Useful for chaining.
        See Also:
        SessionControllerAdapter
      • buildAsync

        @Deprecated
        @DeprecatedSince("3.8.0")
        @ReplaceWith("build()")
        public JDA buildAsync()
                       throws javax.security.auth.login.LoginException
        Deprecated.
        Use build() instead
        Builds a new JDA instance and uses the provided token to start the login process.
        The login process runs in a different thread, so while this will return immediately, JDA has not finished loading, thus many JDA methods have the chance to return incorrect information.
        The main use of this method is to start the JDA connect process and do other things in parallel while startup is being performed like database connection or local resource loading.

        If you wish to be sure that the JDA information is correct, please use buildBlocking() or register an EventListener to listen for the ReadyEvent .

        Returns:
        A JDA instance that has started the login process. It is unknown as to whether or not loading has finished when this returns.
        Throws:
        javax.security.auth.login.LoginException - If the provided token is invalid.
        java.lang.IllegalArgumentException - If the provided token is empty or null.
      • buildBlocking

        @Deprecated
        @DeprecatedSince("3.8.0")
        @ReplaceWith("build().awaitStatus(Status)")
        public JDA buildBlocking​(JDA.Status status)
                          throws javax.security.auth.login.LoginException,
                                 java.lang.InterruptedException
        Deprecated.
        Builds a new JDA instance and uses the provided token to start the login process.
        This method will block until JDA has reached the specified connection status.

        Login Cycle

        1. INITIALIZING
        2. INITIALIZED
        3. LOGGING_IN
        4. CONNECTING_TO_WEBSOCKET
        5. IDENTIFYING_SESSION
        6. AWAITING_LOGIN_CONFIRMATION
        7. LOADING_SUBSYSTEMS
        8. CONNECTED
        Parameters:
        status - The Status to wait for, once JDA has reached the specified stage of the startup cycle this method will return.
        Returns:
        A JDA Object that is guaranteed to be logged in and finished loading.
        Throws:
        javax.security.auth.login.LoginException - If the provided token is invalid.
        java.lang.IllegalArgumentException - If the provided token is empty or null or the provided status is not part of the login cycle.
        java.lang.InterruptedException - If an interrupt request is received while waiting for JDA to finish logging in. This would most likely be caused by a JVM shutdown request.
      • buildBlocking

        @Deprecated
        @DeprecatedSince("3.8.0")
        @ReplaceWith("build().awaitReady()")
        public JDA buildBlocking()
                          throws javax.security.auth.login.LoginException,
                                 java.lang.InterruptedException
        Deprecated.
        Use build() and JDA.awaitReady() instead
        Builds a new JDA instance and uses the provided token to start the login process.
        This method will block until JDA has logged in and finished loading all resources. This is an alternative to using ReadyEvent.
        Returns:
        A JDA Object that is guaranteed to be logged in and finished loading.
        Throws:
        javax.security.auth.login.LoginException - If the provided token is invalid.
        java.lang.IllegalArgumentException - If the provided token is empty or null.
        java.lang.InterruptedException - If an interrupt request is received while waiting for JDA to finish logging in. This would most likely be caused by a JVM shutdown request.
      • build

        public JDA build()
                  throws javax.security.auth.login.LoginException
        Builds a new JDA instance and uses the provided token to start the login process.
        The login process runs in a different thread, so while this will return immediately, JDA has not finished loading, thus many JDA methods have the chance to return incorrect information.
        The main use of this method is to start the JDA connect process and do other things in parallel while startup is being performed like database connection or local resource loading.

        If you wish to be sure that the JDA information is correct, please use JDA.awaitReady() or register an EventListener to listen for the ReadyEvent.

        Returns:
        A JDA instance that has started the login process. It is unknown as to whether or not loading has finished when this returns.
        Throws:
        javax.security.auth.login.LoginException - If the provided token is invalid.
        java.lang.IllegalArgumentException - If the provided token is empty or null.