Class JDABuilder


  • public class JDABuilder
    extends 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.

    • Method Detail

      • setRawEventsEnabled

        @Nonnull
        public JDABuilder setRawEventsEnabled​(boolean enable)
        Whether JDA should fire RawGatewayEvent for every discord event.
        Default: false
        Parameters:
        enable - True, if JDA should fire RawGatewayEvent.
        Returns:
        The JDABuilder instance. Useful for chaining.
        Since:
        4.0.0
      • setRelativeRateLimit

        @Nonnull
        public JDABuilder setRelativeRateLimit​(boolean enable)
        Whether the rate-limit should be relative to the current time plus latency.
        By default we use the X-RateLimit-Rest-After header to determine when a rate-limit is no longer imminent. This has the disadvantage that it might wait longer than needed due to the latency which is ignored by the reset-after relative delay.

        When disabled, we will use the X-RateLimit-Reset absolute timestamp instead which accounts for latency but requires a properly NTP synchronized clock to be present. If your system does have this feature you might gain a little quicker rate-limit handling than the default allows.

        Default: true

        Parameters:
        enable - True, if the relative X-RateLimit-Reset-After header should be used.
        Returns:
        The JDABuilder instance. Useful for chaining.
        Since:
        4.1.0
      • setEnabledCacheFlags

        @Nonnull
        public JDABuilder setEnabledCacheFlags​(@Nullable
                                               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

        @Nonnull
        public JDABuilder setDisabledCacheFlags​(@Nullable
                                                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

        @Nonnull
        public JDABuilder setContextMap​(@Nullable
                                        ConcurrentMap<String,​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)
      • setCompression

        @Nonnull
        public JDABuilder setCompression​(@Nonnull
                                         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. Compression can be entirely disabled by setting this to Compression.NONE.
        Default: Compression.ZLIB

        We 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:
        Official Discord Documentation - Transport Compression
      • setRequestTimeoutRetry

        @Nonnull
        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

        @Nonnull
        public JDABuilder setToken​(@Nullable
                                   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

        @Nonnull
        public JDABuilder setHttpClientBuilder​(@Nullable
                                               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

        @Nonnull
        public JDABuilder setHttpClient​(@Nullable
                                        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.
      • setRateLimitPool

        @Nonnull
        public JDABuilder setRateLimitPool​(@Nullable
                                           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)

        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.

        Default: ScheduledThreadPoolExecutor with 5 threads.

        Parameters:
        pool - The thread-pool to use for rate-limit handling
        Returns:
        The JDABuilder instance. Useful for chaining.
      • setRateLimitPool

        @Nonnull
        public JDABuilder setRateLimitPool​(@Nullable
                                           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.

        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.

        Default: ScheduledThreadPoolExecutor with 5 threads.

        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

        @Nonnull
        public JDABuilder setGatewayPool​(@Nullable
                                         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)

        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)
        When nothing has to be sent the pool will only be used every 500 milliseconds to check the queue for new payloads. Once a new payload is sent we switch to "rapid mode" which means more tasks will be submitted until no more payloads have to be sent.

        Default: ScheduledThreadPoolExecutor with 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 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 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)
        When nothing has to be sent the pool will only be used every 500 milliseconds to check the queue for new payloads. Once a new payload is sent we switch to "rapid mode" which means more tasks will be submitted until no more payloads have to be sent.

        Default: ScheduledThreadPoolExecutor with 1 thread

        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.
      • setBulkDeleteSplittingEnabled

        @Nonnull
        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

        @Nonnull
        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

        @Nonnull
        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

        @Nonnull
        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)
      • setMaxReconnectDelay

        @Nonnull
        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:
        IllegalArgumentException - Thrown if the provided maxReconnectDelay is less than 32.
      • useSharding

        @Nonnull
        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
        IllegalArgumentException - If the provided shard configuration is invalid (0 <= shardId < shardTotal with shardTotal > 0)
        See Also:
        JDA.getShardInfo(), ShardManager
      • setSessionController

        @Nonnull
        public JDABuilder setSessionController​(@Nullable
                                               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
      • 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:
        VoiceDispatchInterceptor
      • setGuildSubscriptionsEnabled

        @Nonnull
        public JDABuilder setGuildSubscriptionsEnabled​(boolean enabled)
        Enable typing and presence update events.
        These events cover the majority of traffic happening on the gateway and thus cause a lot of bandwidth usage. Disabling these events means the cache for users might become outdated since user properties are only updated by presence updates.
        Default: true

        Notice

        This disables the majority of member cache and related events. If anything in your project relies on member state you should keep this enabled.
        Parameters:
        enabled - True, if guild subscriptions should be enabled
        Returns:
        The JDABuilder instance. Useful for chaining.
        Since:
        4.1.0
      • setLargeThreshold

        @Nonnull
        public JDABuilder setLargeThreshold​(int threshold)
        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 the chunking filter is set to ChunkingFilter.ALL this should be set to 250 (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
      • build

        @Nonnull
        public JDA build()
                  throws 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. For example JDA.getGuilds() might return an empty list or JDA.getUserById(long) might return null for arbitrary user IDs.

        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:
        LoginException - If the provided token is invalid.
        IllegalArgumentException - If the provided token is empty or null.
        See Also:
        JDA.awaitReady()