better-chat module

better-chat: Minecraft 26.3 cheat module, full source for every implementation (1 client: Meteor Client).

1 implementationMisc

Clients with this module

Full module source: 1 implementation

Every implementation below is the complete module file, verbatim. Expand a client to read its code.

Meteor ClientMiscsrc/main/java/meteordevelopment/meteorclient/systems/modules/misc/BetterChat.javaJava · 604 lines · 20.5 KB

Improves your chat experience in various ways.

Settingsannoyfancy-chattimestampsshow-secondsplayer-headscoords-protectionkeep-historyanti-spamdepthanti-clearfilter-regexregex-filterinfinite-chat-boxlonger-chat-historyextra-linesprefixrandomtextsmall-capssuffix
BetterChat.javaJava · Minecraft 26.2 · 604 lines · 20.5 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Meteor Client distribution (https://github.com/MeteorDevelopment/meteor-client).
3
 * Copyright (c) Meteor Development.
4
 */
5
6
package meteordevelopment.meteorclient.systems.modules.misc;
7
8
import com.mojang.authlib.GameProfile;
9
import it.unimi.dsi.fastutil.chars.Char2CharMap;
10
import it.unimi.dsi.fastutil.chars.Char2CharOpenHashMap;
11
import it.unimi.dsi.fastutil.ints.IntArrayList;
12
import it.unimi.dsi.fastutil.ints.IntList;
13
import meteordevelopment.meteorclient.MeteorClient;
14
import meteordevelopment.meteorclient.commands.Commands;
15
import meteordevelopment.meteorclient.events.game.ReceiveMessageEvent;
16
import meteordevelopment.meteorclient.events.game.SendMessageEvent;
17
import meteordevelopment.meteorclient.mixin.ChatComponentAccessor;
18
import meteordevelopment.meteorclient.mixininterface.IGuiMessage;
19
import meteordevelopment.meteorclient.mixininterface.IGuiMessageVisible;
20
import meteordevelopment.meteorclient.settings.*;
21
import meteordevelopment.meteorclient.systems.modules.Categories;
22
import meteordevelopment.meteorclient.systems.modules.Module;
23
import meteordevelopment.meteorclient.utils.Utils;
24
import meteordevelopment.meteorclient.utils.misc.text.MeteorClickEvent;
25
import meteordevelopment.meteorclient.utils.player.ChatUtils;
26
import meteordevelopment.orbit.EventHandler;
27
import net.minecraft.ChatFormatting;
28
import net.minecraft.client.gui.GuiGraphicsExtractor;
29
import net.minecraft.client.gui.components.PlayerFaceExtractor;
30
import net.minecraft.client.multiplayer.PlayerInfo;
31
import net.minecraft.client.multiplayer.chat.GuiMessage;
32
import net.minecraft.client.renderer.RenderPipelines;
33
import net.minecraft.network.chat.Component;
34
import net.minecraft.network.chat.HoverEvent;
35
import net.minecraft.network.chat.MutableComponent;
36
import net.minecraft.network.chat.Style;
37
import net.minecraft.resources.Identifier;
38
import org.jetbrains.annotations.UnknownNullability;
39
40
import java.text.SimpleDateFormat;
41
import java.util.ArrayList;
42
import java.util.Date;
43
import java.util.List;
44
import java.util.Optional;
45
import java.util.regex.Matcher;
46
import java.util.regex.Pattern;
47
import java.util.regex.PatternSyntaxException;
48
49
public class BetterChat extends Module {
50
    private final SettingGroup sgGeneral = settings.getDefaultGroup();
51
    private final SettingGroup sgFilter = settings.createGroup("Filter");
52
    private final SettingGroup sgLongerChat = settings.createGroup("Longer Chat");
53
    private final SettingGroup sgPrefix = settings.createGroup("Prefix");
54
    private final SettingGroup sgSuffix = settings.createGroup("Suffix");
55
56
    private final Setting<Boolean> annoy = sgGeneral.add(new BoolSetting.Builder()
57
        .name("annoy")
58
        .description("Makes your messages aNnOyInG.")
59
        .defaultValue(false)
60
        .build()
61
    );
62
63
    private final Setting<Boolean> fancy = sgGeneral.add(new BoolSetting.Builder()
64
        .name("fancy-chat")
65
        .description("Makes your messages ғᴀɴᴄʏ!")
66
        .defaultValue(false)
67
        .build()
68
    );
69
70
    private final Setting<Boolean> timestamps = sgGeneral.add(new BoolSetting.Builder()
71
        .name("timestamps")
72
        .description("Adds client-side time stamps to the beginning of chat messages.")
73
        .defaultValue(false)
74
        .build()
75
    );
76
77
    private final Setting<Boolean> showSeconds = sgGeneral.add(new BoolSetting.Builder()
78
        .name("show-seconds")
79
        .description("Shows seconds in the chat message timestamps")
80
        .defaultValue(false)
81
        .visible(timestamps::get)
82
        .onChanged(_ -> updateDateFormat())
83
        .build()
84
    );
85
86
    private final Setting<Boolean> playerHeads = sgGeneral.add(new BoolSetting.Builder()
87
        .name("player-heads")
88
        .description("Displays player heads next to their messages.")
89
        .defaultValue(true)
90
        .build()
91
    );
92
93
    private final Setting<Boolean> coordsProtection = sgGeneral.add(new BoolSetting.Builder()
94
        .name("coords-protection")
95
        .description("Prevents you from sending messages in chat that may contain coordinates.")
96
        .defaultValue(true)
97
        .build()
98
    );
99
100
    private final Setting<Boolean> keepHistory = sgGeneral.add(new BoolSetting.Builder()
101
        .name("keep-history")
102
        .description("Prevents the chat history from being cleared when disconnecting.")
103
        .defaultValue(true)
104
        .build()
105
    );
106
107
    // Filter
108
109
    private final Setting<Boolean> antiSpam = sgFilter.add(new BoolSetting.Builder()
110
        .name("anti-spam")
111
        .description("Blocks duplicate messages from filling your chat.")
112
        .defaultValue(true)
113
        .build()
114
    );
115
116
    private final Setting<Integer> antiSpamDepth = sgFilter.add(new IntSetting.Builder()
117
        .name("depth")
118
        .description("How many messages to filter.")
119
        .defaultValue(20)
120
        .min(1)
121
        .sliderMin(1)
122
        .visible(antiSpam::get)
123
        .build()
124
    );
125
126
    private final Setting<Boolean> antiClear = sgFilter.add(new BoolSetting.Builder()
127
        .name("anti-clear")
128
        .description("Prevents servers from clearing chat.")
129
        .defaultValue(true)
130
        .build()
131
    );
132
133
    private final Setting<Boolean> filterRegex = sgFilter.add(new BoolSetting.Builder()
134
        .name("filter-regex")
135
        .description("Filter out chat messages that match the regex filter.")
136
        .defaultValue(false)
137
        .build()
138
    );
139
140
    private final Setting<List<String>> regexFilters = sgFilter.add(new StringListSetting.Builder()
141
        .name("regex-filter")
142
        .description("Regex filter used for filtering chat messages.")
143
        .visible(filterRegex::get)
144
        .onChanged(_ -> compileFilterRegexList())
145
        .build()
146
    );
147
148
149
    // Longer chat
150
151
    private final Setting<Boolean> infiniteChatBox = sgLongerChat.add(new BoolSetting.Builder()
152
        .name("infinite-chat-box")
153
        .description("Lets you type infinitely long messages.")
154
        .defaultValue(true)
155
        .build()
156
    );
157
158
    private final Setting<Boolean> longerChatHistory = sgLongerChat.add(new BoolSetting.Builder()
159
        .name("longer-chat-history")
160
        .description("Extends chat length.")
161
        .defaultValue(true)
162
        .build()
163
    );
164
165
    private final Setting<Integer> longerChatLines = sgLongerChat.add(new IntSetting.Builder()
166
        .name("extra-lines")
167
        .description("The amount of extra chat lines.")
168
        .defaultValue(1000)
169
        .min(0)
170
        .sliderRange(0, 1000)
171
        .visible(longerChatHistory::get)
172
        .build()
173
    );
174
175
    // Prefix
176
177
    private final Setting<Boolean> prefix = sgPrefix.add(new BoolSetting.Builder()
178
        .name("prefix")
179
        .description("Adds a prefix to your chat messages.")
180
        .defaultValue(false)
181
        .build()
182
    );
183
184
    private final Setting<Boolean> prefixRandom = sgPrefix.add(new BoolSetting.Builder()
185
        .name("random")
186
        .description("Uses a random number as your prefix.")
187
        .defaultValue(false)
188
        .build()
189
    );
190
191
    private final Setting<String> prefixText = sgPrefix.add(new StringSetting.Builder()
192
        .name("text")
193
        .description("The text to add as your prefix.")
194
        .defaultValue("> ")
195
        .visible(() -> !prefixRandom.get())
196
        .build()
197
    );
198
199
    private final Setting<Boolean> prefixSmallCaps = sgPrefix.add(new BoolSetting.Builder()
200
        .name("small-caps")
201
        .description("Uses small caps in the prefix.")
202
        .defaultValue(false)
203
        .visible(() -> !prefixRandom.get())
204
        .build()
205
    );
206
207
    // Suffix
208
209
    private final Setting<Boolean> suffix = sgSuffix.add(new BoolSetting.Builder()
210
        .name("suffix")
211
        .description("Adds a suffix to your chat messages.")
212
        .defaultValue(false)
213
        .build()
214
    );
215
216
    private final Setting<Boolean> suffixRandom = sgSuffix.add(new BoolSetting.Builder()
217
        .name("random")
218
        .description("Uses a random number as your suffix.")
219
        .defaultValue(false)
220
        .build()
221
    );
222
223
    private final Setting<String> suffixText = sgSuffix.add(new StringSetting.Builder()
224
        .name("text")
225
        .description("The text to add as your suffix.")
226
        .defaultValue(" | meteor on crack!")
227
        .visible(() -> !suffixRandom.get())
228
        .build()
229
    );
230
231
    private final Setting<Boolean> suffixSmallCaps = sgSuffix.add(new BoolSetting.Builder()
232
        .name("small-caps")
233
        .description("Uses small caps in the suffix.")
234
        .defaultValue(true)
235
        .visible(() -> !suffixRandom.get())
236
        .build()
237
    );
238
239
    private static final Pattern antiSpamRegex = Pattern.compile(" \\((\\d{1,9})\\)$");
240
    private static final Pattern antiClearRegex = Pattern.compile("\\n(\\n|\\s)+\\n");
241
    private static final Pattern timestampRegex = Pattern.compile("^(<\\d{2}:\\d{2}(?::\\d{2})?> )");
242
    private static final Pattern usernameRegex = Pattern.compile("^(?:<\\d{2}:\\d{2}>\\s)?<(.*?)>.*");
243
244
    private final Char2CharMap SMALL_CAPS = new Char2CharOpenHashMap();
245
    public final IntList lines = new IntArrayList();
246
247
    public BetterChat() {
248
        super(Categories.Misc, "better-chat", "Improves your chat experience in various ways.");
249
250
        String[] a = "abcdefghijklmnopqrstuvwxyz".split("");
251
        String[] b = "ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴩqʀꜱᴛᴜᴠᴡxyᴢ".split("");
252
        for (int i = 0; i < a.length; i++) SMALL_CAPS.put(a[i].charAt(0), b[i].charAt(0));
253
        compileFilterRegexList();
254
    }
255
256
    @EventHandler
257
    private void onMessageReceive(ReceiveMessageEvent event) {
258
        Component message = event.getMessage();
259
260
        if (filterRegex.get()) {
261
            String messageString = message.getString();
262
            for (Pattern pattern : filterRegexList) {
263
                if (pattern.matcher(messageString).find()) {
264
                    event.cancel();
265
                    return;
266
                }
267
            }
268
        }
269
270
        if (antiClear.get()) {
271
            String messageString = message.getString();
272
            if (antiClearRegex.matcher(messageString).find()) {
273
                MutableComponent newMessage = Component.empty();
274
                message.visit((style, string) -> {
275
                    Matcher antiClearMatcher = antiClearRegex.matcher(string);
276
                    newMessage.append(Component.literal(
277
                        antiClearMatcher.find() ? antiClearMatcher.replaceAll("\n\n") : string
278
                    ).setStyle(style));
279
280
                    return Optional.empty();
281
                }, Style.EMPTY);
282
                message = newMessage;
283
            }
284
        }
285
286
        if (antiSpam.get()) {
287
            MutableComponent antiSpammed = appendAntiSpam(message);
288
289
            if (antiSpammed != null) {
290
                message = antiSpammed;
291
            }
292
        }
293
294
        if (timestamps.get()) {
295
            MutableComponent timestamp = Component.literal("<" + dateFormat.format(new Date()) + "> ").withStyle(ChatFormatting.GRAY);
296
297
            message = Component.empty().append(timestamp).append(message);
298
        }
299
300
        event.setMessage(message);
301
    }
302
303
    @EventHandler
304
    private void onMessageSend(SendMessageEvent event) {
305
        String message = event.message;
306
307
        if (annoy.get()) message = applyAnnoy(message);
308
309
        if (fancy.get()) message = applyFancy(message);
310
311
        message = getPrefix() + message + getSuffix();
312
313
        if (coordsProtection.get() && containsCoordinates(message)) {
314
            MutableComponent warningMessage = Component.literal("It looks like there are coordinates in your message! ");
315
316
            MutableComponent sendButton = getSendButton(message);
317
            warningMessage.append(sendButton);
318
319
            ChatUtils.sendMsg(warningMessage);
320
321
            event.cancel();
322
            return;
323
        }
324
325
        event.message = message;
326
    }
327
328
    // Anti Spam
329
330
    private MutableComponent appendAntiSpam(@UnknownNullability Component text) {
331
        String textString = text.getString();
332
        MutableComponent returnText = null;
333
        int messageIndex = -1;
334
335
        List<GuiMessage> messages = ((ChatComponentAccessor) mc.gui.hud.getChat()).meteor$getAllMessages();
336
        if (messages.isEmpty()) return null;
337
338
        for (int i = 0; i < Math.min(antiSpamDepth.get(), messages.size()); i++) {
339
            String stringToCheck = messages.get(i).content().getString();
340
341
            Matcher timestampMatcher = timestampRegex.matcher(stringToCheck);
342
            if (timestampMatcher.find()) {
343
                stringToCheck = stringToCheck.substring(timestampMatcher.end());
344
            }
345
346
            if (textString.equals(stringToCheck)) {
347
                messageIndex = i;
348
                returnText = text.copy().append(Component.literal(" (2)").withStyle(ChatFormatting.GRAY));
349
                break;
350
            } else {
351
                Matcher matcher = antiSpamRegex.matcher(stringToCheck);
352
                if (!matcher.find()) continue;
353
354
                String group = matcher.group(matcher.groupCount());
355
                int number = Integer.parseInt(group);
356
357
                if (stringToCheck.substring(0, matcher.start()).equals(textString)) {
358
                    messageIndex = i;
359
                    returnText = text.copy().append(Component.literal(" (" + (number + 1) + ")").withStyle(ChatFormatting.GRAY));
360
                    break;
361
                }
362
            }
363
        }
364
365
        if (returnText != null) {
366
            List<GuiMessage.Line> visible = ((ChatComponentAccessor) mc.gui.hud.getChat()).meteor$getTrimmedMessages();
367
368
            int start = -1;
369
            for (int i = 0; i < messageIndex; i++) {
370
                start += lines.getInt(i);
371
            }
372
373
            int i = lines.getInt(messageIndex);
374
            while (i > 0) {
375
                visible.remove(start + 1);
376
                i--;
377
            }
378
379
            messages.remove(messageIndex);
380
            lines.removeInt(messageIndex);
381
        }
382
383
        return returnText;
384
    }
385
386
    public void removeLine(int index) {
387
        if (index >= lines.size()) {
388
            if (antiSpam.get()) {
389
                error("Issue detected with the anti-spam system! Likely a compatibility issue with another mod. Disabling anti-spam to protect chat integrity.");
390
                antiSpam.set(false);
391
            }
392
393
            return;
394
        }
395
396
        lines.removeInt(index);
397
    }
398
399
    // Player Heads
400
401
    private record CustomHeadEntry(String prefix, Identifier texture) {
402
    }
403
404
    private static final List<CustomHeadEntry> CUSTOM_HEAD_ENTRIES = new ArrayList<>();
405
406
    private static final Pattern TIMESTAMP_REGEX = Pattern.compile("^<\\d{1,2}:\\d{1,2}>");
407
408
    public GuiMessage.Line line;
409
410
411
    /**
412
     * Registers a custom player head to render based on a message prefix
413
     */
414
    public static void registerCustomHead(String prefix, Identifier texture) {
415
        CUSTOM_HEAD_ENTRIES.add(new CustomHeadEntry(prefix, texture));
416
    }
417
418
    static {
419
        registerCustomHead("[Meteor]", MeteorClient.identifier("textures/icons/chat/meteor.png"));
420
        registerCustomHead("[Baritone]", MeteorClient.identifier("textures/icons/chat/baritone.png"));
421
    }
422
423
    public int modifyChatWidth(int width) {
424
        if (isActive() && playerHeads.get()) return width + 10;
425
        return width;
426
    }
427
428
429
    public void beforeDrawMessage(GuiGraphicsExtractor graphics, int y, int color) {
430
        if (!isActive() || !playerHeads.get() || line == null) return;
431
432
        // Only draw the first line of multi line messages
433
        if (((IGuiMessageVisible) (Object) line).meteor$isStartOfEntry()) {
434
            drawTexture(graphics, (IGuiMessage) (Object) line, y, color);
435
        }
436
    }
437
438
    public void afterDrawMessage() {
439
        if (!isActive() || !playerHeads.get()) return;
440
441
        line = null;
442
    }
443
444
    private void drawTexture(GuiGraphicsExtractor graphics, IGuiMessage line, int y, int color) {
445
        String text = line.meteor$getText().trim();
446
447
        // Custom
448
        int startOffset = 0;
449
450
        try {
451
            Matcher m = TIMESTAMP_REGEX.matcher(text);
452
            if (m.find()) startOffset = m.end() + 1;
453
        } catch (IllegalStateException _) {
454
        }
455
456
        for (CustomHeadEntry entry : CUSTOM_HEAD_ENTRIES) {
457
            // Check prefix
458
            if (text.startsWith(entry.prefix(), startOffset)) {
459
                graphics.blit(RenderPipelines.GUI_TEXTURED, entry.texture(), 0, y, 0, 0, 8, 8, 64, 64, 64, 64, color);
460
                return;
461
            }
462
        }
463
464
        // Player
465
        GameProfile sender = getSender(line, text);
466
        if (sender == null) return;
467
468
        PlayerInfo entry = mc.getConnection().getPlayerInfo(sender.id());
469
        if (entry == null) return;
470
471
        PlayerFaceExtractor.extractRenderState(graphics, entry.getSkin(), 0, y, 8, color);
472
    }
473
474
    private GameProfile getSender(IGuiMessage line, String text) {
475
        GameProfile sender = line.meteor$getSender();
476
477
        // If the packet did not contain a sender field then try to get the sender from the message
478
        if (sender == null) {
479
            Matcher usernameMatcher = usernameRegex.matcher(text);
480
481
            if (usernameMatcher.matches()) {
482
                String username = usernameMatcher.group(1);
483
484
                PlayerInfo entry = mc.getConnection().getPlayerInfo(username);
485
                if (entry != null) sender = entry.getProfile();
486
            }
487
        }
488
489
        return sender;
490
    }
491
492
    // Timestamps
493
494
    private SimpleDateFormat dateFormat;
495
496
    private void updateDateFormat() {
497
        dateFormat = new SimpleDateFormat(showSeconds.get() ? "HH:mm:ss" : "HH:mm");
498
    }
499
500
    // Annoy
501
502
    private String applyAnnoy(String message) {
503
        StringBuilder sb = new StringBuilder(message.length());
504
        boolean upperCase = true;
505
        for (int cp : message.codePoints().toArray()) {
506
            if (upperCase) sb.appendCodePoint(Character.toUpperCase(cp));
507
            else sb.appendCodePoint(Character.toLowerCase(cp));
508
            upperCase = !upperCase;
509
        }
510
        message = sb.toString();
511
        return message;
512
    }
513
514
    // Fancy
515
516
    private String applyFancy(String message) {
517
        StringBuilder sb = new StringBuilder();
518
519
        for (char ch : message.toCharArray()) {
520
            sb.append(SMALL_CAPS.getOrDefault(ch, ch));
521
        }
522
523
        return sb.toString();
524
    }
525
526
    // Filter Regex
527
528
    private final List<Pattern> filterRegexList = new ArrayList<>();
529
530
    private void compileFilterRegexList() {
531
        filterRegexList.clear();
532
533
        for (int i = 0; i < regexFilters.get().size(); i++) {
534
            try {
535
                filterRegexList.add(Pattern.compile(regexFilters.get().get(i)));
536
            } catch (PatternSyntaxException _) {
537
                String removed = regexFilters.get().remove(i);
538
                error("Removing Invalid regex: %s", removed);
539
            }
540
        }
541
    }
542
543
    // Prefix and Suffix
544
545
    private String getPrefix() {
546
        return prefix.get() ? getAffix(prefixText.get(), prefixSmallCaps.get(), prefixRandom.get()) : "";
547
    }
548
549
    private String getSuffix() {
550
        return suffix.get() ? getAffix(suffixText.get(), suffixSmallCaps.get(), suffixRandom.get()) : "";
551
    }
552
553
    private String getAffix(String text, boolean smallcaps, boolean random) {
554
        if (random) return String.format("(%03d) ", Utils.random(0, 1000));
555
        else if (smallcaps) return applyFancy(text);
556
        else return text;
557
    }
558
559
    // Coords Protection
560
561
    private static final Pattern coordRegex = Pattern.compile("(?<x>-?\\d{3,}(?:\\.\\d*)?)(?:\\s+(?<y>-?\\d{1,3}(?:\\.\\d*)?))?\\s+(?<z>-?\\d{3,}(?:\\.\\d*)?)");
562
563
    private boolean containsCoordinates(String message) {
564
        return coordRegex.matcher(message).find();
565
    }
566
567
    private MutableComponent getSendButton(String message) {
568
        MutableComponent sendButton = Component.literal("[SEND ANYWAY]");
569
        MutableComponent hintBaseText = Component.literal("");
570
571
        MutableComponent hintMsg = Component.literal("Send your message to the global chat even if there are coordinates:");
572
        hintMsg.setStyle(hintBaseText.getStyle().applyFormat(ChatFormatting.GRAY));
573
        hintBaseText.append(hintMsg);
574
575
        hintBaseText.append(Component.literal('\n' + message));
576
577
        sendButton.setStyle(sendButton.getStyle()
578
            .applyFormat(ChatFormatting.DARK_RED)
579
            .withClickEvent(new MeteorClickEvent(Commands.get("say").toString(message)))
580
            .withHoverEvent(new HoverEvent.ShowText(
581
                hintBaseText
582
            )));
583
        return sendButton;
584
    }
585
586
    // Longer chat
587
588
    public boolean isInfiniteChatBox() {
589
        return isActive() && infiniteChatBox.get();
590
    }
591
592
    public boolean isLongerChat() {
593
        return isActive() && longerChatHistory.get();
594
    }
595
596
    public boolean keepHistory() {
597
        return isActive() && keepHistory.get();
598
    }
599
600
    public int getExtraChatLines() {
601
        return longerChatLines.get();
602
    }
603
}
604