Class JDAImpl
- All Implemented Interfaces:
IGuildChannelContainer<Channel>
,JDA
-
Nested Class Summary
Nested classes/interfaces inherited from interface net.dv8tion.jda.api.JDA
JDA.ShardInfo, JDA.Status
-
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionJDAImpl
(AuthorizationConfig authConfig) JDAImpl
(AuthorizationConfig authConfig, SessionConfig sessionConfig, ThreadingConfig threadConfig, MetaConfig metaConfig, RestConfig restConfig) -
Method Summary
Modifier and TypeMethodDescriptionvoid
addEventListener
(Object... listeners) Adds all provided listeners to the event-listeners that will be used to handle events.boolean
awaitShutdown
(long timeout, TimeUnit unit) Blocks the current thread untilJDA.getStatus()
returnsJDA.Status.SHUTDOWN
.awaitStatus
(JDA.Status status, JDA.Status... failOn) This method will block until JDA has reached the specified connection status.boolean
cacheMember
(Member member) int
Cancels all currently scheduledRestAction
requests.boolean
chunkGuild
(long id) createApplicationEmoji
(String name, Icon icon) Creates a newApplicationEmoji
for this bot.createGuild
(String name) Constructs a newGuild
with the specified name
Use the returnedGuildAction
to provide further details and settings for the resulting Guild!createGuildFromTemplate
(String code, String name, Icon icon) Constructs a newGuild
from the specified template code.createTestEntitlement
(long skuId, long ownerId, TestEntitlementCreateAction.OwnerType ownerType) Constructs a newEntitlement
with the skuId and the type.deleteCommandById
(String commandId) Delete the global command for this id.deleteTestEntitlement
(long entitlementId) Deletes a test entitlement by its id.editCommandById
(Command.Type type, String id) Edit an existing global command by id.Returns theApplicationManager
that manages the application associated with the bot.CacheView
of all cachedAudioManagers
created for this JDA instance.Thecache flags
that have been enabled for this JDA session.ExecutorService
used to handleRestAction
callbacks and completions.SortedSnowflakeCacheView
ofCategory
.<T extends Channel>
TgetChannelById
(Class<T> type, long id) Get a channel of the specified type by id.Unified cache of all channels associated with this shard or guild.Direct access to audio (dis-)connect requests.UnifiedSnowflakeCacheView
of all cachedCustom Emojis
visible to this JDA session.The EventManager used by this JDA instance.TheGatewayIntents
for this JDA session.long
The time in milliseconds that discord took to respond to our last heartbeat
This roughly represents the WebSocket ping of this sessionScheduledExecutorService
used to send WebSocket messages to discord.SnowflakeCacheView
of all cachedGuilds
visible to this JDA session.getGuildChannelById
(long id) GetGuildChannel
for the provided ID.getGuildChannelById
(ChannelType type, long id) GetGuildChannel
for the provided ID.okhttp3.OkHttpClient
TheOkHttpClient
used for handling http requests fromRestActions
.getInviteUrl
(Collection<Permission> permissions) Creates an authorization invite url for the currently logged in Bot-Account.getInviteUrl
(Permission... permissions) Creates an authorization invite url for the currently logged in Bot-Account.int
int
int
This value is the maximum amount of time, in seconds, that JDA will wait between reconnect attempts.getMutualGuilds
(Collection<User> users) Gets allGuilds
that contain all given users as their members.getMutualGuilds
(User... users) Gets allGuilds
that contain all given users as their members.SortedSnowflakeCacheView
ofNewsChannel
.ThePresence
controller for the current session.getPrivateChannelById
(long id) This returns thePrivateChannel
which has the same id as the one provided.This returns thePrivateChannel
which has the same id as the one provided.SnowflakeCacheView
of all cachedPrivateChannels
visible to this JDA session.ScheduledExecutorService
used to handle rate-limits forRestAction
executions.Immutable List of Objects that have been registered as EventListeners.long
This value is the total amount of JSON responses that discord has sent.UnifiedSnowflakeCacheView
of all cachedRoles
visible to this JDA session.SnowflakeCacheView
of all cachedScheduledEvents
visible to this JDA session.Returns the currently logged in account represented bySelfUser
.The shard information used when creating this instance of JDA.Returns theShardManager
that manages this JDA instances or null if this instance is not managed by anyShardManager
.SortedSnowflakeCacheView
ofStageChannel
.Gets the currentStatus
of the JDA instance.SortedSnowflakeCacheView
ofTextChannel
.getToken()
The login token that is currently being used for Discord authentication.Set ofGuild
IDs for guilds that were marked unavailable by the gateway.SnowflakeCacheView
of all cachedUsers
visible to this JDA session.SortedSnowflakeCacheView
ofVoiceChannel
.void
handleEvent
(GenericEvent event) boolean
void
boolean
Used to determine whether or not autoReconnect is enabled for JDA.boolean
Used to determine if JDA will process MESSAGE_DELETE_BULK messages received from Discord as a singleMessageBulkDeleteEvent
or split the deleted messages up and fire multipleMessageDeleteEvents
, one for each deleted message.boolean
isCacheFlagSet
(CacheFlag flag) boolean
boolean
isIntent
(GatewayIntent intent) boolean
boolean
isUnavailable
(long guildId) Whether the guild is unavailable.<E extends GenericEvent>
Once.Builder<E> listenOnce
(Class<E> eventType) Returns a reusable builder for a one-time event listener.int
login()
int
login
(String gatewayUrl, JDA.ShardInfo shardInfo, Compression compression, boolean validateToken, int intents, GatewayEncoding encoding) int
login
(JDA.ShardInfo shardInfo, Compression compression, boolean validateToken, int intents, GatewayEncoding encoding) openPrivateChannelById
(long userId) Opens aPrivateChannel
with the provided user by id.void
removeEventListener
(Object... listeners) Removes all provided listeners from the event-listeners and no longer uses them to handle events.void
retrieveApplicationEmojiById
(String emojiId) Retrieves an application emoji together with its respective creator.Retrieves a list of Application Emojis together with their respective creators.Retrieves theApplicationInfo
for the application that owns the logged in Bot-Account.Retrieves the existingCommand
instance by id.retrieveCommands
(boolean withLocalizations) Retrieves the list of global commands.retrieveEntitlementById
(long entitlementId) Retrieves anEntitlement
by its id.APaginationAction
implementation which allows you toiterate
overEntitlement
s that are applicable to the logged in application.Retrieves a list of all the publicStickerPacks
used for nitro.Retrieves the currently configuredRoleConnectionMetadata
records for this application.retrieveSticker
(StickerSnowflake sticker) Attempts to retrieve aSticker
object based on the provided snowflake reference.retrieveUserById
(long id) Attempts to retrieve aUser
object based on the provided id.retrieveWebhookById
(String webhookId) Retrieves aWebhook
by its id.void
setAudioSendFactory
(IAudioSendFactory factory) void
setAutoReconnect
(boolean autoReconnect) Sets whether or not JDA should try to automatically reconnect if a connection-error is encountered.void
setChunkingFilter
(ChunkingFilter filter) void
void
setEventManager
(IEventManager eventManager) Changes the internal EventManager.void
setGatewayPing
(long ping) void
void
setRequestTimeoutRetry
(boolean retryOnTimeout) Whether the Requester should retry when aSocketTimeoutException
occurs.setRequiredScopes
(Collection<String> scopes) Configures the required scopes applied to theJDA.getInviteUrl(Permission...)
and similar methods.void
setResponseTotal
(int responseTotal) void
setSelfUser
(SelfUser selfUser) void
setShardManager
(ShardManager shardManager) void
setStatus
(JDA.Status status) void
void
shutdown()
Shuts down this JDA instance, closing all its connections.void
shutdownInternals
(ShutdownEvent event) void
Shuts down this JDA instance instantly, closing all its connections.void
boolean
unloadUser
(long userId) Attempts to remove the user with the provided id from the cache.Configures the complete list of global commands.updateRoleConnectionMetadata
(Collection<? extends RoleConnectionMetadata> records) Updates the currently configuredRoleConnectionMetadata
records for this application.upsertCommand
(CommandData command) Creates or updates a global command.void
usedPrivateChannel
(long id) void
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface net.dv8tion.jda.api.entities.channel.attribute.IGuildChannelContainer
getCategories, getCategoriesByName, getCategoryById, getCategoryById, getChannelById, getForumChannelById, getForumChannelById, getForumChannels, getForumChannelsByName, getGuildChannelById, getGuildChannelById, getMediaChannelById, getMediaChannelById, getMediaChannels, getMediaChannelsByName, getNewsChannelById, getNewsChannelById, getNewsChannels, getNewsChannelsByName, getStageChannelById, getStageChannelById, getStageChannels, getStageChannelsByName, getTextChannelById, getTextChannelById, getTextChannels, getTextChannelsByName, getThreadChannelById, getThreadChannelById, getThreadChannels, getThreadChannelsByName, getVoiceChannelById, getVoiceChannelById, getVoiceChannels, getVoiceChannelsByName
Methods inherited from interface net.dv8tion.jda.api.JDA
awaitReady, awaitShutdown, awaitShutdown, awaitStatus, createTestEntitlement, deleteCommandById, deleteTestEntitlement, editCommandById, getAudioManagers, getEmojiById, getEmojiById, getEmojis, getEmojisByName, getGuildById, getGuildById, getGuilds, getGuildsByName, getPrivateChannels, getRestPing, getRoleById, getRoleById, getRoles, getRolesByName, getScheduledEventById, getScheduledEventById, getScheduledEvents, getScheduledEventsByName, getUserById, getUserById, getUserByTag, getUserByTag, getUsers, getUsersByName, installAuxiliaryPort, openPrivateChannelById, retrieveApplicationEmojiById, retrieveCommandById, retrieveCommands, retrieveEntitlementById, retrieveUserById, retrieveWebhookById, setRequiredScopes, upsertCommand
-
Field Details
-
LOG
public static final org.slf4j.Logger LOG -
shutdownReason
-
-
Constructor Details
-
JDAImpl
-
JDAImpl
public JDAImpl(AuthorizationConfig authConfig, SessionConfig sessionConfig, ThreadingConfig threadConfig, MetaConfig metaConfig, RestConfig restConfig)
-
-
Method Details
-
handleEvent
-
isRawEvents
public boolean isRawEvents() -
isEventPassthrough
public boolean isEventPassthrough() -
isCacheFlagSet
-
isIntent
-
getLargeThreshold
public int getLargeThreshold() -
getMaxBufferSize
public int getMaxBufferSize() -
chunkGuild
public boolean chunkGuild(long id) -
setChunkingFilter
-
cacheMember
-
setMemberCachePolicy
-
getSessionController
-
getGuildSetupController
-
getVoiceInterceptor
-
usedPrivateChannel
public void usedPrivateChannel(long id) -
initRequester
public void initRequester() -
login
public int login() -
login
public int login(JDA.ShardInfo shardInfo, Compression compression, boolean validateToken, int intents, GatewayEncoding encoding) -
login
public int login(String gatewayUrl, JDA.ShardInfo shardInfo, Compression compression, boolean validateToken, int intents, GatewayEncoding encoding) -
getGateway
-
getShardedGateway
-
getContextMap
-
setContext
public void setContext() -
setToken
-
setStatus
-
verifyToken
public void verifyToken() -
getAuthorizationConfig
-
getToken
Description copied from interface:JDA
The login token that is currently being used for Discord authentication. -
isBulkDeleteSplittingEnabled
public boolean isBulkDeleteSplittingEnabled()Description copied from interface:JDA
Used to determine if JDA will process MESSAGE_DELETE_BULK messages received from Discord as a singleMessageBulkDeleteEvent
or split the deleted messages up and fire multipleMessageDeleteEvents
, one for each deleted message.By default, 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
- Specified by:
isBulkDeleteSplittingEnabled
in interfaceJDA
- Returns:
- Whether or not JDA currently handles the BULK_MESSAGE_DELETE event by splitting it into individual MessageDeleteEvents or not.
-
setAutoReconnect
public void setAutoReconnect(boolean autoReconnect) Description copied from interface:JDA
Sets whether or not JDA should try to automatically reconnect if a connection-error is encountered.
This will use an incremental reconnect (timeouts are increased each time an attempt fails).Default is true.
- Specified by:
setAutoReconnect
in interfaceJDA
- Parameters:
autoReconnect
- If true - enables autoReconnect
-
setRequestTimeoutRetry
public void setRequestTimeoutRetry(boolean retryOnTimeout) Description copied from interface:JDA
Whether the Requester should retry when aSocketTimeoutException
occurs.- Specified by:
setRequestTimeoutRetry
in interfaceJDA
- Parameters:
retryOnTimeout
- True, if the Request should retry once on a socket timeout
-
isAutoReconnect
public boolean isAutoReconnect()Description copied from interface:JDA
Used to determine whether or not autoReconnect is enabled for JDA.- Specified by:
isAutoReconnect
in interfaceJDA
- Returns:
- True if JDA will attempt to automatically reconnect when a connection-error is encountered.
-
getStatus
Description copied from interface:JDA
Gets the currentStatus
of the JDA instance. -
getGatewayIntents
Description copied from interface:JDA
TheGatewayIntents
for this JDA session.- Specified by:
getGatewayIntents
in interfaceJDA
- Returns:
EnumSet
of active gateway intents
-
getCacheFlags
Description copied from interface:JDA
Thecache flags
that have been enabled for this JDA session.- Specified by:
getCacheFlags
in interfaceJDA
- Returns:
- Copy of the EnumSet of cache flags for this session
-
unloadUser
public boolean unloadUser(long userId) Description copied from interface:JDA
Attempts to remove the user with the provided id from the cache.
If you attempt to remove theSelfUser
this will simply returnfalse
.This should be used by an implementation of
MemberCachePolicy
as an upstream request to remove a member.- Specified by:
unloadUser
in interfaceJDA
- Parameters:
userId
- The target user id- Returns:
- True, if the cache was changed
-
getGatewayPing
public long getGatewayPing()Description copied from interface:JDA
The time in milliseconds that discord took to respond to our last heartbeat
This roughly represents the WebSocket ping of this sessionRestAction
request times do not correlate to this value!The
GatewayPingEvent
indicates an update to this value.- Specified by:
getGatewayPing
in interfaceJDA
- Returns:
- time in milliseconds between heartbeat and the heartbeat ack response
- See Also:
-
awaitStatus
@Nonnull public JDA awaitStatus(@Nonnull JDA.Status status, @Nonnull JDA.Status... failOn) throws InterruptedException Description copied from interface:JDA
This method will block until JDA has reached the specified connection status.Login Cycle
- Specified by:
awaitStatus
in interfaceJDA
- Parameters:
status
- The init status to wait for, once JDA has reached the specified stage of the startup cycle this method will return.failOn
- Optional failure states that will force a premature return- Returns:
- The current JDA instance, for chaining convenience
- Throws:
InterruptedException
- If this thread is interrupted while waiting
-
awaitShutdown
Description copied from interface:JDA
Blocks the current thread untilJDA.getStatus()
returnsJDA.Status.SHUTDOWN
.
This can be useful in certain situations like disabling class loading.Note that shutdown time depends on the length of the rate-limit queue. You can use
JDA.shutdownNow()
to cancel all pending requests and immediately shutdown.Example
jda.shutdown(); // Allow at most 10 seconds for remaining requests to finish if (!jda.awaitShutdown(10, TimeUnit.SECONDS)) { jda.shutdownNow(); // Cancel all remaining requests jda.awaitShutdown(); // Wait until shutdown is complete (indefinitely) }
This will not implicitly call
shutdown()
, you are responsible to ensure that the shutdown process has started.- Specified by:
awaitShutdown
in interfaceJDA
- Parameters:
timeout
- The maximum time to wait, or 0 to wait indefinitelyunit
- The time unit for the duration- Returns:
- False, if the timeout has elapsed before the shutdown has completed, true otherwise.
- Throws:
InterruptedException
- If the current thread is interrupted while waiting
-
cancelRequests
public int cancelRequests()Description copied from interface:JDA
Cancels all currently scheduledRestAction
requests.
When aRestAction
is cancelled, aCancellationException
will be provided to the failure callback. This meansRestAction.queue(Consumer, Consumer)
will invoke the second callback andRestAction.complete()
will throw an exception.This is only recommended as an extreme last measure to avoid backpressure. If you want to stop requests on shutdown you should use
JDA.shutdownNow()
instead of this method.- Specified by:
cancelRequests
in interfaceJDA
- Returns:
- how many requests were cancelled
- See Also:
-
getRateLimitPool
Description copied from interface:JDA
ScheduledExecutorService
used to handle rate-limits forRestAction
executions. This is also used in other parts of JDA related to http requests.- Specified by:
getRateLimitPool
in interfaceJDA
- Returns:
- The
ScheduledExecutorService
used for http request handling
-
getGatewayPool
Description copied from interface:JDA
ScheduledExecutorService
used to send WebSocket messages to discord.
This involves initial setup of guilds as well as keeping the connection alive.- Specified by:
getGatewayPool
in interfaceJDA
- Returns:
- The
ScheduledExecutorService
used for WebSocket transmissions
-
getCallbackPool
Description copied from interface:JDA
ExecutorService
used to handleRestAction
callbacks and completions. This is also used for handlingMessage.Attachment
downloads when needed.
By default this uses theCommonPool
of the runtime.- Specified by:
getCallbackPool
in interfaceJDA
- Returns:
- The
ExecutorService
used for callbacks
-
getHttpClient
Description copied from interface:JDA
TheOkHttpClient
used for handling http requests fromRestActions
.- Specified by:
getHttpClient
in interfaceJDA
- Returns:
- The http client
-
getDirectAudioController
Description copied from interface:JDA
Direct access to audio (dis-)connect requests.
This should not be used when normal audio operation is desired.The correct way to open and close an audio connection is through the
Guild's
AudioManager
.- Specified by:
getDirectAudioController
in interfaceJDA
- Returns:
- The
DirectAudioController
for this JDA instance
-
getMutualGuilds
Description copied from interface:JDA
Gets allGuilds
that contain all given users as their members.- Specified by:
getMutualGuilds
in interfaceJDA
- Parameters:
users
- The users which all the returnedGuilds
must contain.- Returns:
- Immutable list of all
Guild
instances which have allUsers
in them. - See Also:
-
getMutualGuilds
Description copied from interface:JDA
Gets allGuilds
that contain all given users as their members.- Specified by:
getMutualGuilds
in interfaceJDA
- Parameters:
users
- The users which all the returnedGuilds
must contain.- Returns:
- Immutable list of all
Guild
instances which have allUsers
in them.
-
retrieveUserById
Description copied from interface:JDA
Attempts to retrieve aUser
object based on the provided id.If
JDA.getUserById(long)
is cached, this will directly return the user in a completedRestAction
without making a request. When bothGUILD_PRESENCES
andGUILD_MEMBERS
intents are disabled this will always make a request even if the user is cached. You can useaction.useCache(false)
to force an update.The returned
RestAction
can encounter the following Discord errors:ErrorResponse.UNKNOWN_USER
Occurs when the provided id does not refer to aUser
known by Discord. Typically occurs when developers provide an incomplete id (cut short).
- Specified by:
retrieveUserById
in interfaceJDA
- Parameters:
id
- The id of the requestedUser
.- Returns:
CacheRestAction
- Type:User
On request, gets the User with id matching provided id from Discord.
-
getAudioManagerCache
Description copied from interface:JDA
CacheView
of all cachedAudioManagers
created for this JDA instance.
AudioManagers are created when first retrieved viaGuild.getAudioManager()
. Using this will perform better than callingGuild.getAudioManager()
iteratively as that would cause many useless audio managers to be created!AudioManagers are cross-session persistent!
- Specified by:
getAudioManagerCache
in interfaceJDA
- Returns:
CacheView
-
getGuildCache
Description copied from interface:JDA
SnowflakeCacheView
of all cachedGuilds
visible to this JDA session.- Specified by:
getGuildCache
in interfaceJDA
- Returns:
SnowflakeCacheView
-
getRoleCache
Description copied from interface:JDA
UnifiedSnowflakeCacheView
of all cachedRoles
visible to this JDA session.- Specified by:
getRoleCache
in interfaceJDA
- Returns:
- Unified
SnowflakeCacheView
- See Also:
-
getEmojiCache
Description copied from interface:JDA
UnifiedSnowflakeCacheView
of all cachedCustom Emojis
visible to this JDA session.- Specified by:
getEmojiCache
in interfaceJDA
- Returns:
- Unified
SnowflakeCacheView
- See Also:
-
createApplicationEmoji
@Nonnull public RestAction<ApplicationEmoji> createApplicationEmoji(@Nonnull String name, @Nonnull Icon icon) Description copied from interface:JDA
Creates a newApplicationEmoji
for this bot.Note that the bot is limited to 2000 Application Emojis (normal and animated).
- Specified by:
createApplicationEmoji
in interfaceJDA
- Parameters:
name
- The name for the new emoji (2-32 characters)icon
- TheIcon
for the new emoji- Returns:
RestAction
- Type:ApplicationEmoji
-
retrieveApplicationEmojis
Description copied from interface:JDA
Retrieves a list of Application Emojis together with their respective creators.- Specified by:
retrieveApplicationEmojis
in interfaceJDA
- Returns:
RestAction
- Type: List ofApplicationEmoji
-
retrieveApplicationEmojiById
Description copied from interface:JDA
Retrieves an application emoji together with its respective creator.- Specified by:
retrieveApplicationEmojiById
in interfaceJDA
- Parameters:
emojiId
- The emoji id- Returns:
RestAction
- Type:ApplicationEmoji
-
retrieveSticker
Description copied from interface:JDA
Attempts to retrieve aSticker
object based on the provided snowflake reference.
This works for bothStandardSticker
andGuildSticker
, and you can resolve them using the providedStickerUnion
.If the sticker is not one of the supported
Types
, the request fails withIllegalArgumentException
.The returned
RestAction
can encounter the following Discord errors:UNKNOWN_STICKER
Occurs when the provided id does not refer to a sticker known by Discord.
- Specified by:
retrieveSticker
in interfaceJDA
- Parameters:
sticker
- The reference of the requestedSticker
.
Can beRichSticker
,StickerItem
, orSticker.fromId(long)
.- Returns:
RestAction
- Type:StickerUnion
On request, gets the sticker with id matching provided id from Discord.
-
retrieveNitroStickerPacks
Description copied from interface:JDA
Retrieves a list of all the publicStickerPacks
used for nitro.- Specified by:
retrieveNitroStickerPacks
in interfaceJDA
- Returns:
RestAction
- Type: List ofStickerPack
-
getScheduledEventCache
Description copied from interface:JDA
SnowflakeCacheView
of all cachedScheduledEvents
visible to this JDA session.This requires
CacheFlag.SCHEDULED_EVENTS
to be enabled.- Specified by:
getScheduledEventCache
in interfaceJDA
- Returns:
SnowflakeCacheView
-
getChannelCache
Description copied from interface:IGuildChannelContainer
Unified cache of all channels associated with this shard or guild.This
ChannelCacheView
stores all channels in individually typed maps based onChannelType
. You can useChannelCacheView.getElementById(ChannelType, long)
orChannelCacheView.ofType(Class)
to filter out more specific types.- Specified by:
getChannelCache
in interfaceIGuildChannelContainer<Channel>
- Returns:
ChannelCacheView
-
getCategoryCache
Description copied from interface:IGuildChannelContainer
SortedSnowflakeCacheView
ofCategory
.
InGuild
cache, channels are sorted according to their position and id.This getter exists on any instance of
IGuildChannelContainer
and only checks the caches with the relevant scoping. ForGuild
,JDA
, orShardManager
, this returns the relevant channel with respect to the cache within each of those objects. For a guild, this would mean it only returns channels within the same guild.
If this is called onJDA
orShardManager
, this may return null immediately after building, because the cache isn't initialized yet. To make sure the cache is initialized after building yourJDA
instance, you can useJDA.awaitReady()
.- Specified by:
getCategoryCache
in interfaceIGuildChannelContainer<Channel>
- Returns:
SortedSnowflakeCacheView
-
getTextChannelCache
Description copied from interface:IGuildChannelContainer
SortedSnowflakeCacheView
ofTextChannel
.
InGuild
cache, channels are sorted according to their position and id.This getter exists on any instance of
IGuildChannelContainer
and only checks the caches with the relevant scoping. ForGuild
,JDA
, orShardManager
, this returns the relevant channel with respect to the cache within each of those objects. For a guild, this would mean it only returns channels within the same guild.
If this is called onJDA
orShardManager
, this may return null immediately after building, because the cache isn't initialized yet. To make sure the cache is initialized after building yourJDA
instance, you can useJDA.awaitReady()
.- Specified by:
getTextChannelCache
in interfaceIGuildChannelContainer<Channel>
- Returns:
SortedSnowflakeCacheView
-
getNewsChannelCache
Description copied from interface:IGuildChannelContainer
SortedSnowflakeCacheView
ofNewsChannel
.
InGuild
cache, channels are sorted according to their position and id.This getter exists on any instance of
IGuildChannelContainer
and only checks the caches with the relevant scoping. ForGuild
,JDA
, orShardManager
, this returns the relevant channel with respect to the cache within each of those objects. For a guild, this would mean it only returns channels within the same guild.
If this is called onJDA
orShardManager
, this may return null immediately after building, because the cache isn't initialized yet. To make sure the cache is initialized after building yourJDA
instance, you can useJDA.awaitReady()
.- Specified by:
getNewsChannelCache
in interfaceIGuildChannelContainer<Channel>
- Returns:
SortedSnowflakeCacheView
-
getVoiceChannelCache
Description copied from interface:IGuildChannelContainer
SortedSnowflakeCacheView
ofVoiceChannel
.
InGuild
cache, channels are sorted according to their position and id.This getter exists on any instance of
IGuildChannelContainer
and only checks the caches with the relevant scoping. ForGuild
,JDA
, orShardManager
, this returns the relevant channel with respect to the cache within each of those objects. For a guild, this would mean it only returns channels within the same guild.
If this is called onJDA
orShardManager
, this may return null immediately after building, because the cache isn't initialized yet. To make sure the cache is initialized after building yourJDA
instance, you can useJDA.awaitReady()
.- Specified by:
getVoiceChannelCache
in interfaceIGuildChannelContainer<Channel>
- Returns:
SortedSnowflakeCacheView
-
getStageChannelCache
Description copied from interface:IGuildChannelContainer
SortedSnowflakeCacheView
ofStageChannel
.
InGuild
cache, channels are sorted according to their position and id.This getter exists on any instance of
IGuildChannelContainer
and only checks the caches with the relevant scoping. ForGuild
,JDA
, orShardManager
, this returns the relevant channel with respect to the cache within each of those objects. For a guild, this would mean it only returns channels within the same guild.
If this is called onJDA
orShardManager
, this may return null immediately after building, because the cache isn't initialized yet. To make sure the cache is initialized after building yourJDA
instance, you can useJDA.awaitReady()
.- Specified by:
getStageChannelCache
in interfaceIGuildChannelContainer<Channel>
- Returns:
SortedSnowflakeCacheView
-
getThreadChannelCache
Description copied from interface:IGuildChannelContainer
SnowflakeCacheView
ofThreadChannel
.These threads can also represent posts in
ForumChannels
.This getter exists on any instance of
IGuildChannelContainer
and only checks the caches with the relevant scoping. ForGuild
,JDA
, orShardManager
, this returns the relevant channel with respect to the cache within each of those objects. For a guild, this would mean it only returns channels within the same guild.
If this is called onJDA
orShardManager
, this may return null immediately after building, because the cache isn't initialized yet. To make sure the cache is initialized after building yourJDA
instance, you can useJDA.awaitReady()
.- Specified by:
getThreadChannelCache
in interfaceIGuildChannelContainer<Channel>
- Returns:
SnowflakeCacheView
-
getForumChannelCache
Description copied from interface:IGuildChannelContainer
SnowflakeCacheView
ofForumChannel
.This getter exists on any instance of
IGuildChannelContainer
and only checks the caches with the relevant scoping. ForGuild
,JDA
, orShardManager
, this returns the relevant channel with respect to the cache within each of those objects. For a guild, this would mean it only returns channels within the same guild.
If this is called onJDA
orShardManager
, this may return null immediately after building, because the cache isn't initialized yet. To make sure the cache is initialized after building yourJDA
instance, you can useJDA.awaitReady()
.- Specified by:
getForumChannelCache
in interfaceIGuildChannelContainer<Channel>
- Returns:
SnowflakeCacheView
-
getMediaChannelCache
Description copied from interface:IGuildChannelContainer
SnowflakeCacheView
ofMediaChannel
.This getter exists on any instance of
IGuildChannelContainer
and only checks the caches with the relevant scoping. ForGuild
,JDA
, orShardManager
, this returns the relevant channel with respect to the cache within each of those objects. For a guild, this would mean it only returns channels within the same guild.
If this is called onJDA
orShardManager
, this may return null immediately after building, because the cache isn't initialized yet. To make sure the cache is initialized after building yourJDA
instance, you can useJDA.awaitReady()
.- Specified by:
getMediaChannelCache
in interfaceIGuildChannelContainer<Channel>
- Returns:
SnowflakeCacheView
-
getPrivateChannelCache
Description copied from interface:JDA
SnowflakeCacheView
of all cachedPrivateChannels
visible to this JDA session.- Specified by:
getPrivateChannelCache
in interfaceJDA
- Returns:
SnowflakeCacheView
-
getPrivateChannelById
Description copied from interface:JDA
This returns thePrivateChannel
which has the same id as the one provided.
If there is no knownPrivateChannel
with an id that matches the provided one, then this returnsnull
.- Specified by:
getPrivateChannelById
in interfaceJDA
- Parameters:
id
- The id of thePrivateChannel
.- Returns:
- Possibly-null
PrivateChannel
with matching id.
-
getPrivateChannelById
Description copied from interface:JDA
This returns thePrivateChannel
which has the same id as the one provided.
If there is no knownPrivateChannel
with an id that matches the provided one, then this returnsnull
.- Specified by:
getPrivateChannelById
in interfaceJDA
- Parameters:
id
- The id of thePrivateChannel
.- Returns:
- Possibly-null
PrivateChannel
with matching id.
-
getChannelById
Description copied from interface:IGuildChannelContainer
Get a channel of the specified type by id.This will automatically check for all channel types and cast to the specified class. If a channel with the specified id does not exist, or exists but is not an instance of the provided class, this returns null.
- Specified by:
getChannelById
in interfaceIGuildChannelContainer<Channel>
- Type Parameters:
T
- The type argument for the class- Parameters:
type
-Class
of a channel typeid
- The snowflake id of the channel- Returns:
- The casted channel, if it exists and is assignable to the provided class, or null
-
getGuildChannelById
Description copied from interface:IGuildChannelContainer
GetGuildChannel
for the provided ID.This getter exists on any instance of
IGuildChannelContainer
and only checks the caches with the relevant scoping. ForGuild
,JDA
, orShardManager
, this returns the relevant channel with respect to the cache within each of those objects. For a guild, this would mean it only returns channels within the same guild.
If this is called onJDA
orShardManager
, this may return null immediately after building, because the cache isn't initialized yet. To make sure the cache is initialized after building yourJDA
instance, you can useJDA.awaitReady()
.To get more specific channel types you can use one of the following:
IGuildChannelContainer.getChannelById(Class, long)
IGuildChannelContainer.getTextChannelById(long)
IGuildChannelContainer.getNewsChannelById(long)
IGuildChannelContainer.getStageChannelById(long)
IGuildChannelContainer.getVoiceChannelById(long)
IGuildChannelContainer.getCategoryById(long)
IGuildChannelContainer.getForumChannelById(long)
- Specified by:
getGuildChannelById
in interfaceIGuildChannelContainer<Channel>
- Parameters:
id
- The ID of the channel- Returns:
- The GuildChannel or null
-
getGuildChannelById
Description copied from interface:IGuildChannelContainer
GetGuildChannel
for the provided ID.This getter exists on any instance of
IGuildChannelContainer
and only checks the caches with the relevant scoping. ForGuild
,JDA
, orShardManager
, this returns the relevant channel with respect to the cache within each of those objects. For a guild, this would mean it only returns channels within the same guild.
If this is called onJDA
orShardManager
, this may return null immediately after building, because the cache isn't initialized yet. To make sure the cache is initialized after building yourJDA
instance, you can useJDA.awaitReady()
.
This is meant for systems that use a dynamicChannelType
and can profit from a simple function to get the channel instance.To get more specific channel types you can use one of the following:
IGuildChannelContainer.getChannelById(Class, long)
IGuildChannelContainer.getTextChannelById(long)
IGuildChannelContainer.getNewsChannelById(long)
IGuildChannelContainer.getStageChannelById(long)
IGuildChannelContainer.getVoiceChannelById(long)
IGuildChannelContainer.getCategoryById(long)
IGuildChannelContainer.getForumChannelById(long)
- Specified by:
getGuildChannelById
in interfaceIGuildChannelContainer<Channel>
- Parameters:
type
- TheChannelType
id
- The ID of the channel- Returns:
- The GuildChannel or null
-
openPrivateChannelById
Description copied from interface:JDA
Opens aPrivateChannel
with the provided user by id.
This will fail withUNKNOWN_USER
if the user does not exist.If the channel is cached, this will directly return the channel in a completed
RestAction
without making a request. You can useaction.useCache(false)
to force an update.Example
public void sendMessage(JDA jda, long userId, String content) { jda.openPrivateChannelById(userId) .flatMap(channel -> channel.sendMessage(content)) .queue(); }
- Specified by:
openPrivateChannelById
in interfaceJDA
- Parameters:
userId
- The id of the target user- Returns:
CacheRestAction
- Type:PrivateChannel
- See Also:
-
getUserCache
Description copied from interface:JDA
SnowflakeCacheView
of all cachedUsers
visible to this JDA session.- Specified by:
getUserCache
in interfaceJDA
- Returns:
SnowflakeCacheView
-
hasSelfUser
public boolean hasSelfUser() -
getSelfUser
Description copied from interface:JDA
Returns the currently logged in account represented bySelfUser
.
Account settings cannot be modified using this object. If you wish to modify account settings please use the AccountManager which is accessible bySelfUser.getManager()
.- Specified by:
getSelfUser
in interfaceJDA
- Returns:
- The currently logged in account.
-
shutdownNow
public void shutdownNow()Description copied from interface:JDA
Shuts down this JDA instance instantly, closing all its connections. After this command is issued the JDA Instance can not be used anymore. This will also cancel all queuedRestActions
.If you want this instance to shutdown without cancelling enqueued RestActions use
shutdown()
This will interrupt the default JDA event thread, due to the gateway connection being interrupted.
- Specified by:
shutdownNow
in interfaceJDA
- See Also:
-
shutdown
public void shutdown()Description copied from interface:JDA
Shuts down this JDA instance, closing all its connections. After this command is issued the JDA Instance can not be used anymore. Already enqueuedRestActions
are still going to be executed.If you want this instance to shutdown without executing, use
shutdownNow()
This will interrupt the default JDA event thread, due to the gateway connection being interrupted.
-
shutdownInternals
-
shutdownRequester
public void shutdownRequester() -
getResponseTotal
public long getResponseTotal()Description copied from interface:JDA
This value is the total amount of JSON responses that discord has sent.
This value resets every time the websocket has to perform a full reconnect (not resume).- Specified by:
getResponseTotal
in interfaceJDA
- Returns:
- Never-negative long containing total response amount.
-
getMaxReconnectDelay
public int getMaxReconnectDelay()Description copied from interface:JDA
This value is the maximum amount of time, in seconds, that JDA will wait between reconnect attempts.
Can be set usingJDABuilder.setMaxReconnectDelay(int)
.- Specified by:
getMaxReconnectDelay
in interfaceJDA
- Returns:
- The maximum amount of time JDA will wait between reconnect attempts in seconds.
-
getShardInfo
Description copied from interface:JDA
The shard information used when creating this instance of JDA.
Represents the information provided toJDABuilder.useSharding(int, int)
.- Specified by:
getShardInfo
in interfaceJDA
- Returns:
- The shard information for this shard
-
getPresence
Description copied from interface:JDA
- Specified by:
getPresence
in interfaceJDA
- Returns:
- The never-null
Presence
for this session.
-
getEventManager
Description copied from interface:JDA
The EventManager used by this JDA instance.- Specified by:
getEventManager
in interfaceJDA
- Returns:
- The
IEventManager
-
setEventManager
Description copied from interface:JDA
Changes the internal EventManager.The default EventManager is
InterfacedEventListener
.
There is also anAnnotatedEventManager
available.- Specified by:
setEventManager
in interfaceJDA
- Parameters:
eventManager
- The new EventManager to use
-
addEventListener
Description copied from interface:JDA
Adds all provided listeners to the event-listeners that will be used to handle events. This uses theInterfacedEventListener
by default. To switch to theAnnotatedEventManager
, useJDA.setEventManager(IEventManager)
.Note: when using the
InterfacedEventListener
(default), given listener must be instance ofEventListener
!- Specified by:
addEventListener
in interfaceJDA
- Parameters:
listeners
- The listener(s) which will react to events.
-
removeEventListener
Description copied from interface:JDA
Removes all provided listeners from the event-listeners and no longer uses them to handle events.- Specified by:
removeEventListener
in interfaceJDA
- Parameters:
listeners
- The listener(s) to be removed.
-
getRegisteredListeners
Description copied from interface:JDA
Immutable List of Objects that have been registered as EventListeners.- Specified by:
getRegisteredListeners
in interfaceJDA
- Returns:
- List of currently registered Objects acting as EventListeners.
-
listenOnce
Description copied from interface:JDA
Returns a reusable builder for a one-time event listener.Note that this method only works if the
event manager
is either theInterfacedEventManager
orAnnotatedEventManager
.
Other implementations can support it as long as they callEventListener.onEvent(GenericEvent)
.Example:
Listening to a message from a channel and a user, after using a slash command:
final Duration timeout = Duration.ofSeconds(5); event.reply("Reply in " + TimeFormat.RELATIVE.after(timeout) + " if you can!") .setEphemeral(true) .queue(); event.getJDA().listenOnce(MessageReceivedEvent.class) .filter(messageEvent -> messageEvent.getChannel().getIdLong() == event.getChannel().getIdLong()) .filter(messageEvent -> messageEvent.getAuthor().getIdLong() == event.getUser().getIdLong()) .timeout(timeout, () -> { event.getHook().editOriginal("Timeout!").queue(); }) .subscribe(messageEvent -> { event.getHook().editOriginal("You sent: " + messageEvent.getMessage().getContentRaw()).queue(); });
- Specified by:
listenOnce
in interfaceJDA
- Parameters:
eventType
- Type of the event to listen to- Returns:
- The one-time event listener builder
-
retrieveCommands
Description copied from interface:JDA
Retrieves the list of global commands.
This list does not include guild commands! UseGuild.retrieveCommands()
for guild commands.- Specified by:
retrieveCommands
in interfaceJDA
- Parameters:
withLocalizations
-true
if the localization data (such as name and description) should be included- Returns:
RestAction
- Type:List
ofCommand
-
retrieveCommandById
Description copied from interface:JDA
Retrieves the existingCommand
instance by id.If there is no command with the provided ID, this RestAction fails with
ErrorResponse.UNKNOWN_COMMAND
- Specified by:
retrieveCommandById
in interfaceJDA
- Parameters:
id
- The command id- Returns:
RestAction
- Type:Command
-
upsertCommand
Description copied from interface:JDA
Creates or updates a global command.
If a command with the same name exists, it will be replaced. This operation is idempotent. Commands will persist between restarts of your bot, you only have to create a command once.To specify a complete list of all commands you can use
JDA.updateCommands()
instead.You need the OAuth2 scope
"applications.commands"
in order to add commands to a guild.- Specified by:
upsertCommand
in interfaceJDA
- Parameters:
command
- TheCommandData
for the command- Returns:
RestAction
- Type:Command
The RestAction used to create or update the command- See Also:
-
updateCommands
Description copied from interface:JDA
Configures the complete list of global commands.
This will replace the existing command list for this bot. You should only use this once on startup!This operation is idempotent. Commands will persist between restarts of your bot, you only have to create a command once.
You need the OAuth2 scope
"applications.commands"
in order to add commands to a guild.Examples
Set list to 2 commands:
jda.updateCommands() .addCommands(Commands.slash("ping", "Gives the current ping")) .addCommands(Commands.slash("ban", "Ban the target user") .setGuildOnly(true) .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.BAN_MEMBERS)) .addOption(OptionType.USER, "user", "The user to ban", true)) .queue();
Delete all commands:
jda.updateCommands().queue();
- Specified by:
updateCommands
in interfaceJDA
- Returns:
CommandListUpdateAction
- See Also:
-
editCommandById
Description copied from interface:JDA
Edit an existing global command by id.If there is no command with the provided ID, this RestAction fails with
ErrorResponse.UNKNOWN_COMMAND
- Specified by:
editCommandById
in interfaceJDA
- Parameters:
type
- The command typeid
- The id of the command to edit- Returns:
CommandEditAction
used to edit the command
-
deleteCommandById
Description copied from interface:JDA
Delete the global command for this id.If there is no command with the provided ID, this RestAction fails with
ErrorResponse.UNKNOWN_COMMAND
- Specified by:
deleteCommandById
in interfaceJDA
- Parameters:
commandId
- The id of the command that should be deleted- Returns:
RestAction
-
retrieveRoleConnectionMetadata
Description copied from interface:JDA
Retrieves the currently configuredRoleConnectionMetadata
records for this application.- Specified by:
retrieveRoleConnectionMetadata
in interfaceJDA
- Returns:
RestAction
- Type:List
ofRoleConnectionMetadata
- See Also:
-
updateRoleConnectionMetadata
@Nonnull public RestAction<List<RoleConnectionMetadata>> updateRoleConnectionMetadata(@Nonnull Collection<? extends RoleConnectionMetadata> records) Description copied from interface:JDA
Updates the currently configuredRoleConnectionMetadata
records for this application.Returns the updated connection metadata records on success.
- Specified by:
updateRoleConnectionMetadata
in interfaceJDA
- Parameters:
records
- The new records to set- Returns:
RestAction
- Type:List
ofRoleConnectionMetadata
- See Also:
-
createGuild
Description copied from interface:JDA
Constructs a newGuild
with the specified name
Use the returnedGuildAction
to provide further details and settings for the resulting Guild!This RestAction does not provide the resulting Guild! It will be in a following
GuildJoinEvent
.- Specified by:
createGuild
in interfaceJDA
- Parameters:
name
- The name of the resulting guild- Returns:
GuildAction
Allows for setting various details for the resulting Guild
-
createGuildFromTemplate
@Nonnull public RestAction<Void> createGuildFromTemplate(@Nonnull String code, @Nonnull String name, Icon icon) Description copied from interface:JDA
Constructs a newGuild
from the specified template code.This RestAction does not provide the resulting Guild! It will be in a following
GuildJoinEvent
.Possible
ErrorResponses
include:Unknown Guild Template
The template doesn't exist.
- Specified by:
createGuildFromTemplate
in interfaceJDA
- Parameters:
code
- The template code to use to create a guildname
- The name of the resulting guildicon
- TheIcon
to use, or null to use no icon- Returns:
RestAction
-
retrieveWebhookById
Description copied from interface:JDA
Retrieves aWebhook
by its id.
If the webhook does not belong to any known guild of this JDA session, it will bepartial
.Possible
ErrorResponses
caused by the returnedRestAction
include the following:MISSING_PERMISSIONS
We do not have the required permissionsUNKNOWN_WEBHOOK
A webhook with this id does not exist
- Specified by:
retrieveWebhookById
in interfaceJDA
- Parameters:
webhookId
- The webhook id- Returns:
RestAction
- Type:Webhook
The webhook object.- See Also:
-
getApplicationManager
Description copied from interface:JDA
Returns theApplicationManager
that manages the application associated with the bot.
You modify multiple fields in one request by chaining setters before callingRestAction.queue()
.- Specified by:
getApplicationManager
in interfaceJDA
- Returns:
- The corresponding ApplicationManager
-
retrieveApplicationInfo
Description copied from interface:JDA
Retrieves theApplicationInfo
for the application that owns the logged in Bot-Account.
This contains information about the owner of the currently logged in bot account!- Specified by:
retrieveApplicationInfo
in interfaceJDA
- Returns:
RestAction
- Type:ApplicationInfo
TheApplicationInfo
of the bot's application.
-
retrieveEntitlements
Description copied from interface:JDA
APaginationAction
implementation which allows you toiterate
overEntitlement
s that are applicable to the logged in application.- Specified by:
retrieveEntitlements
in interfaceJDA
- Returns:
EntitlementPaginationAction
-
retrieveEntitlementById
Description copied from interface:JDA
Retrieves anEntitlement
by its id.- Specified by:
retrieveEntitlementById
in interfaceJDA
- Parameters:
entitlementId
- The id of the entitlement to retrieve- Returns:
RestAction
- Type:Entitlement
The entitlement with the provided id
-
createTestEntitlement
@Nonnull public TestEntitlementCreateAction createTestEntitlement(long skuId, long ownerId, @Nonnull TestEntitlementCreateAction.OwnerType ownerType) Description copied from interface:JDA
Constructs a newEntitlement
with the skuId and the type.
Use the returnedTestEntitlementCreateAction
to provide more details.- Specified by:
createTestEntitlement
in interfaceJDA
- Parameters:
skuId
- The id of the SKU the entitlement is forownerId
- The id of the owner of the entitlementownerType
- The type of the owner of the entitlement- Returns:
TestEntitlementCreateAction
Allows for setting various details for the resulting Entitlement
-
deleteTestEntitlement
Description copied from interface:JDA
Deletes a test entitlement by its id.- Specified by:
deleteTestEntitlement
in interfaceJDA
- Parameters:
entitlementId
- The id of the entitlement to delete- Returns:
RestAction
- Type: Void
-
setRequiredScopes
Description copied from interface:JDA
Configures the required scopes applied to theJDA.getInviteUrl(Permission...)
and similar methods.
To use slash commands you must add"applications.commands"
to these scopes. The scope"bot"
is always applied.- Specified by:
setRequiredScopes
in interfaceJDA
- Parameters:
scopes
- The scopes to use withJDA.getInviteUrl(Permission...)
and the likes- Returns:
- The current JDA instance
-
getInviteUrl
Description copied from interface:JDA
Creates an authorization invite url for the currently logged in Bot-Account.
Example Format:https://discord.com/oauth2/authorize?scope=bot&client_id=288202953599221761&permissions=8
Hint: To enable a pre-selected Guild of choice append the parameter
&guild_id=YOUR_GUILD_ID
- Specified by:
getInviteUrl
in interfaceJDA
- Parameters:
permissions
- The permissions to use in your invite, these can be changed by the link user.
If no permissions are provided thepermissions
parameter is omitted- Returns:
- A valid OAuth2 invite url for the currently logged in Bot-Account
-
getInviteUrl
Description copied from interface:JDA
Creates an authorization invite url for the currently logged in Bot-Account.
Example Format:https://discord.com/oauth2/authorize?scope=bot&client_id=288202953599221761&permissions=8
Hint: To enable a pre-selected Guild of choice append the parameter
&guild_id=YOUR_GUILD_ID
- Specified by:
getInviteUrl
in interfaceJDA
- Parameters:
permissions
- The permissions to use in your invite, these can be changed by the link user.
If no permissions are provided thepermissions
parameter is omitted- Returns:
- A valid OAuth2 invite url for the currently logged in Bot-Account
-
setShardManager
-
getShardManager
Description copied from interface:JDA
Returns theShardManager
that manages this JDA instances or null if this instance is not managed by anyShardManager
.- Specified by:
getShardManager
in interfaceJDA
- Returns:
- The corresponding ShardManager or
null
if there is no such manager
-
getEntityBuilder
-
getAudioSendFactory
-
setAudioSendFactory
-
setGatewayPing
public void setGatewayPing(long ping) -
getRequester
-
getWebSocketFactory
-
getClient
-
getUsersView
-
getGuildsView
-
getChannelsView
-
getAudioManagersView
-
setSelfUser
-
setResponseTotal
public void setResponseTotal(int responseTotal) -
getIdentifierString
-
getEventCache
-
getGatewayUrl
-
resetGatewayUrl
public void resetGatewayUrl() -
getAudioLifeCyclePool
-