Interface JDA

    • Method Detail

      • getCacheFlags

        @Nonnull
        EnumSet<CacheFlag> getCacheFlags()
        The cache flags that have been enabled for this JDA session.
        Returns:
        Copy of the EnumSet of cache flags for this session
      • unloadUser

        boolean unloadUser​(long userId)
        Attempts to remove the user with the provided id from the cache.
        If you attempt to remove the SelfUser this will simply return false.

        This should be used by an implementation of MemberCachePolicy as an upstream request to remove a member.

        Parameters:
        userId - The target user id
        Returns:
        True, if the cache was changed
      • getGatewayPing

        long getGatewayPing()
        The time in milliseconds that discord took to respond to our last heartbeat
        This roughly represents the WebSocket ping of this session

        RestAction request times do not correlate to this value!

        The GatewayPingEvent indicates an update to this value.

        Returns:
        time in milliseconds between heartbeat and the heartbeat ack response
        See Also:
        Getting RestAction ping
      • getRestPing

        @Nonnull
        default RestAction<Long> getRestPing()
        The time in milliseconds that discord took to respond to a REST request.
        This will request the current user from the API and calculate the time the response took.

        Example

        
         jda.getRestPing().queue( (time) ->
             channel.sendMessageFormat("Ping: %d ms", time).queue()
         );
         
        Returns:
        RestAction - Type: long
        Since:
        4.0.0
        See Also:
        getGatewayPing()
      • getHttpClient

        @Nonnull
        okhttp3.OkHttpClient getHttpClient()
        The OkHttpClient used for handling http requests from RestActions.
        Returns:
        The http client
        Since:
        4.0.0
      • removeEventListener

        void removeEventListener​(@Nonnull
                                 Object... listeners)
        Removes all provided listeners from the event-listeners and no longer uses them to handle events.
        Parameters:
        listeners - The listener(s) to be removed.
        Throws:
        IllegalArgumentException - If either listeners or one of it's objects is null.
      • getRegisteredListeners

        @Nonnull
        List<Object> getRegisteredListeners()
        Immutable List of Objects that have been registered as EventListeners.
        Returns:
        List of currently registered Objects acting as EventListeners.
      • upsertCommand

        @Nonnull
        @CheckReturnValue
        default CommandCreateAction upsertCommand​(@Nonnull
                                                  String name,
                                                  @Nonnull
                                                  String description)
        Creates or updates a global slash 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 updateCommands() instead.

        You need the OAuth2 scope "applications.commands" in order to add commands to a guild.

        Global commands can take up to 1 hour to propagate to the clients. For testing, it is recommended to use a test guild with guild commands.

        Parameters:
        name - The lowercase alphanumeric (with dash) name, 1-32 characters
        description - The description for the command, 1-100 characters
        Returns:
        CommandCreateAction
        Throws:
        IllegalArgumentException - If null is provided or the name/description do not meet the requirements
        See Also:
        Guild.upsertCommand(String, String)
      • updateCommands

        @Nonnull
        @CheckReturnValue
        CommandListUpdateAction updateCommands()
        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.

        Global commands can take up to 1 hour to propagate to the clients. For testing, it is recommended to use a test guild with guild commands.

        Examples

        
         // Set list to 2 commands
         jda.updateCommands()
           .addCommands(Commands.slash("ping", "Gives the current ping"))
           .addCommands(Commands.slash("ban", "Ban the target user")
             .addOption(OptionType.USER, "user", "The user to ban", true))
           .queue();
         // Delete all commands
         jda.updateCommands().queue();
         
        Returns:
        CommandListUpdateAction
        See Also:
        Guild.updateCommands()
      • editCommandById

        @Nonnull
        @CheckReturnValue
        default CommandEditAction editCommandById​(long id)
        Edit an existing global command by id.

        If there is no command with the provided ID, this RestAction fails with ErrorResponse.UNKNOWN_COMMAND

        Global commands can take up to 1 hour to propagate to the clients. For testing, it is recommended to use a test guild with guild commands.

        Parameters:
        id - The id of the command to edit
        Returns:
        CommandEditAction used to edit the command
      • deleteCommandById

        @Nonnull
        @CheckReturnValue
        default RestAction<Void> deleteCommandById​(long commandId)
        Delete the global command for this id.

        If there is no command with the provided ID, this RestAction fails with ErrorResponse.UNKNOWN_COMMAND

        Global commands can take up to 1 hour to propagate to the clients. For testing, it is recommended to use a test guild with guild commands.

        Parameters:
        commandId - The id of the command that should be deleted
        Returns:
        RestAction
      • getAudioManagerCache

        @Nonnull
        CacheView<AudioManager> getAudioManagerCache()
        CacheView of all cached AudioManagers created for this JDA instance.
        AudioManagers are created when first retrieved via Guild.getAudioManager(). Using this will perform better than calling Guild.getAudioManager() iteratively as that would cause many useless audio managers to be created!

        AudioManagers are cross-session persistent!

        Returns:
        CacheView
      • getAudioManagers

        @Nonnull
        default List<AudioManager> getAudioManagers()
        Immutable list of all created AudioManagers for this JDA instance!
        Returns:
        Immutable list of all created AudioManager instances
      • getUsers

        @Nonnull
        default List<User> getUsers()
        An immutable list of all Users that share a Guild with the currently logged in account.
        This list will never contain duplicates and represents all Users that JDA can currently see.

        This will only check cached users!

        If the developer is sharding, then only users from guilds connected to the specifically logged in shard will be returned in the List.

        This copies the backing store into a list. This means every call creates a new list with O(n) complexity. It is recommended to store this into a local variable or use getUserCache() and use its more efficient versions of handling these values.

        Returns:
        Immutable list of all Users that are visible to JDA.
      • getUserById

        @Nullable
        default User getUserById​(long id)
        This returns the User which has the same id as the one provided.
        If there is no visible user with an id that matches the provided one, this returns null.

        This will only check cached users!

        Parameters:
        id - The id of the requested User.
        Returns:
        Possibly-null User with matching id.
        See Also:
        retrieveUserById(long)
      • getUserByTag

        @Nullable
        default User getUserByTag​(@Nonnull
                                  String tag)
        Searches for a user that has the matching Discord Tag.
        Format has to be in the form Username#Discriminator where the username must be between 2 and 32 characters (inclusive) matching the exact casing and the discriminator must be exactly 4 digits.

        This only checks users that are known to the currently logged in account (shard). If a user exists with the tag that is not available in the User-Cache it will not be detected.
        Currently Discord does not offer a way to retrieve a user by their discord tag.

        This will only check cached users!

        Parameters:
        tag - The Discord Tag in the format Username#Discriminator
        Returns:
        The User for the discord tag or null if no user has the provided tag
        Throws:
        IllegalArgumentException - If the provided tag is null or not in the described format
      • getUserByTag

        @Nullable
        default User getUserByTag​(@Nonnull
                                  String username,
                                  @Nonnull
                                  String discriminator)
        Searches for a user that has the matching Discord Tag.
        Format has to be in the form Username#Discriminator where the username must be between 2 and 32 characters (inclusive) matching the exact casing and the discriminator must be exactly 4 digits.

        This only checks users that are known to the currently logged in account (shard). If a user exists with the tag that is not available in the User-Cache it will not be detected.
        Currently Discord does not offer a way to retrieve a user by their discord tag.

        This will only check cached users!

        Parameters:
        username - The name of the user
        discriminator - The discriminator of the user
        Returns:
        The User for the discord tag or null if no user has the provided tag
        Throws:
        IllegalArgumentException - If the provided arguments are null or not in the described format
      • getUsersByName

        @Nonnull
        default List<User> getUsersByName​(@Nonnull
                                          String name,
                                          boolean ignoreCase)
        This immutable returns all Users that have the same username as the one provided.
        If there are no Users with the provided name, then this returns an empty list.

        This will only check cached users!

        Note: This does **not** consider nicknames, it only considers User.getName()

        Parameters:
        name - The name of the requested Users.
        ignoreCase - Whether to ignore case or not when comparing the provided name to each User.getName().
        Returns:
        Possibly-empty immutable list of Users that all have the same name as the provided name.
      • getMutualGuilds

        @Nonnull
        List<Guild> getMutualGuilds​(@Nonnull
                                    Collection<User> users)
        Gets all Guilds that contain all given users as their members.
        Parameters:
        users - The users which all the returned Guilds must contain.
        Returns:
        Immutable list of all Guild instances which have all Users in them.
      • retrieveUserById

        @Nonnull
        @CheckReturnValue
        RestAction<User> retrieveUserById​(long id,
                                          boolean update)
        Attempts to retrieve a User object based on the provided id.
        If both GUILD_MEMBERS and GUILD_PRESENCES intents are disabled this method will update the cached user unless the update parameter is false.
        If either of those intents is enabled, this will immediately provide the cached user if possible.

        The returned RestAction can encounter the following Discord errors:

        • ErrorResponse.UNKNOWN_USER
          Occurs when the provided id does not refer to a User known by Discord. Typically occurs when developers provide an incomplete id (cut short).
        Parameters:
        id - The id of the requested User.
        update - Whether JDA should perform a request even if the member is already cached to update properties such as the name
        Returns:
        RestAction - Type: User
        On request, gets the User with id matching provided id from Discord.
        Throws:
        AccountTypeException - This endpoint is AccountType.BOT only.
      • getGuilds

        @Nonnull
        default List<Guild> getGuilds()
        An immutable List of all Guilds that the logged account is connected to.
        If this account is not connected to any Guilds, this will return an empty list.

        If the developer is sharding (JDABuilder.useSharding(int, int), then this list will only contain the Guilds that the shard is actually connected to. Discord determines which guilds a shard is connect to using the following format:
        Guild connected if shardId == (guildId >> 22) % totalShards;
        Source for formula: Discord Documentation

        This copies the backing store into a list. This means every call creates a new list with O(n) complexity. It is recommended to store this into a local variable or use getGuildCache() and use its more efficient versions of handling these values.

        Returns:
        Possibly-empty immutable list of all the Guilds that this account is connected to.
      • getGuildById

        @Nullable
        default Guild getGuildById​(long id)
        This returns the Guild which has the same id as the one provided.
        If there is no connected guild with an id that matches the provided one, then this returns null.
        Parameters:
        id - The id of the Guild.
        Returns:
        Possibly-null Guild with matching id.
      • getGuildsByName

        @Nonnull
        default List<Guild> getGuildsByName​(@Nonnull
                                            String name,
                                            boolean ignoreCase)
        An immutable list of all Guilds that have the same name as the one provided.
        If there are no Guilds with the provided name, then this returns an empty list.
        Parameters:
        name - The name of the requested Guilds.
        ignoreCase - Whether to ignore case or not when comparing the provided name to each Guild.getName().
        Returns:
        Possibly-empty immutable list of all the Guilds that all have the same name as the provided name.
      • getUnavailableGuilds

        @Nonnull
        Set<String> getUnavailableGuilds()
        Set of Guild IDs for guilds that were marked unavailable by the gateway.
        When a guild becomes unavailable a GuildUnavailableEvent is emitted and a GuildAvailableEvent is emitted when it becomes available again. During the time a guild is unavailable it its not reachable through cache such as getGuildById(long).
        Returns:
        Possibly-empty set of guild IDs for unavailable guilds
      • isUnavailable

        boolean isUnavailable​(long guildId)
        Whether the guild is unavailable. If this returns true, the guild id should be in getUnavailableGuilds().
        Parameters:
        guildId - The guild id
        Returns:
        True, if this guild is unavailable
      • getRoles

        @Nonnull
        default List<Role> getRoles()
        All Roles this JDA instance can see.
        This will iterate over each Guild retrieved from getGuilds() and collect its Guild.getRoles().

        This copies the backing store into a list. This means every call creates a new list with O(n) complexity. It is recommended to store this into a local variable or use getRoleCache() and use its more efficient versions of handling these values.

        Returns:
        Immutable List of all visible Roles
      • getRoleById

        @Nullable
        default Role getRoleById​(@Nonnull
                                 String id)
        Retrieves the Role associated to the provided id.
        This iterates over all Guilds and check whether a Role from that Guild is assigned to the specified ID and will return the first that can be found.
        Parameters:
        id - The id of the searched Role
        Returns:
        Possibly-null Role for the specified ID
        Throws:
        NumberFormatException - If the provided id cannot be parsed by Long.parseLong(String)
      • getRoleById

        @Nullable
        default Role getRoleById​(long id)
        Retrieves the Role associated to the provided id.
        This iterates over all Guilds and check whether a Role from that Guild is assigned to the specified ID and will return the first that can be found.
        Parameters:
        id - The id of the searched Role
        Returns:
        Possibly-null Role for the specified ID
      • getChannelById

        @Nullable
        default <T extends Channel> T getChannelById​(@Nonnull
                                                     Class<T> type,
                                                     long id)
        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 interface IGuildChannelContainer
        Type Parameters:
        T - The type argument for the class
        Parameters:
        type - Class of a channel type
        id - The snowflake id of the channel
        Returns:
        The casted channel, if it exists and is assignable to the provided class, or null
      • getPrivateChannels

        @Nonnull
        default List<PrivateChannel> getPrivateChannels()
        An unmodifiable list of all known PrivateChannels.

        This copies the backing store into a list. This means every call creates a new list with O(n) complexity. It is recommended to store this into a local variable or use getPrivateChannelCache() and use its more efficient versions of handling these values.

        Returns:
        Possibly-empty list of all PrivateChannels.
      • getEmoteById

        @Nullable
        default Emote getEmoteById​(long id)
        Retrieves an emote matching the specified id if one is available in our cache.
        This will be null if CacheFlag.EMOTE is disabled.

        Unicode emojis are not included as Emote!

        Parameters:
        id - The id of the requested Emote.
        Returns:
        An Emote represented by this id or null if none is found in our cache.
      • getEmotesByName

        @Nonnull
        default List<Emote> getEmotesByName​(@Nonnull
                                            String name,
                                            boolean ignoreCase)
        An unmodifiable list of all Emotes that have the same name as the one provided.
        If there are no Emotes with the provided name, then this returns an empty list.
        This will be empty if CacheFlag.EMOTE is disabled.

        Unicode emojis are not included as Emote!

        Parameters:
        name - The name of the requested Emotes. Without colons.
        ignoreCase - Whether to ignore case or not when comparing the provided name to each Emote.getName().
        Returns:
        Possibly-empty list of all the Emotes that all have the same name as the provided name.
      • getSelfUser

        @Nonnull
        SelfUser getSelfUser()
        Returns the currently logged in account represented by SelfUser.
        Account settings cannot be modified using this object. If you wish to modify account settings please use the AccountManager which is accessible by SelfUser.getManager().
        Returns:
        The currently logged in account.
      • getToken

        @Nonnull
        String getToken()
        The login token that is currently being used for Discord authentication.
        Returns:
        Never-null, 18 character length string containing the auth token.
      • getResponseTotal

        long getResponseTotal()
        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).
        Returns:
        Never-negative long containing total response amount.
      • getMaxReconnectDelay

        int getMaxReconnectDelay()
        This value is the maximum amount of time, in seconds, that JDA will wait between reconnect attempts.
        Can be set using JDABuilder.setMaxReconnectDelay(int).
        Returns:
        The maximum amount of time JDA will wait between reconnect attempts in seconds.
      • setAutoReconnect

        void setAutoReconnect​(boolean reconnect)
        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.

        Parameters:
        reconnect - If true - enables autoReconnect
      • setRequestTimeoutRetry

        void setRequestTimeoutRetry​(boolean retryOnTimeout)
        Whether the Requester should retry when a SocketTimeoutException occurs.
        Parameters:
        retryOnTimeout - True, if the Request should retry once on a socket timeout
      • isAutoReconnect

        boolean isAutoReconnect()
        USed to determine whether or not autoReconnect is enabled for JDA.
        Returns:
        True if JDA will attempt to automatically reconnect when a connection-error is encountered.
      • isBulkDeleteSplittingEnabled

        boolean isBulkDeleteSplittingEnabled()
        Used to determine if JDA will process MESSAGE_DELETE_BULK messages received from Discord as a single MessageBulkDeleteEvent or split the deleted messages up and fire multiple MessageDeleteEvents, 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

        Returns:
        Whether or not JDA currently handles the BULK_MESSAGE_DELETE event by splitting it into individual MessageDeleteEvents or not.
      • shutdown

        void shutdown()
        Shuts down this JDA instance, closing all its connections. After this command is issued the JDA Instance can not be used anymore. Already enqueued RestActions 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.

        See Also:
        shutdownNow()
      • shutdownNow

        void shutdownNow()
        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 queued RestActions.

        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.

        See Also:
        shutdown()
      • getAccountType

        @Nonnull
        AccountType getAccountType()
        The AccountType of the currently logged in account.
        Used when determining functions that are restricted based on the type of account.
        Returns:
        The current AccountType.
      • getInviteUrl

        @Nonnull
        String getInviteUrl​(@Nullable
                            Permission... permissions)
        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

        Parameters:
        permissions - The permissions to use in your invite, these can be changed by the link user.
        If no permissions are provided the permissions parameter is omitted
        Returns:
        A valid OAuth2 invite url for the currently logged in Bot-Account
        Throws:
        AccountTypeException - If the currently logged in account is not from AccountType.BOT
      • getInviteUrl

        @Nonnull
        String getInviteUrl​(@Nullable
                            Collection<Permission> permissions)
        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

        Parameters:
        permissions - The permissions to use in your invite, these can be changed by the link user.
        If no permissions are provided the permissions parameter is omitted
        Returns:
        A valid OAuth2 invite url for the currently logged in Bot-Account
        Throws:
        AccountTypeException - If the currently logged in account is not from AccountType.BOT
      • getShardManager

        @Nullable
        ShardManager getShardManager()
        Returns the ShardManager that manages this JDA instances or null if this instance is not managed by any ShardManager.
        Returns:
        The corresponding ShardManager or null if there is no such manager