Class GatewayBootstrap<O extends GatewayOptions>
- java.lang.Object
-
- discord4j.core.shard.GatewayBootstrap<O>
-
- Type Parameters:
O- the configuration flavor supplied to theGatewayClientinstances to be built.
public class GatewayBootstrap<O extends GatewayOptions> extends Object
Builder to create a shard group connecting to Discord Gateway to produce aGatewayDiscordClient. A shard group represents a set of shards for a given bot that will share some key resources like entity caching and event dispatching. Defaults to creating an automatic sharding group using all shards up to the recommended amount. Refer to each setter for more details about the default values for each configuration. Some of the commonly used ones are:- Setting the number of shards to connect through the
setSharding(ShardingStrategy)method. - Setting the initial status of the bot depending on the shard, through
setInitialPresence(Function) - Customize the entity cache using
setStore(Store)
One of the following methods must be subscribed to in order to begin establishing Discord Gateway connections:
login()to obtain aMonofor aGatewayDiscordClientthat can be externally managed.login(Function)to customize theGatewayClientinstances to build.withGateway(Function)to work with theGatewayDiscordClientin a scoped way, providing a mapping function that will close and release all resources on disconnection.
setAwaitConnections(boolean).
-
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static GatewayBootstrap<GatewayOptions>create(DiscordClient client)Create a defaultGatewayBootstrapbased off the givenDiscordClientthat provides an instance ofCoreResourcesused to provide defaults while building aGatewayDiscordClient.static VoiceConnectionFactorydefaultVoiceConnectionFactory()Create aVoiceConnectionFactorywith reconnecting capabilities.Mono<GatewayDiscordClient>login()Connect to the Discord Gateway upon subscription to build aGatewayClientfrom the set of options configured by this builder.Mono<GatewayDiscordClient>login(Function<O,GatewayClient> clientFactory)Connect to the Discord Gateway upon subscription using a customfactoryto build aGatewayClientfrom the set of options configured by this builder.static Function<GatewayDiscordClient,Mono<Void>>noopDestroyHandler()Destroy handler that doesn't perform any cleanup task.GatewayBootstrap<O>setAwaitConnections(boolean awaitConnections)Set if the connectMonoshould defer completion until all joining shards have connected.GatewayBootstrap<O>setDestroyHandler(Function<GatewayDiscordClient,Mono<Void>> destroyHandler)Set a customhandlerthat generate a destroy sequence to be run once all joining shards have disconnected, after all internal resources have been released.GatewayBootstrap<O>setDisabledIntents(IntentSet intents)Set the intents which should not be subscribed from the gateway for this shard.GatewayBootstrap<O>setDispatchEventMapper(DispatchEventMapper dispatchEventMapper)Customize theDispatchEventMapperused to convert Gateway Dispatch intoEventinstances.GatewayBootstrap<O>setEnabledIntents(IntentSet intents)Set the intents to subscribe from the gateway for this shard.GatewayBootstrap<O>setEntityRetrievalStrategy(EntityRetrievalStrategy entityRetrievalStrategy)Customize theEntityRetrievalStrategyto use by default in order to retrieve Discord entities.GatewayBootstrap<O>setEventDispatcher(EventDispatcher eventDispatcher)Set a customEventDispatcherto receiveEventsfrom all joining shards and publish them to all subscribers.<O2 extends GatewayOptions>
GatewayBootstrap<O2>setExtraOptions(Function<? super O,O2> optionsModifier)Add a configuration forGatewayClientimplementation-specific cases, changing the type of the currentGatewayOptionsobject passed to theGatewayClientfactory in connect methods.GatewayBootstrap<O>setGatewayObserver(GatewayObserver gatewayObserver)Set a customGatewayObserverto be notified of Gateway lifecycle events across all joining shards.GatewayBootstrap<O>setGatewayReactorResources(Function<ReactorResources,GatewayReactorResources> gatewayReactorResources)Customize theReactorResourcesused exclusively for Gateway-related operations, such as maintaining the websocket connections and scheduling Gateway tasks.GatewayBootstrap<O>setInitialPresence(Function<ShardInfo,ClientPresence> initialPresence)Set aFunctionto determine theClientPresencethat each joining shard should use when identifying to the Gateway.GatewayBootstrap<O>setInitialStatus(Function<ShardInfo,ClientPresence> initialStatus)Deprecated.GatewayBootstrap<O>setMaxMissedHeartbeatAck(int maxMissedHeartbeatAck)Set the maximum number of missed heartbeat acknowledge payloads each connection to Gateway will allow before triggering an automatic reconnect.GatewayBootstrap<O>setMemberRequestFilter(MemberRequestFilter memberRequestFilter)Set aMemberRequestFilterto determine how this shard group should request guild members.GatewayBootstrap<O>setPayloadReader(PayloadReader payloadReader)Customize how inbound Gateway payloads are decoded fromByteBuf.GatewayBootstrap<O>setPayloadWriter(PayloadWriter payloadWriter)Customize how outbound Gateway payloads are encoded intoByteBuf.GatewayBootstrap<O>setReconnectOptions(ReconnectOptions reconnectOptions)Set a customReconnectOptionsto configure how Gateway connections will attempt to reconnect every time a websocket session is closed unexpectedly.GatewayBootstrap<O>setResumeOptions(Function<ShardInfo,SessionInfo> resumeOptions)Set aFunctionto determine the details to resume a session that each joining shard should use when identifying for the first time to the Gateway.GatewayBootstrap<O>setShardCoordinator(ShardCoordinator shardCoordinator)Set a customShardCoordinatorto manage multipleGatewayDiscordClientinstances, even across boundaries.GatewayBootstrap<O>setSharding(ShardingStrategy shardingStrategy)Set the sharding method to use while building aGatewayDiscordClient.GatewayBootstrap<O>setStore(Store store)Set a customStoreto cache Gateway updates.GatewayBootstrap<O>setVoiceConnectionFactory(VoiceConnectionFactory voiceConnectionFactory)Customize theVoiceConnectionFactoryused to establish and maintainVoiceConnectioninstances to perform voice-related operations.GatewayBootstrap<O>setVoiceReactorResources(Function<ReactorResources,VoiceReactorResources> voiceReactorResources)Customize theReactorResourcesused exclusively for voice-related operations, such as maintaining the Voice Gateway websocket connections, Voice UDP socket connections and scheduling Gateway tasks.GatewayBootstrap<O>setVoiceReconnectOptions(ReconnectOptions voiceReconnectOptions)Set a customReconnectOptionsto configure how Voice Gateway connections will attempt to reconnect every time a websocket session is closed unexpectedly.static Function<GatewayDiscordClient,Mono<Void>>shutdownDestroyHandler()Destroy handler that callsEventDispatcher.shutdown()asynchronously.GatewayBootstrap<O>withEventDispatcher(Function<EventDispatcher,Publisher<?>> dispatcherFunction)Set an initial subscriber to the bootstrappedEventDispatcherto gain access to early startup events.Mono<Void>withGateway(Function<GatewayDiscordClient,Publisher<?>> whileConnectedFunction)Connect to the Discord Gateway upon subscription to acquire aGatewayDiscordClientinstance and use it in a declarative way, releasing the object once the derived usageFunctioncompletes, and the underlying shard group disconnects, according toGatewayDiscordClient.onDisconnect().
-
-
-
Method Detail
-
create
public static GatewayBootstrap<GatewayOptions> create(DiscordClient client)
Create a defaultGatewayBootstrapbased off the givenDiscordClientthat provides an instance ofCoreResourcesused to provide defaults while building aGatewayDiscordClient.- Parameters:
client- theDiscordClientused to set up configuration- Returns:
- a default builder to create
GatewayDiscordClient
-
setExtraOptions
public <O2 extends GatewayOptions> GatewayBootstrap<O2> setExtraOptions(Function<? super O,O2> optionsModifier)
Add a configuration forGatewayClientimplementation-specific cases, changing the type of the currentGatewayOptionsobject passed to theGatewayClientfactory in connect methods.- Type Parameters:
O2- new type for the options- Parameters:
optionsModifier-Functionto transform theGatewayOptionstype to provide customGatewayClientimplementations a proper configuration object.- Returns:
- a new
GatewayBootstrapthat will now work with the new options type.
-
setSharding
public GatewayBootstrap<O> setSharding(ShardingStrategy shardingStrategy)
Set the sharding method to use while building aGatewayDiscordClient. Defaults to creating all shards given by the recommended amount from Discord, which is equivalent toShardingStrategy.recommended(). Built-in factories likeShardingStrategy.fixed(int)to use a predefined number of shards, or customize the strategy usingShardingStrategy.builder().For example, it is possible to define the
shardCountparameter independently from the number of shards to create and connect to Gateway by using:.setSharding(ShardingStrategy.builder() .indices(0, 2, 4) .count(6) .build())Would only connect shards 0, 2 and 4 while still indicating that your bot guilds are split across 6 shards.- Parameters:
shardingStrategy- a strategy to use while sharding the connections to Discord Gateway- Returns:
- this builder
-
setAwaitConnections
public GatewayBootstrap<O> setAwaitConnections(boolean awaitConnections)
Set if the connectMonoshould defer completion until all joining shards have connected. Defaults totrueif running a single shard, otherwisefalse.- Parameters:
awaitConnections-trueif connect should wait until all joining shards have connected before completing, orfalseto complete immediately- Returns:
- this builder
-
setShardCoordinator
public GatewayBootstrap<O> setShardCoordinator(ShardCoordinator shardCoordinator)
Set a customShardCoordinatorto manage multipleGatewayDiscordClientinstances, even across boundaries. Defaults to usingLocalShardCoordinator.- Parameters:
shardCoordinator- an externally managedShardCoordinatorto coordinate multipleGatewayDiscordClientinstances.- Returns:
- this builder
-
setEventDispatcher
public GatewayBootstrap<O> setEventDispatcher(@Nullable EventDispatcher eventDispatcher)
Set a customEventDispatcherto receiveEventsfrom all joining shards and publish them to all subscribers. Defaults to usingEventDispatcher.buffering()which buffers all events until the first subscriber subscribes to the dispatcher.- Parameters:
eventDispatcher- an externally managedEventDispatcherto publish events- Returns:
- this builder
-
setStore
public GatewayBootstrap<O> setStore(@Nullable Store store)
Set a customStoreto cache Gateway updates.- Parameters:
store- an externally managedStoreto receive Gateway updates- Returns:
- this builder
-
setMemberRequestFilter
public GatewayBootstrap<O> setMemberRequestFilter(MemberRequestFilter memberRequestFilter)
Set aMemberRequestFilterto determine how this shard group should request guild members. The provided filter is applied on each GUILD_CREATE payload and if returnstrue, members will be requested for the given guild. Defaults to loading members from all large guilds immediately after a GUILD_CREATE.- Parameters:
memberRequestFilter- the filter indicating how to load guild members- Returns:
- this builder
- See Also:
- Request Guild Members
-
setDestroyHandler
public GatewayBootstrap<O> setDestroyHandler(Function<GatewayDiscordClient,Mono<Void>> destroyHandler)
Set a customhandlerthat generate a destroy sequence to be run once all joining shards have disconnected, after all internal resources have been released. The destroy procedure is applied asynchronously and errors are logged and swallowed. Defaults toshutdownDestroyHandler()that will release the setEventDispatcher.
-
setInitialPresence
public GatewayBootstrap<O> setInitialPresence(Function<ShardInfo,ClientPresence> initialPresence)
Set aFunctionto determine theClientPresencethat each joining shard should use when identifying to the Gateway. Defaults to no status given.- Parameters:
initialPresence- aFunctionthat suppliesClientPresenceinstances from a givenShardInfo- Returns:
- this builder
-
setInitialStatus
@Deprecated public GatewayBootstrap<O> setInitialStatus(Function<ShardInfo,ClientPresence> initialStatus)
Deprecated.Set aFunctionto determine theClientPresencethat each joining shard should use when identifying to the Gateway. Defaults to no status given.- Parameters:
initialStatus- aFunctionthat suppliesClientPresenceinstances from a givenShardInfo- Returns:
- this builder
-
setResumeOptions
public GatewayBootstrap<O> setResumeOptions(Function<ShardInfo,SessionInfo> resumeOptions)
Set aFunctionto determine the details to resume a session that each joining shard should use when identifying for the first time to the Gateway. Defaults to returningnullto begin a fresh session on startup.- Parameters:
resumeOptions- aFunctionthat suppliesSessionInfoinstances from a givenShardInfo- Returns:
- this builder
-
setEnabledIntents
public GatewayBootstrap<O> setEnabledIntents(IntentSet intents)
Set the intents to subscribe from the gateway for this shard. Using this method is mutually exclusive fromsetDisabledIntents(IntentSet). Defaults toIntentSet.nonPrivileged().When using intents, make sure you understand their effect on your bot, to avoid issues specially when working around members. Depend on
GatewayDiscordClient.requestMembers(Snowflake, Set)andGuild.requestMembers(Set)to fetch members directly. Methods that returnMembercan lazily fetch entities from the Gateway if missing, according to the configuredsetEntityRetrievalStrategy(EntityRetrievalStrategy).Members can also be requested eagerly on startup, using
setMemberRequestFilter(MemberRequestFilter), either for select guilds or all of them, provided you are able to request the entire list of members in a guild.The following scenarios are affected by this feature:
- Fetching guild members: if you don't enable
Intent.GUILD_MEMBERSyou will not be able to request the entire list of members in a guild. - Fetching guild presences: if you don't enable
Intent.GUILD_PRESENCESyou will not receive user activity and status information. In addition, you will not receive the initial guild member list, which includes all members for small guilds and online members + members without roles for larger guilds. - Establishing voice connections: if you don't enable
Intent.GUILD_VOICE_STATESyou will not be able to connect to a voice channel.
- Parameters:
intents- set of intents to subscribe- Returns:
- this builder
- Fetching guild members: if you don't enable
-
setDisabledIntents
public GatewayBootstrap<O> setDisabledIntents(IntentSet intents)
Set the intents which should not be subscribed from the gateway for this shard. This method computes byIntentSet.all()minus the provided intents. Using this method is mutually exclusive fromsetEnabledIntents(IntentSet).When using intents, make sure you understand their effect on your bot, to avoid issues specially when working around members. Depend on
GatewayDiscordClient.requestMembers(Snowflake, Set)andGuild.requestMembers(Set)to fetch members directly. Methods that returnMembercan lazily fetch entities from the Gateway if missing, according to the configuredsetEntityRetrievalStrategy(EntityRetrievalStrategy).Members can also be requested eagerly on startup, using
setMemberRequestFilter(MemberRequestFilter), either for select guilds or all of them, provided you are able to request the entire list of members in a guild.The following scenarios are affected by this feature:
- Fetching guild members: if you disable
Intent.GUILD_MEMBERSyou will not be able to request the entire list of members in a guild. - Fetching guild presences: if you disable
Intent.GUILD_PRESENCESyou will not receive user activity and status information. In addition, you will not receive the initial guild member list, which includes all members for small guilds and online members + members without roles for larger guilds. - Establishing voice connections: if you disable
Intent.GUILD_VOICE_STATESyou will not be able to connect to a voice channel.
- Parameters:
intents- set of intents which should not be subscribed- Returns:
- this builder
- Fetching guild members: if you disable
-
setPayloadReader
public GatewayBootstrap<O> setPayloadReader(@Nullable PayloadReader payloadReader)
Customize how inbound Gateway payloads are decoded fromByteBuf.- Parameters:
payloadReader- a Gateway payload decoder- Returns:
- this builder
-
setPayloadWriter
public GatewayBootstrap<O> setPayloadWriter(@Nullable PayloadWriter payloadWriter)
Customize how outbound Gateway payloads are encoded intoByteBuf.- Parameters:
payloadWriter- a Gateway payload encoder- Returns:
- this builder
-
setReconnectOptions
public GatewayBootstrap<O> setReconnectOptions(ReconnectOptions reconnectOptions)
Set a customReconnectOptionsto configure how Gateway connections will attempt to reconnect every time a websocket session is closed unexpectedly.- Parameters:
reconnectOptions- aReconnectOptionspolicy to use in Gateway connections- Returns:
- this builder
-
setVoiceReconnectOptions
public GatewayBootstrap<O> setVoiceReconnectOptions(ReconnectOptions voiceReconnectOptions)
Set a customReconnectOptionsto configure how Voice Gateway connections will attempt to reconnect every time a websocket session is closed unexpectedly.- Parameters:
voiceReconnectOptions- aReconnectOptionspolicy to use in Voice Gateway connections- Returns:
- this builder
-
setGatewayObserver
public GatewayBootstrap<O> setGatewayObserver(GatewayObserver gatewayObserver)
Set a customGatewayObserverto be notified of Gateway lifecycle events across all joining shards.- Parameters:
gatewayObserver- aGatewayObserverto install on all joining shards- Returns:
- this builder
-
setGatewayReactorResources
public GatewayBootstrap<O> setGatewayReactorResources(Function<ReactorResources,GatewayReactorResources> gatewayReactorResources)
Customize theReactorResourcesused exclusively for Gateway-related operations, such as maintaining the websocket connections and scheduling Gateway tasks. Defaults to using the parentReactorResourcesinherited fromDiscordClient.- Parameters:
gatewayReactorResources- aReactorResourcesobject for Gateway operations- Returns:
- this builder
-
setVoiceReactorResources
public GatewayBootstrap<O> setVoiceReactorResources(Function<ReactorResources,VoiceReactorResources> voiceReactorResources)
Customize theReactorResourcesused exclusively for voice-related operations, such as maintaining the Voice Gateway websocket connections, Voice UDP socket connections and scheduling Gateway tasks. Defaults to using the parentReactorResourcesinherited fromDiscordClient.- Parameters:
voiceReactorResources- aReactorResourcesobject for voice operations- Returns:
- this builder
-
setVoiceConnectionFactory
public GatewayBootstrap<O> setVoiceConnectionFactory(VoiceConnectionFactory voiceConnectionFactory)
Customize theVoiceConnectionFactoryused to establish and maintainVoiceConnectioninstances to perform voice-related operations. Defaults todefaultVoiceConnectionFactory().- Parameters:
voiceConnectionFactory- a factory that can createVoiceConnectioninstances.- Returns:
- this builder
-
setEntityRetrievalStrategy
public GatewayBootstrap<O> setEntityRetrievalStrategy(@Nullable EntityRetrievalStrategy entityRetrievalStrategy)
Customize theEntityRetrievalStrategyto use by default in order to retrieve Discord entities. Defaults toEntityRetrievalStrategy.STORE_FALLBACK_REST.- Parameters:
entityRetrievalStrategy- a strategy to use to retrieve entities- Returns:
- this builder
-
setDispatchEventMapper
public GatewayBootstrap<O> setDispatchEventMapper(DispatchEventMapper dispatchEventMapper)
Customize theDispatchEventMapperused to convert Gateway Dispatch intoEventinstances. Defaults to usingDispatchEventMapper.emitEvents()that will process payloads and save its updates to the appropriateStore, then generate the rightEventinstance.- Parameters:
dispatchEventMapper- a factory to deriveEventsfrom Gateway- Returns:
- this builder
-
setMaxMissedHeartbeatAck
public GatewayBootstrap<O> setMaxMissedHeartbeatAck(int maxMissedHeartbeatAck)
Set the maximum number of missed heartbeat acknowledge payloads each connection to Gateway will allow before triggering an automatic reconnect. A missed acknowledge is counted if a client does not receive a heartbeat ACK between its attempts at sending heartbeats. Defaults to 1.- Parameters:
maxMissedHeartbeatAck- a non-negative number representing the maximum number of allowed- Returns:
- this builder
-
withEventDispatcher
@Experimental public GatewayBootstrap<O> withEventDispatcher(Function<EventDispatcher,Publisher<?>> dispatcherFunction)
Set an initial subscriber to the bootstrappedEventDispatcherto gain access to early startup events. The subscriber is derived from the givenFunctionwhich returns aPublisherthat is subscribed early in the Gateway connection process.Errors emitted from the given
dispatcherFunctionwill instruct a logout procedure to disconnect from the Gateway.- Parameters:
dispatcherFunction- anEventDispatchermapper that derives an asynchronous listener- Returns:
- this builder
-
withGateway
public Mono<Void> withGateway(Function<GatewayDiscordClient,Publisher<?>> whileConnectedFunction)
Connect to the Discord Gateway upon subscription to acquire aGatewayDiscordClientinstance and use it in a declarative way, releasing the object once the derived usageFunctioncompletes, and the underlying shard group disconnects, according toGatewayDiscordClient.onDisconnect().The timing of acquiring a
GatewayDiscordClientdepends on thesetAwaitConnections(boolean)setting: iftrue, when all joining shards have connected; iffalse, as soon as it is possible to establish a connection to the Gateway.Calling this method is useful when you operate on the
GatewayDiscordClientobject using reactive API you can compose within the scope of the givenFunction.- Parameters:
whileConnectedFunction- theFunctionto apply the connectedGatewayDiscordClientand trigger a processing pipeline from it.- Returns:
- an empty
Monocompleting after all resources have released
-
login
public Mono<GatewayDiscordClient> login()
Connect to the Discord Gateway upon subscription to build aGatewayClientfrom the set of options configured by this builder. The resultingGatewayDiscordClientcan be externally managed, leaving you in charge of properly releasing its resources by callingGatewayDiscordClient.logout().The timing of acquiring a
GatewayDiscordClientdepends on thesetAwaitConnections(boolean)setting: iftrue, when all joining shards have connected; iffalse, as soon as it is possible to establish a connection to the Gateway.All joining shards will attempt to serially connect to Discord Gateway, coordinated by the current
ShardCoordinator. If one of the shards fail to connect due to a retryable problem like invalid session it will retry before continuing to the next one.- Returns:
- a
Monothat upon subscription and depending on the configuration ofsetAwaitConnections(boolean), emits aGatewayDiscordClient. If an error occurs during the setup sequence, it will be emitted through theMono.
-
login
public Mono<GatewayDiscordClient> login(Function<O,GatewayClient> clientFactory)
Connect to the Discord Gateway upon subscription using a customfactoryto build aGatewayClientfrom the set of options configured by this builder. Seelogin()for more details about how the returnedMonooperates.- Returns:
- a
Monothat upon subscription and depending on the configuration ofsetAwaitConnections(boolean), emits aGatewayDiscordClient. If an error occurs during the setup sequence, it will be emitted through theMono.
-
noopDestroyHandler
public static Function<GatewayDiscordClient,Mono<Void>> noopDestroyHandler()
Destroy handler that doesn't perform any cleanup task.- Returns:
- a noop destroy handler
-
shutdownDestroyHandler
public static Function<GatewayDiscordClient,Mono<Void>> shutdownDestroyHandler()
Destroy handler that callsEventDispatcher.shutdown()asynchronously.- Returns:
- a shutdown destroy handler
-
defaultVoiceConnectionFactory
public static VoiceConnectionFactory defaultVoiceConnectionFactory()
Create aVoiceConnectionFactorywith reconnecting capabilities.- Returns:
- a default
VoiceConnectionFactory
-
-