Class MessageBuilder

  • All Implemented Interfaces:
    java.lang.Appendable

    public class MessageBuilder
    extends java.lang.Object
    implements java.lang.Appendable
    Builder system used to build Messages.
    Internally the builder uses a StringBuilder to take advantage of the efficiencies offered by the StringBuilder, and the methods provided by this class are a combination of those offered by the StringBuilder and String.format(String, Object...).
    Since:
    1.0
    Author:
    Michael Ritter, Aljoscha Grebe
    • Constructor Detail

      • MessageBuilder

        public MessageBuilder()
      • MessageBuilder

        public MessageBuilder​(java.lang.CharSequence content)
      • MessageBuilder

        public MessageBuilder​(Message message)
      • MessageBuilder

        public MessageBuilder​(EmbedBuilder builder)
      • MessageBuilder

        public MessageBuilder​(MessageEmbed embed)
    • Method Detail

      • setTTS

        public MessageBuilder setTTS​(boolean tts)
        Makes the created Message a TTS message.
        TTS stands for Text-To-Speech. When a TTS method is received by the Discord client, it is vocalized so long as the user has not disabled TTS.
        Parameters:
        tts - whether the created Message should be a tts message
        Returns:
        The MessageBuilder instance. Useful for chaining.
      • setEmbed

        public MessageBuilder setEmbed​(MessageEmbed embed)
        Adds a MessageEmbed to the Message. Embeds can be built using the EmbedBuilder and offer specialized formatting.
        Parameters:
        embed - the embed to add, or null to remove
        Returns:
        The MessageBuilder instance. Useful for chaining.
      • setNonce

        public MessageBuilder setNonce​(java.lang.String nonce)
        Sets the nonce of the built message(s). It is recommended to have only 100% unique strings to validate messages via this nonce.
        The nonce will be available from the resulting message via Message.getNonce() in message received by events and RestAction responses.
        When null is provided no nonce will be used.
        Parameters:
        nonce - Validation nonce string
        Returns:
        The MessageBuilder instance. Useful for chaining.
        See Also:
        Message.getNonce(), Cryptographic Nonce - Wikipedia
      • setContent

        public MessageBuilder setContent​(java.lang.String content)
        Sets the content of the resulting Message
        This will replace already added content.
        Parameters:
        content - The content to use, or null to reset the content
        Returns:
        The MessageBuilder instance. Useful for chaining.
        Throws:
        java.lang.IllegalArgumentException - If the provided content exceeds Message.MAX_CONTENT_LENGTH
        See Also:
        Message.getContentRaw()
      • append

        public MessageBuilder append​(java.lang.CharSequence text)
        Specified by:
        append in interface java.lang.Appendable
      • append

        public MessageBuilder append​(java.lang.CharSequence text,
                                     int start,
                                     int end)
        Specified by:
        append in interface java.lang.Appendable
      • append

        public MessageBuilder append​(char c)
        Specified by:
        append in interface java.lang.Appendable
      • append

        public MessageBuilder append​(java.lang.Object object)
        Appends the string representation of an object to the Message.
        This is the same as append(String.valueOf(object))
        Parameters:
        object - the object to append
        Returns:
        The MessageBuilder instance. Useful for chaining.
      • append

        public MessageBuilder append​(IMentionable mention)
        Appends a mention to the Message.
        Typical usage would be providing an IMentionable like User or TextChannel.
        Parameters:
        mention - the mention to append
        Returns:
        The MessageBuilder instance. Useful for chaining.
      • append

        public MessageBuilder append​(java.lang.CharSequence text,
                                     MessageBuilder.Formatting... format)
        Appends a String using the specified chat Formatting(s).
        Parameters:
        text - the text to append.
        format - the format(s) to apply to the text.
        Returns:
        The MessageBuilder instance. Useful for chaining.
      • appendFormat

        public MessageBuilder appendFormat​(java.lang.String format,
                                           java.lang.Object... args)
        This method is an extended form of String.format(String, Object...). It allows for all of the token replacement functionality that String.format(String, Object...) supports.
        A lot of JDA entities implement Formattable and will provide specific format outputs for their specific type.

        Example:
        If you placed the following code in an method handling a MessageReceivedEvent

        
         User user = event.getAuthor();
         MessageBuilder builder = new MessageBuilder();
         builder.appendFormat("%#s is really cool!", user);
         builder.build();
         
        It would build a message that mentions the author and says that he is really cool!. If the user's name was "Minn" and his discriminator "6688", it would say:
          "Minn#6688 is really cool!"

        Note that this uses the # flag to utilize the alternative format for User.
        By default it would fallback to IMentionable.getAsMention()
        Parameters:
        format - a format string.
        args - an array objects that will be used to replace the tokens, they must be provided in the order that the tokens appear in the provided format string.
        Returns:
        The MessageBuilder instance. Useful for chaining.
        Throws:
        java.lang.IllegalArgumentException - If the provided format string is null or empty
        java.util.IllegalFormatException - If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the Details section of the formatter class specification.
      • appendCodeBlock

        public MessageBuilder appendCodeBlock​(java.lang.CharSequence text,
                                              java.lang.CharSequence language)
        Appends a code-block to the Message.
        Discord uses Highlight.js for its language highlighting support. You can find out what specific languages are supported here.
        Parameters:
        text - the code to append
        language - the language of the code. If unknown use an empty string
        Returns:
        The MessageBuilder instance. Useful for chaining.
      • length

        public int length()
        Returns the current length of the content that will be built into a Message when build() is called.
        If this value is 0 (and there is no embed) or greater than 2000 when build() is called, an exception will be raised as you cannot send an empty message to Discord and Discord has a hard limit of 2000 characters per message.

        Hint: You can use build(int, int) or buildAll(SplitPolicy...) as possible ways to deal with the 2000 character cap.

        Returns:
        the current length of the content that will be built into a Message.
      • isEmpty

        public boolean isEmpty()
        Checks if the message contains any contend. This includes text as well as embeds.
        Returns:
        weather the message contains content
      • replace

        public MessageBuilder replace​(java.lang.String target,
                                      java.lang.String replacement)
        Replaces each substring that matches the target string with the specified replacement string. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the message "aaa" will result in "ba" rather than "ab".
        Parameters:
        target - the sequence of char values to be replaced
        replacement - the replacement sequence of char values
        Returns:
        The MessageBuilder instance. Useful for chaining.
      • replaceFirst

        public MessageBuilder replaceFirst​(java.lang.String target,
                                           java.lang.String replacement)
        Replaces the first substring that matches the target string with the specified replacement string.
        Parameters:
        target - the sequence of char values to be replaced
        replacement - the replacement sequence of char values
        Returns:
        The MessageBuilder instance. Useful for chaining.
      • replaceLast

        public MessageBuilder replaceLast​(java.lang.String target,
                                          java.lang.String replacement)
        Replaces the last substring that matches the target string with the specified replacement string.
        Parameters:
        target - the sequence of char values to be replaced
        replacement - the replacement sequence of char values
        Returns:
        The MessageBuilder instance. Useful for chaining.
      • stripMentions

        public MessageBuilder stripMentions​(JDA jda)
        Removes all mentions and replaces them with the closest looking textual representation.

        Use this over stripMentions(Guild) if User mentions should be replaced with their User.getName() instead of their Nicknames.

        Parameters:
        jda - The JDA instance used to resolve the mentions.
        Returns:
        The MessageBuilder instance. Useful for chaining.
      • stripMentions

        public MessageBuilder stripMentions​(Guild guild)
        Removes all mentions and replaces them with the closest looking textual representation.

        Use this over stripMentions(JDA) if User mentions should be replaced with their nicknames in a specific guild based.
        Uses Member.getEffectiveName()

        Parameters:
        guild - the guild for User mentions
        Returns:
        The MessageBuilder instance. Useful for chaining.
      • getStringBuilder

        public java.lang.StringBuilder getStringBuilder()
        Returns the underlying StringBuilder.
        Returns:
        The StringBuilder used by this MessageBuilder
      • clear

        public MessageBuilder clear()
        Clears the current builder. Useful for mass message creation.
        Returns:
        The MessageBuilder instance. Useful for chaining.
      • indexOf

        public int indexOf​(java.lang.CharSequence target,
                           int fromIndex,
                           int endIndex)
        Returns the index within this string of the first occurrence of the specified substring between the specified indices.

        If no such value of target exists, then -1 is returned.

        Parameters:
        target - the substring to search for.
        fromIndex - the index from which to start the search.
        endIndex - the index at which to end the search.
        Returns:
        the index of the first occurrence of the specified substring between the specified indices or -1 if there is no such occurrence.
        Throws:
        java.lang.IndexOutOfBoundsException -
        • If the fromIndex is outside of the range of 0 to length()
        • If the endIndex is outside of the range of 0 to length()
        • If the fromIndex is greater than endIndex
      • lastIndexOf

        public int lastIndexOf​(java.lang.CharSequence target,
                               int fromIndex,
                               int endIndex)
        Returns the index within this string of the last occurrence of the specified substring between the specified indices. If no such value of target exists, then -1 is returned.
        Parameters:
        target - the substring to search for.
        fromIndex - the index from which to start the search.
        endIndex - the index at which to end the search.
        Returns:
        the index of the last occurrence of the specified substring between the specified indices or -1 if there is no such occurrence.
        Throws:
        java.lang.IndexOutOfBoundsException -
        • If the fromIndex is outside of the range of 0 to length()
        • If the endIndex is outside of the range of 0 to length()
        • If the fromIndex is greater than endIndex
      • sendTo

        @CheckReturnValue
        public MessageAction sendTo​(MessageChannel channel)
        Creates a MessageAction with the current settings without building a Message instance first.
        Parameters:
        channel - The not-null target MessageChannel
        Returns:
        MessageAction
        Throws:
        java.lang.IllegalArgumentException - If the provided channel is null
        PermissionException - If the currently logged in account does not have permission to send or read messages in this channel, or if this is a PrivateChannel and both users (sender and receiver) are bots.
      • buildAll

        public java.util.Queue<Message> buildAll​(MessageBuilder.SplitPolicy... policy)
        Creates a Queue of Message objects from this MessageBuilder.

        This method splits the content if it exceeds 2000 chars. The splitting behaviour can be customized using SplitPolicies. The method will try the policies in the order they are passed to it.
        If no SplitPolicy is provided each message will be split after exactly 2000 chars.

        This is not Markdown safe. An easy workaround is to include Zero Width Spaces as predetermined breaking points to the message and only split on them.

        Parameters:
        policy - The MessageBuilder.SplitPolicy defining how to split the text in the MessageBuilder into different, individual messages.
        Returns:
        the created Messages