Class GatewayDiscordClient

  • All Implemented Interfaces:
    EntityRetriever

    public class GatewayDiscordClient
    extends Object
    implements EntityRetriever
    An aggregation of all dependencies Discord4J requires to operate with the Discord Gateway, REST API and Voice Gateway. Maintains a set of connections to every shard logged in from the same GatewayBootstrap and therefore tracks state updates from all connected shards.

    The following are some of the resources available through this aggregate:

    • Method Detail

      • getGatewayClient

        public Optional<GatewayClient> getGatewayClient​(int shardId)
        Returns a GatewayClient instance created by this GatewayDiscordClient, which is associated to a given shard index.
        Parameters:
        shardId - the shard index used to get the client instance
        Returns:
        a GatewayClient instance represented by the given shard, if present
      • getRestClient

        public RestClient getRestClient()
        Returns the RestClient used to execute REST API requests.
        Returns:
        the RestClient tied to this Gateway client.
      • getWebhookById

        public Mono<Webhook> getWebhookById​(Snowflake webhookId)
        Requests to retrieve the webhook represented by the supplied ID. The bot must have the MANAGE_WEBHOOKS permission in the webhook's channel.
        Parameters:
        webhookId - The ID of the webhook.
        Returns:
        A Mono where, upon successful completion, emits the Webhook as represented by the supplied ID. If an error is received, it is emitted through the Mono.
      • getWebhookByIdWithToken

        public Mono<Webhook> getWebhookByIdWithToken​(Snowflake webhookId,
                                                     String token)
        Requests to retrieve the webhook represented by the supplied ID and token. Doesn't return the user who created the webhook object. Doesn't require the bot to have the MANAGE_WEBHOOKS permission.
        Parameters:
        webhookId - The ID of the webhook.
        token - The authentication token of the webhook.
        Returns:
        A Mono where, upon successful completion, emits the Webhook as represented by the supplied ID without the user field and with the token field. If an error is received, it is emitted through the Mono.
      • getApplicationInfo

        public Mono<ApplicationInfo> getApplicationInfo()
        Requests to retrieve the application info.
        Returns:
        A Mono where, upon successful completion, emits the application info. If an error is received, it is emitted through the Mono.
      • getUsers

        public Flux<User> getUsers()
        Retrieve the currently stored (cached) users.
        Returns:
        A Flux that continually emits the users that the current client has stored. If an error is received, it is emitted through the Flux.
      • getRegions

        public Flux<Region> getRegions()
        Requests to retrieve the voice regions that are available.
        Returns:
        A Flux that continually emits the regions that are available. If an error is received, it is emitted through the Flux.
      • getTemplateByCode

        public Mono<GuildTemplate> getTemplateByCode​(String templateCode)
        Requests to retrieve the template represented by the supplied code.
        Parameters:
        templateCode - The code of the template.
        Returns:
        A Mono where, upon successful completion, emits the GuildTemplate as represented by the supplied code. If an error is received, it is emitted through the Mono.
      • getSelfId

        public Snowflake getSelfId()
        Gets the bot user's ID.
        Returns:
        The bot user's ID.
      • createGuild

        public discord4j.core.spec.GuildCreateMono createGuild​(String name,
                                                               Region region)
        Requests to create a guild. Properties specifying how to create the guild can be set via the withXxx methods of the returned GuildCreateMono.
        Parameters:
        name - the name of the guild to create
        region - the region of the guild to create
        Returns:
        A GuildCreateMono where, upon successful completion, emits the created Guild. If an error is received, it is emitted through the GuildCreateMono.
      • createGuild

        public Mono<Guild> createGuild​(discord4j.core.spec.GuildCreateSpec spec)
        Requests to create a guild.
        Parameters:
        spec - an immutable object that specifies how to create the guild
        Returns:
        A Mono where, upon successful completion, emits the created Guild. If an error is received, it is emitted through the Mono.
      • updatePresence

        public Mono<Void> updatePresence​(ClientPresence clientPresence)
        Update the bot's ClientPresence (client status) for every shard in this shard group.
        Parameters:
        clientPresence - The updated client status.
        Returns:
        A Mono that signals completion upon successful update. If an error is received, it is emitted through the Mono.
      • updatePresence

        public Mono<Void> updatePresence​(ClientPresence clientPresence,
                                         int shardId)
        Update the bot's Presence (status) for the given shard index, provided it belongs in this shard group.
        Parameters:
        clientPresence - The updated client presence.
        Returns:
        A Mono that signals completion upon successful update. If an error is received, it is emitted through the Mono.
      • getInvite

        public Mono<Invite> getInvite​(String inviteCode)
        Requests to retrieve an invite.
        Parameters:
        inviteCode - The code for the invite (e.g. "xdYkpp").
        Returns:
        A Mono where, upon successful completion, emits the Invite as represented by the supplied invite code. If an error is received, it is emitted through the Mono.
      • edit

        public discord4j.core.spec.UserEditMono edit()
        Requests to edit this client (i.e., modify the current bot user). Properties specifying how to edit this client can be set via the withXxx methods of the returned UserEditMono.
        Returns:
        A Mono where, upon successful completion, emits the edited User. If an error is received, it is emitted through the Mono.
      • edit

        public Mono<User> edit​(discord4j.core.spec.UserEditSpec spec)
        Requests to edit this client (i.e., modify the current bot user).
        Parameters:
        spec - an immutable object that specifies how to edit this client
        Returns:
        A Mono where, upon successful completion, emits the edited User. If an error is received, it is emitted through the Mono.
      • logout

        public Mono<Void> logout()
        Disconnects this GatewayDiscordClient from Discord upon subscribing. All GatewayClient instances in this shard group will attempt to close their current Gateway session and complete this Mono after all of them have disconnected.
        Returns:
        A Mono that upon subscription, will disconnect each Gateway connection established by this GatewayDiscordClient and complete after all of them have closed.
      • onDisconnect

        public Mono<Void> onDisconnect()
        Return a Mono that signals completion when all GatewayClient instances in this shard group have disconnected.
        Returns:
        a Mono that will complete once all GatewayClient instances in this shard group have disconnected.
      • on

        public <E extends EventFlux<E> on​(Class<E> eventClass)
        Retrieves a Flux with elements of the given Event type. This Flux has to be subscribed to in order to start processing. See Event class for the list of possible event classes.

        Note: Errors occurring while processing events will terminate your sequence. If you wish to use a version capable of handling errors for you, use on(Class, Function). See Reactive Streams Spec explaining this behavior.

        A recommended pattern to use this method is wrapping your code that may throw exceptions within a flatMap block and use Mono.onErrorResume(Function), Flux.onErrorResume(Function) or equivalent methods to maintain the sequence active:

         client.on(MessageCreateEvent.class)
             .flatMap(event -> myCodeThatMightThrow(event)
                     .onErrorResume(error -> {
                         // log and then discard the error to keep the sequence alive
                         log.error("Failed to handle event!", error);
                         return Mono.empty();
                     }))
             .subscribe();
         

        For more alternatives to handling errors, please see Error Handling docs page.

        Type Parameters:
        E - the type of the event class
        Parameters:
        eventClass - the event class to obtain events from
        Returns:
        a new Flux with the requested events
      • on

        public <E extends Event,​T> Flux<T> on​(Class<E> eventClass,
                                                    Function<E,​Publisher<T>> mapper)
        Retrieves a Flux with elements of the given Event type, to be processed through a given Function upon subscription. Errors occurring within the mapper will be logged and discarded, preventing the termination of the "infinite" event sequence. See Event class for the list of possible event classes.

        There are multiple ways of using this event handling method, for example:

         client.on(MessageCreateEvent.class, event -> {
                 // myCodeThatMightThrow should return a Reactor type (Mono or Flux)
                 return myCodeThatMightThrow(event);
             })
             .subscribe();
        
         client.on(MessageCreateEvent.class, event -> {
                 // myCodeThatMightThrow *can* be blocking, so wrap it in a Reactor type
                 return Mono.fromRunnable(() -> myCodeThatMightThrow(event));
             })
             .subscribe();
         

        Continuing the chain after on(class, event -> ...) will require your own error handling strategy. Check the docs for on(Class) for more details.

        Type Parameters:
        E - the type of the event class
        T - the type of the event mapper function
        Parameters:
        eventClass - the event class to obtain events from
        mapper - an event mapping function called on each event. If you do not wish to perform further operations you can return Mono.empty().
        Returns:
        a new Flux with the type resulting from the given event mapper
      • on

        public Flux<Event> on​(ReactiveEventAdapter adapter)
        Applies a given adapter to all events from this dispatcher. Errors occurring within the mapper will be logged and discarded, preventing the termination of the "infinite" event sequence. This variant allows you to have a single subscriber to this dispatcher, which is useful to collect all startup events.

        A standard approach to this method is to subclass ReactiveEventAdapter, overriding the methods you want to listen for:

         client.on(new ReactiveEventAdapter() {
        
             public Publisher<?> onReady(ReadyEvent event) {
                 return Mono.fromRunnable(() ->
                         System.out.println("Connected as " + event.getSelf().getTag()));
             }
        
             public Publisher<?> onMessageCreate(MessageCreateEvent event) {
                 if (event.getMessage().getContent().equals("!ping")) {
                     return event.getMessage().getChannel()
                             .flatMap(channel -> channel.createMessage("Pong!"));
                 }
                 return Mono.empty();
             }
        
         }).subscribe(); // nothing happens until you subscribe
         

        Each method requires a Publisher return like Mono or Flux and all errors will be logged and discarded. To use a synchronous implementation you can wrap your code with Mono.fromRunnable(Runnable).

        Continuing the chain will require your own error handling strategy. Check the docs for on(Class) for more details.

        Parameters:
        adapter - an adapter meant to be subclassed with its appropriate methods overridden
        Returns:
        a new Flux with the type resulting from the given event mapper
      • requestMembers

        public Flux<Member> requestMembers​(Snowflake guildId)
        Return all members from the given guildId using the current Gateway connection. This method performs a check to validate whether the given guild's data can be obtained from this GatewayDiscordClient.
        Parameters:
        guildId - the Snowflake of the guild to obtain members from
        Returns:
        a Flux of Member for the given Guild. If an error occurs, it is emitted through the Flux.
      • requestMembers

        public Flux<Member> requestMembers​(Snowflake guildId,
                                           Set<Snowflake> userIds)
        Return a set of members from the given guildId using the current Gateway connection. This method performs a check to validate whether the given guild's data can be obtained from this GatewayDiscordClient.
        Parameters:
        guildId - the Snowflake of the guild to obtain members from
        userIds - the Snowflake set of users to request
        Returns:
        a Flux of Member for the given Guild. If an error occurs, it is emitted through the Flux.
      • requestMembers

        public Flux<Member> requestMembers​(discord4j.discordjson.json.gateway.RequestGuildMembers request)
        Submit a RequestGuildMembers payload using the current Gateway connection and wait for its completion, delivering Member elements asynchronously through a Flux. This method performs a check to validate whether the given guild's data can be obtained from this GatewayDiscordClient.
        Parameters:
        request - the member request to submit. Create one using RequestGuildMembers.builder().
        Returns:
        a Flux of Member for the given Guild. If an error occurs, it is emitted through the Flux.
      • requestMemberChunks

        public Flux<discord4j.discordjson.json.gateway.GuildMembersChunk> requestMemberChunks​(discord4j.discordjson.json.gateway.RequestGuildMembers request)
        Submit a RequestGuildMembers payload using the current Gateway connection and wait for its completion, delivering raw GuildMembersChunk elements asynchronously through a Flux. This method performs a check to validate whether the given guild's data can be obtained from this GatewayDiscordClient.

        A timeout given by is used to fail this request if the operation is unable to complete due to disallowed or disabled members intent. This is particularly relevant when requesting a complete member list. If the timeout is triggered, a TimeoutException is forwarded through the Flux.

        Parameters:
        request - the member request to submit. Create one using RequestGuildMembers.builder(). Flux.timeout(Duration)
        Returns:
        a Flux of GuildMembersChunk for the given Guild. If an error occurs, it is emitted through the Flux.
      • withRetrievalStrategy

        public EntityRetriever withRetrievalStrategy​(EntityRetrievalStrategy retrievalStrategy)
        Applies the given strategy to retrieve entities using this GatewayDiscordClient.
        Parameters:
        retrievalStrategy - the strategy to apply
        Returns:
        an EntityRetriever able to retrieve entities using the given strategy
      • getChannelById

        public Mono<Channel> getChannelById​(Snowflake channelId)
        Description copied from interface: EntityRetriever
        Requests to retrieve the channel represented by the supplied ID.
        Specified by:
        getChannelById in interface EntityRetriever
        Parameters:
        channelId - The ID of the channel.
        Returns:
        A Mono where, upon successful completion, emits the Channel as represented by the supplied ID. If an error is received, it is emitted through the Mono.
      • getGuildById

        public Mono<Guild> getGuildById​(Snowflake guildId)
        Description copied from interface: EntityRetriever
        Requests to retrieve the guild represented by the supplied ID.
        Specified by:
        getGuildById in interface EntityRetriever
        Parameters:
        guildId - The ID of the guild.
        Returns:
        A Mono where, upon successful completion, emits the Guild as represented by the supplied ID. If an error is received, it is emitted through the Mono.
      • getGuildEmojiById

        public Mono<GuildEmoji> getGuildEmojiById​(Snowflake guildId,
                                                  Snowflake emojiId)
        Description copied from interface: EntityRetriever
        Requests to retrieve the guild emoji represented by the supplied IDs.
        Specified by:
        getGuildEmojiById in interface EntityRetriever
        Parameters:
        guildId - The ID of the guild.
        emojiId - The ID of the emoji.
        Returns:
        A Mono where, upon successful completion, emits the GuildEmoji as represented by the supplied IDs. If an error is received, it is emitted through the Mono.
      • getMemberById

        public Mono<Member> getMemberById​(Snowflake guildId,
                                          Snowflake userId)
        Description copied from interface: EntityRetriever
        Requests to retrieve the member represented by the supplied IDs. Depending on the implementation, it is possible to lazily request member entities from the Gateway, or the REST API.
        Specified by:
        getMemberById in interface EntityRetriever
        Parameters:
        guildId - The ID of the guild.
        userId - The ID of the user.
        Returns:
        A Mono where, upon successful completion, emits the Member as represented by the supplied IDs. If an error is received, it is emitted through the Mono.
      • getMessageById

        public Mono<Message> getMessageById​(Snowflake channelId,
                                            Snowflake messageId)
        Description copied from interface: EntityRetriever
        Requests to retrieve the message represented by the supplied IDs.
        Specified by:
        getMessageById in interface EntityRetriever
        Parameters:
        channelId - The ID of the channel.
        messageId - The ID of the message.
        Returns:
        A Mono where, upon successful completion, emits the Message as represented by the supplied IDs. If an error is received, it is emitted through the Mono.
      • getRoleById

        public Mono<Role> getRoleById​(Snowflake guildId,
                                      Snowflake roleId)
        Description copied from interface: EntityRetriever
        Requests to retrieve the role represented by the supplied IDs.
        Specified by:
        getRoleById in interface EntityRetriever
        Parameters:
        guildId - The ID of the guild.
        roleId - The ID of the role.
        Returns:
        A Mono where, upon successful completion, emits the Role as represented by the supplied IDs. If an error is received, it is emitted through the Mono.
      • getUserById

        public Mono<User> getUserById​(Snowflake userId)
        Description copied from interface: EntityRetriever
        Requests to retrieve the user represented by the supplied ID.
        Specified by:
        getUserById in interface EntityRetriever
        Parameters:
        userId - The ID of the user.
        Returns:
        A Mono where, upon successful completion, emits the User as represented by the supplied ID. If an error is received, it is emitted through the Mono.
      • getGuilds

        public Flux<Guild> getGuilds()
        Description copied from interface: EntityRetriever
        Requests to retrieve the guilds the current client is in.
        Specified by:
        getGuilds in interface EntityRetriever
        Returns:
        A Flux that continually emits the guilds that the current client is in. If an error is received, it is emitted through the Flux.
      • getSelf

        public Mono<User> getSelf()
        Description copied from interface: EntityRetriever
        Requests to retrieve the bot user.
        Specified by:
        getSelf in interface EntityRetriever
        Returns:
        A Mono where, upon successful completion, emits the bot user. If an error is received, it is emitted through the Mono.
      • getSelfMember

        public Mono<Member> getSelfMember​(Snowflake guildId)
        Description copied from interface: EntityRetriever
        Requests to retrieve the bot user represented as a member of the guild with the supplied ID.
        Specified by:
        getSelfMember in interface EntityRetriever
        Parameters:
        guildId - The ID of the guild.
        Returns:
        A Mono where, upon successful completion, emits the bot member. If an error is received, it is emitted through the Mono.
      • getGuildMembers

        public Flux<Member> getGuildMembers​(Snowflake guildId)
        Description copied from interface: EntityRetriever
        Requests to retrieve the guild's members.
        Specified by:
        getGuildMembers in interface EntityRetriever
        Parameters:
        guildId - the ID of the guild.
        Returns:
        A Flux that continually emits the members of the guild. If an error is received, it is emitted through the Flux.