Class DefaultShardManagerBuilder


  • public class DefaultShardManagerBuilder
    extends Object
    Used to create new instances of JDA's default ShardManager implementation.

    A single DefaultShardManagerBuilder can be reused multiple times. Each call to build() creates a new ShardManager instance using the same information.

    Since:
    3.4.0
    Author:
    Aljoscha Grebe
    • Constructor Detail

      • DefaultShardManagerBuilder

        public DefaultShardManagerBuilder()
        Creates a completely empty DefaultShardManagerBuilder.
        You need to set the token using setToken(String) before calling build().
    • Method Detail

      • setRawEventsEnabled

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

        @Nonnull
        public DefaultShardManagerBuilder 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 DefaultShardManagerBuilder instance. Useful for chaining.
        Since:
        4.1.0
      • setEnabledCacheFlags

        @Nonnull
        public DefaultShardManagerBuilder setEnabledCacheFlags​(@Nullable
                                                               EnumSet<CacheFlag> flags)
        Flags used to enable 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 DefaultShardManagerBuilder instance. Useful for chaining.
      • setDisabledCacheFlags

        @Nonnull
        public DefaultShardManagerBuilder 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 DefaultShardManagerBuilder instance. Useful for chaining.
      • setContextMap

        @Nonnull
        public DefaultShardManagerBuilder setContextMap​(@Nullable
                                                        IntFunction<? extends ConcurrentMap<String,​String>> provider)
        Sets the MDC mappings provider 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.

        The manager will call this with a shardId and it is recommended to provide a different context map for each shard!
        This automatically switches setContextEnabled(boolean) to true if the provided function is not null!

        Parameters:
        provider - The provider for modifiable context maps to use in JDA, or null to reset
        Returns:
        The DefaultShardManagerBuilder instance. Useful for chaining.
        See Also:
        MDC Javadoc
      • setCompression

        @Nonnull
        public DefaultShardManagerBuilder 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 for the gateway connection
        Returns:
        The DefaultShardManagerBuilder instance. Useful for chaining.
        Throws:
        IllegalArgumentException - If provided with null
        See Also:
        Official Discord Documentation - Transport Compression
      • removeEventListenerProvider

        @Nonnull
        public DefaultShardManagerBuilder removeEventListenerProvider​(@Nonnull
                                                                      IntFunction<Object> listenerProvider)
        Removes the provided listener provider from the list of listener providers.
        Parameters:
        listenerProvider - The listener provider to remove from the list of listener providers.
        Returns:
        The DefaultShardManagerBuilder instance. Useful for chaining.
      • removeEventListenerProviders

        @Nonnull
        public DefaultShardManagerBuilder removeEventListenerProviders​(@Nonnull
                                                                       Collection<IntFunction<Object>> listenerProviders)
        Removes all provided listener providers from the list of listener providers.
        Parameters:
        listenerProviders - The listener provider(s) to remove from the list of listener providers.
        Returns:
        The DefaultShardManagerBuilder instance. Useful for chaining.
      • setAutoReconnect

        @Nonnull
        public DefaultShardManagerBuilder 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 DefaultShardManagerBuilder instance. Useful for chaining.
      • setBulkDeleteSplittingEnabled

        @Nonnull
        public DefaultShardManagerBuilder 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 DefaultShardManagerBuilder instance. Useful for chaining.
      • setEnableShutdownHook

        @Nonnull
        public DefaultShardManagerBuilder setEnableShutdownHook​(boolean enable)
        Enables/Disables the use of a Shutdown hook to clean up the ShardManager and it's JDA instances.
        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 the ShardManager and it's JDA instances if the Java program is closed.
        Returns:
        The DefaultShardManagerBuilder instance. Useful for chaining.
      • setThreadFactory

        @Nonnull
        public DefaultShardManagerBuilder setThreadFactory​(@Nullable
                                                           ThreadFactory threadFactory)
        Sets the ThreadFactory that will be used by the internal executor of the ShardManager.

        Note: This will not affect Threads created by any JDA instance.

        Parameters:
        threadFactory - The ThreadFactory or null to reset to the default value.
        Returns:
        The DefaultShardManagerBuilder instance. Useful for chaining.
      • setGatewayPool

        @Nonnull
        public DefaultShardManagerBuilder setGatewayPool​(@Nullable
                                                         ScheduledExecutorService pool)
        Sets the ScheduledExecutorService that should be used for the JDA main WebSocket workers.
        Only change this pool if you know what you're doing.
        This will override the worker pool provider set from setGatewayPoolProvider(ThreadPoolProvider).
        This automatically disables the automatic shutdown of the main-ws pools, you can enable it using setGatewayPoolProvider(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 (per shard)

        Parameters:
        pool - The thread-pool to use for main WebSocket workers
        Returns:
        The DefaultShardManagerBuilder instance. Useful for chaining.
      • setGatewayPool

        @Nonnull
        public DefaultShardManagerBuilder setGatewayPool​(@Nullable
                                                         ScheduledExecutorService pool,
                                                         boolean automaticShutdown)
        Sets the ScheduledExecutorService that should be used for the JDA main WebSocket workers.
        Only change this pool if you know what you're doing.
        This will override the worker pool provider set from setGatewayPoolProvider(ThreadPoolProvider).

        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 (per shard)

        Parameters:
        pool - The thread-pool to use for main WebSocket workers
        automaticShutdown - Whether JDA.shutdown() should automatically shutdown this pool
        Returns:
        The DefaultShardManagerBuilder instance. Useful for chaining.
      • setGatewayPoolProvider

        @Nonnull
        public DefaultShardManagerBuilder setGatewayPoolProvider​(@Nullable
                                                                 ThreadPoolProvider<? extends ScheduledExecutorService> provider)
        Sets the ScheduledExecutorService that should be used for the JDA main WebSocket workers.
        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 (per shard)

        Parameters:
        provider - The thread-pool provider to use for main WebSocket workers
        Returns:
        The DefaultShardManagerBuilder instance. Useful for chaining.
      • setMaxReconnectDelay

        @Nonnull
        public DefaultShardManagerBuilder 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 DefaultShardManagerBuilder instance. Useful for chaining.
        Throws:
        IllegalArgumentException - Thrown if the provided maxReconnectDelay is less than 32.
      • setShards

        @Nonnull
        public DefaultShardManagerBuilder setShards​(int... shardIds)
        Sets the list of shards the DefaultShardManager should contain.

        This does not have any effect if the total shard count is set to -1 (get recommended shards from discord).

        Parameters:
        shardIds - The list of shard ids
        Returns:
        The DefaultShardManagerBuilder instance. Useful for chaining.
      • setShards

        @Nonnull
        public DefaultShardManagerBuilder setShards​(int minShardId,
                                                    int maxShardId)
        Sets the range of shards the DefaultShardManager should contain. This is useful if you want to split your shards between multiple JVMs or servers.

        This does not have any effect if the total shard count is set to -1 (get recommended shards from discord).

        Parameters:
        minShardId - The lowest shard id the DefaultShardManager should contain
        maxShardId - The highest shard id the DefaultShardManager should contain
        Returns:
        The DefaultShardManagerBuilder instance. Useful for chaining.
        Throws:
        IllegalArgumentException - If either minShardId is negative, maxShardId is lower than shardsTotal or minShardId is lower than or equal to maxShardId
      • setShards

        @Nonnull
        public DefaultShardManagerBuilder setShards​(@Nonnull
                                                    Collection<Integer> shardIds)
        Sets the range of shards the DefaultShardManager should contain. This is useful if you want to split your shards between multiple JVMs or servers.

        This does not have any effect if the total shard count is set to -1 (get recommended shards from discord).

        Parameters:
        shardIds - The list of shard ids
        Returns:
        The DefaultShardManagerBuilder instance. Useful for chaining.
        Throws:
        IllegalArgumentException - If either minShardId is negative, maxShardId is lower than shardsTotal or minShardId is lower than or equal to maxShardId
      • setShardsTotal

        @Nonnull
        public DefaultShardManagerBuilder setShardsTotal​(int shardsTotal)
        This will set the total amount of shards the DefaultShardManager should use.

        If this is set to -1 JDA will automatically retrieve the recommended amount of shards from discord (default behavior).

        Parameters:
        shardsTotal - The number of overall shards or -1 if JDA should use the recommended amount from discord.
        Returns:
        The DefaultShardManagerBuilder instance. Useful for chaining.
        See Also:
        setShards(int, int)
      • setToken

        @Nonnull
        public DefaultShardManagerBuilder setToken​(@Nonnull
                                                   String token)
        Sets the token that will be used by the ShardManager instance to log in when build() is called.

        To get a bot token:

        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 DefaultShardManagerBuilder instance. Useful for chaining.
        Throws:
        IllegalArgumentException - If the token is either null or empty
      • setGuildSubscriptionsEnabled

        @Nonnull
        public DefaultShardManagerBuilder 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 DefaultShardManagerBuilder instance. Useful for chaining.
        Since:
        4.0.0
      • setLargeThreshold

        @Nonnull
        public DefaultShardManagerBuilder 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 DefaultShardManagerBuilder instance. Useful for chaining.
        Since:
        4.0.0
      • setMaxBufferSize

        @Nonnull
        public DefaultShardManagerBuilder setMaxBufferSize​(int bufferSize)
        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 to Integer.MAX_VALUE would imply the buffer will never be resized unless memory starvation is imminent.
        Setting this to 0 would 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 DefaultShardManagerBuilder instance. Useful for chaining.
        Throws:
        IllegalArgumentException - If the provided buffer size is negative
      • build

        @Nonnull
        public ShardManager build()
                           throws LoginException,
                                  IllegalArgumentException
        Builds a new ShardManager 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, ShardManager has not finished loading, thus many ShardManager 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.

        Note that this method is async and as such will not block until all shards are started.

        Returns:
        A ShardManager 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.