Class GatewayBootstrap<O extends GatewayOptions>
- java.lang.Object
-
- discord4j.core.shard.GatewayBootstrap<O>
-
- Type Parameters:
O
- the configuration flavor supplied to theGatewayClient
instances 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 aMono
for aGatewayDiscordClient
that can be externally managed.login(Function)
to customize theGatewayClient
instances to build.withGateway(Function)
to work with theGatewayDiscordClient
in 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 defaultGatewayBootstrap
based off the givenDiscordClient
that provides an instance ofCoreResources
used to provide defaults while building aGatewayDiscordClient
.static VoiceConnectionFactory
defaultVoiceConnectionFactory()
Create aVoiceConnectionFactory
with reconnecting capabilities.Mono<GatewayDiscordClient>
login()
Connect to the Discord Gateway upon subscription to build aGatewayClient
from the set of options configured by this builder.Mono<GatewayDiscordClient>
login(Function<O,GatewayClient> clientFactory)
Connect to the Discord Gateway upon subscription using a customfactory
to build aGatewayClient
from 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 connectMono
should defer completion until all joining shards have connected.GatewayBootstrap<O>
setDestroyHandler(Function<GatewayDiscordClient,Mono<Void>> destroyHandler)
Set a customhandler
that 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 theDispatchEventMapper
used to convert Gateway Dispatch intoEvent
instances.GatewayBootstrap<O>
setEnabledIntents(IntentSet intents)
Set the intents to subscribe from the gateway for this shard.GatewayBootstrap<O>
setEntityRetrievalStrategy(EntityRetrievalStrategy entityRetrievalStrategy)
Customize theEntityRetrievalStrategy
to use by default in order to retrieve Discord entities.GatewayBootstrap<O>
setEventDispatcher(EventDispatcher eventDispatcher)
Set a customEventDispatcher
to receiveEvents
from all joining shards and publish them to all subscribers.<O2 extends GatewayOptions>
GatewayBootstrap<O2>setExtraOptions(Function<? super O,O2> optionsModifier)
Add a configuration forGatewayClient
implementation-specific cases, changing the type of the currentGatewayOptions
object passed to theGatewayClient
factory in connect methods.GatewayBootstrap<O>
setGatewayObserver(GatewayObserver gatewayObserver)
Set a customGatewayObserver
to be notified of Gateway lifecycle events across all joining shards.GatewayBootstrap<O>
setGatewayReactorResources(Function<ReactorResources,GatewayReactorResources> gatewayReactorResources)
Customize theReactorResources
used exclusively for Gateway-related operations, such as maintaining the websocket connections and scheduling Gateway tasks.GatewayBootstrap<O>
setInitialPresence(Function<ShardInfo,ClientPresence> initialPresence)
Set aFunction
to determine theClientPresence
that 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 aMemberRequestFilter
to 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 customReconnectOptions
to configure how Gateway connections will attempt to reconnect every time a websocket session is closed unexpectedly.GatewayBootstrap<O>
setResumeOptions(Function<ShardInfo,SessionInfo> resumeOptions)
Set aFunction
to 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 customShardCoordinator
to manage multipleGatewayDiscordClient
instances, even across boundaries.GatewayBootstrap<O>
setSharding(ShardingStrategy shardingStrategy)
Set the sharding method to use while building aGatewayDiscordClient
.GatewayBootstrap<O>
setStore(Store store)
Set a customStore
to cache Gateway updates.GatewayBootstrap<O>
setVoiceConnectionFactory(VoiceConnectionFactory voiceConnectionFactory)
Customize theVoiceConnectionFactory
used to establish and maintainVoiceConnection
instances to perform voice-related operations.GatewayBootstrap<O>
setVoiceReactorResources(Function<ReactorResources,VoiceReactorResources> voiceReactorResources)
Customize theReactorResources
used 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 customReconnectOptions
to 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 bootstrappedEventDispatcher
to gain access to early startup events.Mono<Void>
withGateway(Function<GatewayDiscordClient,Publisher<?>> whileConnectedFunction)
Connect to the Discord Gateway upon subscription to acquire aGatewayDiscordClient
instance and use it in a declarative way, releasing the object once the derived usageFunction
completes, and the underlying shard group disconnects, according toGatewayDiscordClient.onDisconnect()
.
-
-
-
Method Detail
-
create
public static GatewayBootstrap<GatewayOptions> create(DiscordClient client)
Create a defaultGatewayBootstrap
based off the givenDiscordClient
that provides an instance ofCoreResources
used to provide defaults while building aGatewayDiscordClient
.- Parameters:
client
- theDiscordClient
used 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 forGatewayClient
implementation-specific cases, changing the type of the currentGatewayOptions
object passed to theGatewayClient
factory in connect methods.- Type Parameters:
O2
- new type for the options- Parameters:
optionsModifier
-Function
to transform theGatewayOptions
type to provide customGatewayClient
implementations a proper configuration object.- Returns:
- a new
GatewayBootstrap
that 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
shardCount
parameter 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 connectMono
should defer completion until all joining shards have connected. Defaults totrue
if running a single shard, otherwisefalse
.- Parameters:
awaitConnections
-true
if connect should wait until all joining shards have connected before completing, orfalse
to complete immediately- Returns:
- this builder
-
setShardCoordinator
public GatewayBootstrap<O> setShardCoordinator(ShardCoordinator shardCoordinator)
Set a customShardCoordinator
to manage multipleGatewayDiscordClient
instances, even across boundaries. Defaults to usingLocalShardCoordinator
.- Parameters:
shardCoordinator
- an externally managedShardCoordinator
to coordinate multipleGatewayDiscordClient
instances.- Returns:
- this builder
-
setEventDispatcher
public GatewayBootstrap<O> setEventDispatcher(@Nullable EventDispatcher eventDispatcher)
Set a customEventDispatcher
to receiveEvents
from 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 managedEventDispatcher
to publish events- Returns:
- this builder
-
setStore
public GatewayBootstrap<O> setStore(@Nullable Store store)
Set a customStore
to cache Gateway updates.- Parameters:
store
- an externally managedStore
to receive Gateway updates- Returns:
- this builder
-
setMemberRequestFilter
public GatewayBootstrap<O> setMemberRequestFilter(MemberRequestFilter memberRequestFilter)
Set aMemberRequestFilter
to 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 customhandler
that 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 aFunction
to determine theClientPresence
that each joining shard should use when identifying to the Gateway. Defaults to no status given.- Parameters:
initialPresence
- aFunction
that suppliesClientPresence
instances from a givenShardInfo
- Returns:
- this builder
-
setInitialStatus
@Deprecated public GatewayBootstrap<O> setInitialStatus(Function<ShardInfo,ClientPresence> initialStatus)
Deprecated.Set aFunction
to determine theClientPresence
that each joining shard should use when identifying to the Gateway. Defaults to no status given.- Parameters:
initialStatus
- aFunction
that suppliesClientPresence
instances from a givenShardInfo
- Returns:
- this builder
-
setResumeOptions
public GatewayBootstrap<O> setResumeOptions(Function<ShardInfo,SessionInfo> resumeOptions)
Set aFunction
to determine the details to resume a session that each joining shard should use when identifying for the first time to the Gateway. Defaults to returningnull
to begin a fresh session on startup.- Parameters:
resumeOptions
- aFunction
that suppliesSessionInfo
instances 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 returnMember
can 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_MEMBERS
you will not be able to request the entire list of members in a guild. - Fetching guild presences: if you don't enable
Intent.GUILD_PRESENCES
you 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_STATES
you 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 returnMember
can 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_MEMBERS
you will not be able to request the entire list of members in a guild. - Fetching guild presences: if you disable
Intent.GUILD_PRESENCES
you 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_STATES
you 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 customReconnectOptions
to configure how Gateway connections will attempt to reconnect every time a websocket session is closed unexpectedly.- Parameters:
reconnectOptions
- aReconnectOptions
policy to use in Gateway connections- Returns:
- this builder
-
setVoiceReconnectOptions
public GatewayBootstrap<O> setVoiceReconnectOptions(ReconnectOptions voiceReconnectOptions)
Set a customReconnectOptions
to configure how Voice Gateway connections will attempt to reconnect every time a websocket session is closed unexpectedly.- Parameters:
voiceReconnectOptions
- aReconnectOptions
policy to use in Voice Gateway connections- Returns:
- this builder
-
setGatewayObserver
public GatewayBootstrap<O> setGatewayObserver(GatewayObserver gatewayObserver)
Set a customGatewayObserver
to be notified of Gateway lifecycle events across all joining shards.- Parameters:
gatewayObserver
- aGatewayObserver
to install on all joining shards- Returns:
- this builder
-
setGatewayReactorResources
public GatewayBootstrap<O> setGatewayReactorResources(Function<ReactorResources,GatewayReactorResources> gatewayReactorResources)
Customize theReactorResources
used exclusively for Gateway-related operations, such as maintaining the websocket connections and scheduling Gateway tasks. Defaults to using the parentReactorResources
inherited fromDiscordClient
.- Parameters:
gatewayReactorResources
- aReactorResources
object for Gateway operations- Returns:
- this builder
-
setVoiceReactorResources
public GatewayBootstrap<O> setVoiceReactorResources(Function<ReactorResources,VoiceReactorResources> voiceReactorResources)
Customize theReactorResources
used 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 parentReactorResources
inherited fromDiscordClient
.- Parameters:
voiceReactorResources
- aReactorResources
object for voice operations- Returns:
- this builder
-
setVoiceConnectionFactory
public GatewayBootstrap<O> setVoiceConnectionFactory(VoiceConnectionFactory voiceConnectionFactory)
Customize theVoiceConnectionFactory
used to establish and maintainVoiceConnection
instances to perform voice-related operations. Defaults todefaultVoiceConnectionFactory()
.- Parameters:
voiceConnectionFactory
- a factory that can createVoiceConnection
instances.- Returns:
- this builder
-
setEntityRetrievalStrategy
public GatewayBootstrap<O> setEntityRetrievalStrategy(@Nullable EntityRetrievalStrategy entityRetrievalStrategy)
Customize theEntityRetrievalStrategy
to 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 theDispatchEventMapper
used to convert Gateway Dispatch intoEvent
instances. Defaults to usingDispatchEventMapper.emitEvents()
that will process payloads and save its updates to the appropriateStore
, then generate the rightEvent
instance.- Parameters:
dispatchEventMapper
- a factory to deriveEvents
from 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 bootstrappedEventDispatcher
to gain access to early startup events. The subscriber is derived from the givenFunction
which returns aPublisher
that is subscribed early in the Gateway connection process.Errors emitted from the given
dispatcherFunction
will instruct a logout procedure to disconnect from the Gateway.- Parameters:
dispatcherFunction
- anEventDispatcher
mapper 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 aGatewayDiscordClient
instance and use it in a declarative way, releasing the object once the derived usageFunction
completes, and the underlying shard group disconnects, according toGatewayDiscordClient.onDisconnect()
.The timing of acquiring a
GatewayDiscordClient
depends 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
GatewayDiscordClient
object using reactive API you can compose within the scope of the givenFunction
.- Parameters:
whileConnectedFunction
- theFunction
to apply the connectedGatewayDiscordClient
and trigger a processing pipeline from it.- Returns:
- an empty
Mono
completing after all resources have released
-
login
public Mono<GatewayDiscordClient> login()
Connect to the Discord Gateway upon subscription to build aGatewayClient
from the set of options configured by this builder. The resultingGatewayDiscordClient
can be externally managed, leaving you in charge of properly releasing its resources by callingGatewayDiscordClient.logout()
.The timing of acquiring a
GatewayDiscordClient
depends 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
Mono
that 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 customfactory
to build aGatewayClient
from the set of options configured by this builder. Seelogin()
for more details about how the returnedMono
operates.- Returns:
- a
Mono
that 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 aVoiceConnectionFactory
with reconnecting capabilities.- Returns:
- a default
VoiceConnectionFactory
-
-