-
-
Notifications
You must be signed in to change notification settings - Fork 737
/
MessageBuilder.java
893 lines (815 loc) · 33 KB
/
MessageBuilder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
/*
* Copyright 2015-2017 Austin Keener & Michael Ritter & Florian Spieß
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.core;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.entities.impl.MessageImpl;
import net.dv8tion.jda.core.utils.Checks;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Builder system used to build {@link net.dv8tion.jda.core.entities.Message Messages}.
* <br>Internally the builder uses a {@link java.lang.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
* {@link String#format(String, Object...)}.
*
* @since 1.0
* @author Michael Ritter
* @author Aljoscha Grebe
*/
public class MessageBuilder implements Appendable
{
protected static final Pattern USER_MENTION_PATTERN = Pattern.compile("<@!?([0-9]+)>");
protected static final Pattern CHANNEL_MENTION_PATTERN = Pattern.compile("<#!?([0-9]+)>");
protected static final Pattern ROLE_MENTION_PATTERN = Pattern.compile("<@&!?([0-9]+)>");
protected final StringBuilder builder = new StringBuilder();
protected boolean isTTS = false;
protected MessageEmbed embed;
public MessageBuilder() {}
/**
* Makes the created Message a TTS message.
* <br>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.
*
* @param tts
* whether the created Message should be a tts message
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder setTTS(boolean tts)
{
this.isTTS = tts;
return this;
}
/**
* Adds a {@link net.dv8tion.jda.core.entities.MessageEmbed} to the Message. Embeds can be built using
* the {@link net.dv8tion.jda.core.EmbedBuilder} and offer specialized formatting.
*
* @param embed
* the embed to add, or null to remove
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder setEmbed(MessageEmbed embed)
{
this.embed = embed;
return this;
}
/**
* Appends a String to the Message.
*
* @param text
* the text to append
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
@Override
public MessageBuilder append(CharSequence text)
{
builder.append(text);
return this;
}
@Override
public MessageBuilder append(CharSequence text, int start, int end)
{
builder.append(text, start, end);
return this;
}
@Override
public MessageBuilder append(char c)
{
builder.append(c);
return this;
}
/**
* Appends the string representation of an object to the Message.
* <br>This is the same as {@link #append(CharSequence) append(String.valueOf(object))}
*
* @param object
* the object to append
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder append(Object object)
{
return append(String.valueOf(object));
}
/**
* Appends a mention to the Message.
* <br>Typical usage would be providing an {@link net.dv8tion.jda.core.entities.IMentionable IMentionable} like
* {@link net.dv8tion.jda.core.entities.User User} or {@link net.dv8tion.jda.core.entities.TextChannel TextChannel}.
*
* @param mention
* the mention to append
*
* @return The {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder append(IMentionable mention)
{
builder.append(mention.getAsMention());
return this;
}
/**
* Appends a String using the specified chat {@link net.dv8tion.jda.core.MessageBuilder.Formatting Formatting(s)}.
*
* @param text
* the text to append.
* @param format
* the format(s) to apply to the text.
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder append(CharSequence text, Formatting... format)
{
boolean blockPresent = false;
for (Formatting formatting : format)
{
if (formatting == Formatting.BLOCK)
{
blockPresent = true;
continue;
}
builder.append(formatting.getTag());
}
if (blockPresent)
builder.append(Formatting.BLOCK.getTag());
builder.append(text);
if (blockPresent)
builder.append(Formatting.BLOCK.getTag());
for (int i = format.length - 1; i >= 0; i--)
{
if (format[i] == Formatting.BLOCK) continue;
builder.append(format[i].getTag());
}
return this;
}
/**
* This method is an extended form of {@link String#format(String, Object...)}. It allows for all of
* the token replacement functionality that String.format(String, Object...) supports.
* <br>A lot of JDA entities implement {@link java.util.Formattable Formattable} and will provide
* specific format outputs for their specific type.
* <ul>
* <li>{@link net.dv8tion.jda.core.entities.IMentionable IMentionable}
* <br>These will output their {@link net.dv8tion.jda.core.entities.IMentionable#getAsMention() getAsMention} by default,
* some implementations have alternatives such as {@link net.dv8tion.jda.core.entities.User User} and {@link net.dv8tion.jda.core.entities.TextChannel TextChannel}.</li>
* <li>{@link net.dv8tion.jda.core.entities.MessageChannel MessageChannel}
* <br>All message channels format to {@code "#" + getName()} by default, TextChannel has special handling
* and uses the getAsMention output by default and the MessageChannel output as alternative ({@code #} flag).</li>
* <li>{@link net.dv8tion.jda.core.entities.Message Message}
* <br>Messages by default output their {@link net.dv8tion.jda.core.entities.Message#getContent() getContent()} value and
* as alternative use the {@link net.dv8tion.jda.core.entities.Message#getRawContent() getRawContent()} value</li>
* </ul>
*
* <p>Example:
* <br>If you placed the following code in an method handling a
* {@link net.dv8tion.jda.core.events.message.MessageReceivedEvent MessageReceivedEvent}
* <br><pre>{@code
* User user = event.getAuthor();
* MessageBuilder builder = new MessageBuilder();
* builder.appendFormat("%#s is really cool!", user);
* builder.build();
* }</pre>
*
* 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:
* <br><pre> "Minn#6688 is really cool!"</pre>
* <br>Note that this uses the {@code #} flag to utilize the alternative format for {@link net.dv8tion.jda.core.entities.User User}.
* <br>By default it would fallback to {@link net.dv8tion.jda.core.entities.IMentionable#getAsMention()}
*
* @param format
* a format string.
* @param 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.
*
* @throws java.lang.IllegalArgumentException
* If the provided format string is {@code null} or empty
*
* @return The {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder appendFormat(String format, Object... args)
{
Checks.notEmpty(format, "Format String");
this.append(String.format(format, args));
return this;
}
/**
* Appends a code-block to the Message.
* <br>Discord uses <a href="https://highlightjs.org/">Highlight.js</a> for its language highlighting support. You can find out what
* specific languages are supported <a href="https://github.com/isagalaev/highlight.js/tree/master/src/languages">here</a>.
*
* @param text
* the code to append
* @param language
* the language of the code. If unknown use an empty string
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder appendCodeBlock(CharSequence text, CharSequence language)
{
builder.append("```").append(language).append('\n').append(text).append("\n```");
return this;
}
/**
* Returns the current length of the content that will be built into a {@link net.dv8tion.jda.core.entities.Message Message}
* when {@link #build()} is called.
* <br>If this value is {@code 0} (and there is no embed) or greater than {@code 2000} when {@link #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.
*
* <p><b>Hint:</b> You can use {@link #build(int, int)} or
* {@link #buildAll(net.dv8tion.jda.core.MessageBuilder.SplitPolicy...) buildAll(SplitPolicy...)} as possible ways to
* deal with the 2000 character cap.
*
* @return the current length of the content that will be built into a Message.
*/
public int length()
{
return builder.length();
}
/**
* Checks if the message contains any contend. This includes text as well as embeds.
*
* @return weather the message contains content
*/
public boolean isEmpty() {
return builder.length() == 0 && embed == null;
}
/**
* Creates a {@link net.dv8tion.jda.core.entities.Message Message} object from this MessageBuilder
*
* <p><b>Hint:</b> You can use {@link #build(int, int)} or
* {@link #buildAll(net.dv8tion.jda.core.MessageBuilder.SplitPolicy...) buildAll(SplitPolicy...)} as possible ways to
* deal with the 2000 character cap.
*
* @throws java.lang.IllegalStateException
* <ul>
* <li>If you attempt to build() an empty Message ({@link #length()} is {@code 0} and no
* {@link net.dv8tion.jda.core.entities.MessageEmbed} was provided to {@link #setEmbed(net.dv8tion.jda.core.entities.MessageEmbed)})</li>
* <li>If you attempt to build() a Message with more than 2000 characters of content.</li>
* </ul>
*
* @return the created {@link net.dv8tion.jda.core.entities.Message Message}
*/
public Message build()
{
String message = builder.toString();
if (this.isEmpty())
throw new IllegalStateException("Cannot build a Message with no content. (You never added any content to the message)");
if (message.length() > 2000)
throw new IllegalStateException("Cannot build a Message with more than 2000 characters. Please limit your input.");
return new MessageImpl(-1, null, false).setContent(message).setTTS(isTTS)
.setEmbeds(embed == null ? new LinkedList<>() : Collections.singletonList(embed));
}
/**
* 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".
*
* @param target
* the sequence of char values to be replaced
* @param replacement
* the replacement sequence of char values
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder replaceAll(String target, String replacement)
{
int index;
while ((index = builder.indexOf(target)) != -1)
{
builder.replace(index, index + target.length(), replacement);
}
return this;
}
/**
* Replaces the first substring that matches the target string with the specified replacement string.
*
* @param target
* the sequence of char values to be replaced
* @param replacement
* the replacement sequence of char values
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder replaceFirst(String target, String replacement)
{
int index = builder.indexOf(target);
if (index != -1)
{
builder.replace(index, index + target.length(), replacement);
}
return this;
}
/**
* Replaces the last substring that matches the target string with the specified replacement string.
*
* @param target
* the sequence of char values to be replaced
* @param replacement
* the replacement sequence of char values
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder replaceLast(String target, String replacement)
{
int index = builder.lastIndexOf(target);
if (index != -1)
{
builder.replace(index, index + target.length(), replacement);
}
return this;
}
/**
* Removes all mentions and replaces them with the closest looking textual representation.
*
* <p>Use this over {@link #stripMentions(Guild)} if {@link net.dv8tion.jda.core.entities.User User} mentions
* should be replaced with their {@link net.dv8tion.jda.core.entities.User#getName()} instead of their Nicknames.
*
* @param jda
* The JDA instance used to resolve the mentions.
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder stripMentions(JDA jda)
{
// Note: Users can rename to "everyone" or "here", so those
// should be stripped after the USER mention is stripped.
return this.stripMentions(jda, (Guild) null, MentionType.CHANNEL, MentionType.ROLE, MentionType.USER, MentionType.EVERYONE, MentionType.HERE);
}
/**
* Removes all mentions and replaces them with the closest looking textual representation.
*
* <p>Use this over {@link #stripMentions(JDA)} if {@link net.dv8tion.jda.core.entities.User User} mentions should
* be replaced with their nicknames in a specific guild based.
* <br>Uses {@link net.dv8tion.jda.core.entities.Member#getEffectiveName()}
*
* @param guild
* the guild for {@link net.dv8tion.jda.core.entities.User User} mentions
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder stripMentions(Guild guild)
{
// Note: Users can rename to "everyone" or "here", so those
// should be stripped after the USER mention is stripped.
return this.stripMentions(guild.getJDA(), guild, MentionType.CHANNEL, MentionType.ROLE, MentionType.USER, MentionType.EVERYONE, MentionType.HERE);
}
/**
* Removes all mentions of the specified types and replaces them with the closest looking textual representation.
*
* <p>Use this over {@link #stripMentions(JDA, MentionType...)} if {@link net.dv8tion.jda.core.entities.User User} mentions should
* be replaced with their nicknames in a specific guild based.
* <br>Uses {@link net.dv8tion.jda.core.entities.Member#getEffectiveName()}
*
* @param guild
* the guild for {@link net.dv8tion.jda.core.entities.User User} mentions
* @param types
* the {@link MentionType MentionTypes} that should be stripped
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder stripMentions(Guild guild, MentionType... types)
{
return this.stripMentions(guild.getJDA(), guild, types);
}
/**
* Removes all mentions of the specified types and replaces them with the closest looking textual representation.
*
* <p>Use this over {@link #stripMentions(Guild, MentionType...)} if {@link net.dv8tion.jda.core.entities.User User}
* mentions should be replaced with their {@link net.dv8tion.jda.core.entities.User#getName()}.
*
* @param jda
* The JDA instance used to resolve the mentions.
* @param types
* the {@link MentionType MentionTypes} that should be stripped
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder stripMentions(JDA jda, MentionType... types)
{
return this.stripMentions(jda, null, types);
}
private MessageBuilder stripMentions(JDA jda, Guild guild, MentionType... types)
{
if (types == null)
return this;
String string = null;
for (MentionType mention : types)
{
if (mention != null)
{
switch (mention)
{
case EVERYONE:
replaceAll("@everyone", "@\u0435veryone");
break;
case HERE:
replaceAll("@here", "@h\u0435re");
break;
case CHANNEL:
{
if (string == null)
{
string = builder.toString();
}
Matcher matcher = CHANNEL_MENTION_PATTERN.matcher(string);
while (matcher.find())
{
TextChannel channel = jda.getTextChannelById(matcher.group(1));
if (channel != null)
{
replaceAll(matcher.group(), "#" + channel.getName());
}
}
break;
}
case ROLE:
{
if (string == null)
{
string = builder.toString();
}
Matcher matcher = ROLE_MENTION_PATTERN.matcher(string);
while (matcher.find())
{
for (Guild g : jda.getGuilds())
{
Role role = g.getRoleById(matcher.group(1));
if (role != null)
{
replaceAll(matcher.group(), "@"+role.getName());
break;
}
}
}
break;
}
case USER:
{
if (string == null)
{
string = builder.toString();
}
Matcher matcher = USER_MENTION_PATTERN.matcher(string);
while (matcher.find())
{
User user = jda.getUserById(matcher.group(1));
String replacement = null;
if (user == null)
continue;
Member member;
if (guild != null && (member = guild.getMember(user)) != null)
replacement = member.getEffectiveName();
else
replacement = user.getName();
replaceAll(matcher.group(), "@" + replacement);
}
break;
}
}
}
}
return this;
}
/**
* Returns the underlying {@link StringBuilder}.
*
* @return the {@link StringBuilder} used by this {@link MessageBuilder}
*/
public StringBuilder getStringBuilder()
{
return this.builder;
}
/**
* Clears the current builder. Useful for mass message creation.
*
* @return Returns the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder} instance. Useful for chaining.
*/
public MessageBuilder clear() {
this.builder.setLength(0);
this.embed = null;
this.isTTS = false;
return this;
}
/**
* Returns the index within this string of the first occurrence of the
* specified substring between the specified indices.
*
* <p>If no such value of {@code target} exists, then {@code -1} is returned.
*
* @param target
* the substring to search for.
* @param fromIndex
* the index from which to start the search.
* @param endIndex
* the index at which to end the search.
*
* @throws java.lang.IndexOutOfBoundsException
* <ul>
* <li>If the {@code fromIndex} is outside of the range of {@code 0} to {@link #length()}</li>
* <li>If the {@code endIndex} is outside of the range of {@code 0} to {@link #length()}</li>
* <li>If the {@code fromIndex} is greater than {@code endIndex}</li>
* </ul>
*
* @return the index of the first occurrence of the specified substring between
* the specified indices or {@code -1} if there is no such occurrence.
*/
public int indexOf(CharSequence target, int fromIndex, int endIndex)
{
if (fromIndex < 0)
throw new IndexOutOfBoundsException("index out of range: " + fromIndex);
if (endIndex < 0)
throw new IndexOutOfBoundsException("index out of range: " + endIndex);
if (fromIndex > length())
throw new IndexOutOfBoundsException("fromIndex > length()");
if (fromIndex > endIndex)
throw new IndexOutOfBoundsException("fromIndex > endIndex");
if (endIndex >= builder.length())
{
endIndex = builder.length() - 1;
}
int targetCount = target.length();
if (targetCount == 0)
{
return fromIndex;
}
char strFirstChar = target.charAt(0);
int max = endIndex + targetCount - 1;
lastCharSearch:
for (int i = fromIndex; i <= max; i++)
{
if (builder.charAt(i) == strFirstChar)
{
for (int j = 1; j < targetCount; j++)
{
if (builder.charAt(i + j) != target.charAt(j))
{
continue lastCharSearch;
}
}
return i;
}
}
return -1;
}
/**
* Returns the index within this string of the last occurrence of the
* specified substring between the specified indices.
*
* If no such value of {@code target} exists, then {@code -1} is returned.
*
* @param target
* the substring to search for.
* @param fromIndex
* the index from which to start the search.
* @param endIndex
* the index at which to end the search.
*
* @throws java.lang.IndexOutOfBoundsException
* <ul>
* <li>If the {@code fromIndex} is outside of the range of {@code 0} to {@link #length()}</li>
* <li>If the {@code endIndex} is outside of the range of {@code 0} to {@link #length()}</li>
* <li>If the {@code fromIndex} is greater than {@code endIndex}</li>
* </ul>
*
* @return the index of the last occurrence of the specified substring between
* the specified indices or {@code -1} if there is no such occurrence.
*/
public int lastIndexOf(CharSequence target, int fromIndex, int endIndex)
{
if (fromIndex < 0)
throw new IndexOutOfBoundsException("index out of range: " + fromIndex);
if (endIndex < 0)
throw new IndexOutOfBoundsException("index out of range: " + endIndex);
if (fromIndex > length())
throw new IndexOutOfBoundsException("fromIndex > length()");
if (fromIndex > endIndex)
throw new IndexOutOfBoundsException("fromIndex > endIndex");
if (endIndex >= builder.length())
{
endIndex = builder.length() - 1;
}
int targetCount = target.length();
if (targetCount == 0)
{
return endIndex;
}
int rightIndex = endIndex - targetCount;
if (fromIndex > rightIndex)
{
fromIndex = rightIndex;
}
int strLastIndex = targetCount - 1;
char strLastChar = target.charAt(strLastIndex);
int min = fromIndex + targetCount - 1;
lastCharSearch:
for (int i = endIndex; i >= min; i--)
{
if (builder.charAt(i) == strLastChar)
{
for (int j = strLastIndex - 1, k = 1; j >= 0; j--, k++)
{
if (builder.charAt(i - k) != target.charAt(j))
{
continue lastCharSearch;
}
}
return i - target.length() + 1;
}
}
return -1;
}
/**
* Creates a {@link java.util.Queue Queue} of {@link net.dv8tion.jda.core.entities.Message Message} objects from this MessageBuilder.
*
* <p>This method splits the content if it exceeds 2000 chars. The splitting behaviour can be customized using {@link SplitPolicy SplitPolicies}.
* The method will try the policies in the order they are passed to it.
* <br>If no SplitPolicy is provided each message will be split after exactly 2000 chars.
*
* <p><b>This is not Markdown safe.</b> An easy workaround is to include <a href="https://en.wikipedia.org/wiki/Zero-width_space">Zero Width Spaces</a>
* as predetermined breaking points to the message and only split on them.
*
* @param policy
* The {@link net.dv8tion.jda.core.MessageBuilder.SplitPolicy} defining how to split the text in the
* MessageBuilder into different, individual messages.
*
* @return the created {@link net.dv8tion.jda.core.entities.Message Messages}
*/
public Queue<Message> buildAll(SplitPolicy... policy)
{
if (this.isEmpty())
throw new UnsupportedOperationException("Cannot build a Message with no content. (You never added any content to the message)");
LinkedList<Message> messages = new LinkedList<Message>();
if (builder.length() <= 2000) {
messages.add(this.build());
return messages;
}
if (policy == null || policy.length == 0)
{
policy = new SplitPolicy[]{ SplitPolicy.ANYWHERE };
}
int currentBeginIndex = 0;
messageLoop:
while (currentBeginIndex < builder.length() - 2001)
{
for (int i = 0; i < policy.length; i++)
{
int currentEndIndex = policy[i].nextMessage(currentBeginIndex, this);
if (currentEndIndex != -1)
{
messages.add(build(currentBeginIndex, currentEndIndex));
currentBeginIndex = currentEndIndex;
continue messageLoop;
}
}
throw new IllegalStateException("Failed to split the messages");
}
if (currentBeginIndex < builder.length() - 1)
{
messages.add(build(currentBeginIndex, builder.length() - 1));
}
if (this.embed != null)
{
((MessageImpl) messages.get(messages.size() - 1)).setEmbeds(Collections.singletonList(embed));
}
return messages;
}
protected Message build(int beginIndex, int endIndex)
{
return new MessageImpl(-1, null, false).setContent(builder.substring(beginIndex, endIndex)).setTTS(isTTS);
}
/**
* Interface to allow custom implementation of Splitting rules for
* {@link #buildAll(net.dv8tion.jda.core.MessageBuilder.SplitPolicy...) MessageBuilder.buildAll(SplitPolicy...)}.
*/
public interface SplitPolicy
{
/**
* Splits on newline chars {@code `\n`}.
*/
SplitPolicy NEWLINE = new CharSequenceSplitPolicy("\n", true);
/**
* Splits on space chars {@code `\u0020`}.
*/
SplitPolicy SPACE = new CharSequenceSplitPolicy(" ", true);
/**
* Splits exactly after 2000 chars.
*/
SplitPolicy ANYWHERE = (i, b) -> Math.min(i + 2000, b.length());
/**
* Creates a new {@link SplitPolicy} splitting on the specified chars.
*
* @param chars
* the chars to split on
* @param remove
* weather to remove the chars when splitting on them
*
* @return a new {@link SplitPolicy}
*/
static SplitPolicy onChars(CharSequence chars, boolean remove)
{
return new CharSequenceSplitPolicy(chars, remove);
}
/**
* Default {@link SplitPolicy} implementation. Splits on a specified {@link CharSequence}.
*/
class CharSequenceSplitPolicy implements SplitPolicy
{
private final boolean remove;
private final CharSequence chars;
private CharSequenceSplitPolicy(final CharSequence chars, final boolean remove)
{
this.chars = chars;
this.remove = remove;
}
@Override
public int nextMessage(final int currentBeginIndex, final MessageBuilder builder)
{
int currentEndIndex = builder.lastIndexOf(this.chars, currentBeginIndex, currentBeginIndex + 2000 - (this.remove ? this.chars.length() : 0));
if (currentEndIndex < 0)
{
return -1;
}
else
{
return currentEndIndex + this.chars.length();
}
}
}
/**
* Calculates the endIndex for the next {@link net.dv8tion.jda.core.entities.Message Message}.
*
* @param currentBeginIndex
* the index the next {@link net.dv8tion.jda.core.entities.Message Message} should start from
* @param builder
* the {@link net.dv8tion.jda.core.MessageBuilder MessageBuilder}
*
* @return the end Index of the next {@link net.dv8tion.jda.core.entities.Message Message}
*
* @throws java.lang.IllegalStateException when splitting fails
*
*/
int nextMessage(int currentBeginIndex, MessageBuilder builder);
}
/**
* Holds the strippable mention types used in {@link MessageBuilder#stripMentions(JDA, MentionType...)}
* and {@link MessageBuilder#stripMentions(Guild, MentionType...)}
*/
public enum MentionType {
/**
* <b>@everyone</b> mentions
*/
EVERYONE,
/**
* <b>@here</b> mentions
*/
HERE,
/**
* <b>@User</b> mentions
*/
USER,
/**
* <b>#channel</b> mentions
*/
CHANNEL,
/**
* <b>@Role</b> mentions
*/
ROLE
}
/**
* Holds the available formatting used in {@link MessageBuilder#append(java.lang.CharSequence, net.dv8tion.jda.core.MessageBuilder.Formatting...)}
*/
public enum Formatting
{
ITALICS("*"),
BOLD("**"),
STRIKETHROUGH("~~"),
UNDERLINE("__"),
BLOCK("`");
private final String tag;
Formatting(String tag)
{
this.tag = tag;
}
private String getTag()
{
return tag;
}
}
}