AutoLibrarian module

AutoLibrarian: Minecraft 26.3 cheat module, full source for every implementation (1 client: OfflineClient).

1 implementationWORLD

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.

OfflineClientWORLDsrc/main/java/com/jellypudding/offlineclient/modules/world/AutoLibrarian.javaJava · 453 lines · 17.4 KB

Rerolls a librarian until it sells a book you want.

SettingsWanted booksMax priceUpdate booksLock inRangeRepair mode
AutoLibrarian.javaJava · Minecraft 26.2 · 453 lines · 17.4 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.world;
2
3
import com.jellypudding.offlineclient.event.Subscribe;
4
import com.jellypudding.offlineclient.event.events.Render3DEvent;
5
import com.jellypudding.offlineclient.event.events.TickEvent;
6
import com.jellypudding.offlineclient.module.Category;
7
import com.jellypudding.offlineclient.module.ExclusivityGroup;
8
import com.jellypudding.offlineclient.module.Module;
9
import com.jellypudding.offlineclient.setting.BoolSetting;
10
import com.jellypudding.offlineclient.setting.EnumSetting;
11
import com.jellypudding.offlineclient.setting.NumberSetting;
12
import com.jellypudding.offlineclient.setting.TextSetting;
13
import com.jellypudding.offlineclient.util.BlockMiner;
14
import com.jellypudding.offlineclient.util.BlockUtil;
15
import com.jellypudding.offlineclient.util.ChatUtil;
16
import com.jellypudding.offlineclient.util.EntityUtil;
17
import com.jellypudding.offlineclient.util.FaceMode;
18
import com.jellypudding.offlineclient.util.InputUtil;
19
import com.jellypudding.offlineclient.util.InventoryUtil;
20
import com.jellypudding.offlineclient.util.ItemUtil;
21
import com.jellypudding.offlineclient.util.RotationPriority;
22
import com.jellypudding.offlineclient.util.SwingMode;
23
import net.minecraft.client.gui.screens.inventory.MerchantScreen;
24
import net.minecraft.core.BlockPos;
25
import net.minecraft.core.Direction;
26
import net.minecraft.core.Holder;
27
import net.minecraft.core.registries.Registries;
28
import net.minecraft.network.protocol.game.ServerboundSelectTradePacket;
29
import net.minecraft.resources.Identifier;
30
import net.minecraft.resources.ResourceKey;
31
import net.minecraft.world.InteractionHand;
32
import net.minecraft.world.entity.Entity;
33
import net.minecraft.world.entity.npc.villager.Villager;
34
import net.minecraft.world.entity.npc.villager.VillagerProfession;
35
import net.minecraft.world.inventory.ContainerInput;
36
import net.minecraft.world.inventory.MerchantMenu;
37
import net.minecraft.world.item.ItemStack;
38
import net.minecraft.world.item.Items;
39
import net.minecraft.world.item.enchantment.Enchantment;
40
import net.minecraft.world.item.enchantment.EnchantmentHelper;
41
import net.minecraft.world.item.enchantment.ItemEnchantments;
42
import net.minecraft.world.item.trading.MerchantOffer;
43
import net.minecraft.world.level.block.Blocks;
44
import net.minecraft.world.phys.EntityHitResult;
45
import net.minecraft.world.phys.Vec3;
46
47
import java.util.ArrayList;
48
import java.util.HashSet;
49
import java.util.List;
50
import java.util.Locale;
51
import java.util.Set;
52
53
// Rerolls a fresh librarian's book trade by breaking and replacing its
54
// lectern until it offers a book from the wanted list.
55
public final class AutoLibrarian extends Module {
56
57
    private static final int VILLAGER_COLOR = 0xFF30E030;
58
    private static final int LECTERN_COLOR = 0xFF40C0FF;
59
    private static final int SPENT_COLOR = 0xFFE03030;
60
61
    // Trade slots of the merchant screen.
62
    private static final int RESULT_SLOT = 2;
63
64
    private enum Stage { FIND_VILLAGER, FIND_LECTERN, OPEN_TRADE, READ_TRADE, BREAK_LECTERN, PLACE_LECTERN }
65
66
    public enum Update { OFF, REMOVE, PRICE }
67
68
    // One entry of the wanted list along with the text it was written as.
69
    private record Wish(String token, Holder<Enchantment> enchantment, int level, int price) {
70
    }
71
72
    private final TextSetting wanted = new TextSetting("Wanted books",
73
        "Enchantments separated by spaces. A colon and a number sets the lowest level and a"
74
            + " second one sets the most emeralds. Example: mending unbreaking:3:20",
75
        "mending unbreaking:3 sharpness:5 protection:4 efficiency:5 fortune:3 looting:3 silk_touch");
76
    private final NumberSetting maxPrice = new NumberSetting("Max price",
77
        "The most emeralds a book may cost when its own entry names no price.",
78
        64, 1, 64, 1, " emeralds").max(64);
79
    private final EnumSetting<Update> updateBooks = new EnumSetting<>("Update books",
80
        "What to do with a book on the list once a villager has learnt it.", Update.OFF)
81
        .describe(Update.OFF, "Leave the list alone.")
82
        .describe(Update.REMOVE, "Strike it off so the next villager learns something else.")
83
        .describe(Update.PRICE, "Lower its price so the next villager has to beat this one.");
84
    private final BoolSetting lockIn = new BoolSetting("Lock in",
85
        "Buys the book once and the villager keeps the trade. Needs emeralds and paper or a book.", false);
86
    private final NumberSetting range = new NumberSetting("Range",
87
        "How far the villager and its lectern may be.", 5, 1, 6, 0.1).max(6);
88
    private final NumberSetting repairMode = new NumberSetting("Repair mode",
89
        "Stops using a tool once this many uses are left. Nought never stops.",
90
        1, 0, 100, 1, " uses").min(0);
91
    private final EnumSetting<FaceMode> faceTarget = FaceMode.setting(FaceMode.SERVER);
92
    private final EnumSetting<SwingMode> swing = SwingMode.setting(SwingMode.BOTH);
93
94
    private Stage stage;
95
    private Villager villager;
96
    private BlockPos lectern;
97
    private final Set<Integer> spent = new HashSet<>();
98
    private final InventoryUtil.HotbarLoan loan = new InventoryUtil.HotbarLoan();
99
    private int cooldown;
100
    private boolean sneaking;
101
102
    public AutoLibrarian() {
103
        super("AutoLibrarian", "Rerolls a librarian until it sells a book you want.", Category.WORLD);
104
        addSettings(wanted, maxPrice, updateBooks, lockIn, range, repairMode, faceTarget, swing);
105
        searchTags("villager trainer", "enchanted book", "lectern");
106
    }
107
108
    @Override
109
    public ExclusivityGroup getExclusivityGroup() {
110
        return ExclusivityGroup.MINING;
111
    }
112
113
    @Override
114
    public boolean savesEnabledState() {
115
        return false;
116
    }
117
118
    @Override
119
    public String getSuffix() {
120
        return stage == null ? null : switch (stage) {
121
            case FIND_VILLAGER, FIND_LECTERN -> "searching";
122
            case OPEN_TRADE, READ_TRADE -> "checking";
123
            case BREAK_LECTERN, PLACE_LECTERN -> "rerolling";
124
        };
125
    }
126
127
    @Override
128
    protected void onEnable() {
129
        stage = Stage.FIND_VILLAGER;
130
        villager = null;
131
        lectern = null;
132
        spent.clear();
133
        cooldown = 0;
134
    }
135
136
    @Override
137
    protected void onDisable() {
138
        BlockMiner.release();
139
        loan.giveBack();
140
        stopSneaking();
141
        villager = null;
142
        lectern = null;
143
    }
144
145
    @Subscribe
146
    private void onTick(TickEvent event) {
147
        if (!inGame() || mc.player.isSpectator()) {
148
            return;
149
        }
150
        if (cooldown > 0) {
151
            cooldown--;
152
            return;
153
        }
154
        if (stage != Stage.PLACE_LECTERN) {
155
            stopSneaking();
156
        }
157
        switch (stage) {
158
            case FIND_VILLAGER -> findVillager();
159
            case FIND_LECTERN -> findLectern();
160
            case OPEN_TRADE -> openTrade();
161
            case READ_TRADE -> readTrade();
162
            case BREAK_LECTERN -> breakLectern();
163
            case PLACE_LECTERN -> placeLectern();
164
        }
165
    }
166
167
    // A level one librarian that has not traded yet. Its trades can still change.
168
    private void findVillager() {
169
        Villager best = (Villager) EntityUtil.nearest(range.getValue(), this::trainable);
170
        if (best == null) {
171
            ChatUtil.error("No fresh librarian in reach."
172
                + (spent.isEmpty() ? "" : " " + spent.size() + " nearby already traded."));
173
            setEnabled(false);
174
            return;
175
        }
176
        villager = best;
177
        stage = Stage.FIND_LECTERN;
178
    }
179
180
    // A living level one librarian that has not traded yet.
181
    private boolean trainable(Entity entity) {
182
        if (!(entity instanceof Villager candidate) || !candidate.isAlive() || spent.contains(candidate.getId())) {
183
            return false;
184
        }
185
        return candidate.getVillagerData().profession().is(VillagerProfession.LIBRARIAN)
186
            && candidate.getVillagerData().level() == 1;
187
    }
188
189
    private void findLectern() {
190
        BlockPos best = null;
191
        double bestDistance = Double.MAX_VALUE;
192
        for (BlockPos pos : BlockUtil.positionsWithin(range.getValue())) {
193
            if (!BlockUtil.state(pos).is(Blocks.LECTERN)) {
194
                continue;
195
            }
196
            double distance = villager.distanceToSqr(Vec3.atCenterOf(pos));
197
            if (distance < bestDistance) {
198
                bestDistance = distance;
199
                best = pos.immutable();
200
            }
201
        }
202
        if (best == null) {
203
            ChatUtil.error("No lectern in reach for that librarian.");
204
            setEnabled(false);
205
            return;
206
        }
207
        lectern = best;
208
        stage = Stage.OPEN_TRADE;
209
    }
210
211
    private void openTrade() {
212
        if (mc.gui.screen() instanceof MerchantScreen) {
213
            stage = Stage.READ_TRADE;
214
            return;
215
        }
216
        if (mc.gui.screen() != null || mc.rightClickDelay > 0) {
217
            return;
218
        }
219
        if (!villager.isAlive() || mc.player.distanceTo(villager) > range.getValue()) {
220
            ChatUtil.error("The librarian wandered out of reach. Trap it first.");
221
            setEnabled(false);
222
            return;
223
        }
224
        Vec3 centre = villager.getBoundingBox().getCenter();
225
        faceTarget.getValue().face(centre, RotationPriority.PLACE);
226
        EntityHitResult hit = new EntityHitResult(villager, centre);
227
        if (mc.gameMode.interact(mc.player, villager, hit, InteractionHand.MAIN_HAND).consumesAction()) {
228
            swing.getValue().swing(InteractionHand.MAIN_HAND);
229
        }
230
        mc.rightClickDelay = 4;
231
    }
232
233
    private void readTrade() {
234
        if (!(mc.gui.screen() instanceof MerchantScreen screen)) {
235
            stage = Stage.OPEN_TRADE;
236
            return;
237
        }
238
        MerchantMenu menu = screen.getMenu();
239
        // Offers arrive a moment after the screen opens.
240
        if (menu.getOffers().isEmpty()) {
241
            return;
242
        }
243
        if (menu.getTraderXp() > 0) {
244
            ChatUtil.message("§bAutoLibrarian §7that librarian has traded before. Looking for another.");
245
            spent.add(villager.getId());
246
            closeTrade();
247
            stage = Stage.FIND_VILLAGER;
248
            return;
249
        }
250
        int index = 0;
251
        for (MerchantOffer offer : menu.getOffers()) {
252
            ItemStack book = offer.getResult();
253
            if (book.is(Items.ENCHANTED_BOOK)) {
254
                Wish match = wishFor(offer);
255
                if (match != null) {
256
                    accept(menu, index, book, match, offer.getCostA().getCount());
257
                    return;
258
                }
259
                ChatUtil.message("§bAutoLibrarian §7offered §f" + book.getHoverName().getString()
260
                    + "§7 for §f" + offer.getCostA().getCount() + "§7. Rerolling.");
261
                break;
262
            }
263
            index++;
264
        }
265
        closeTrade();
266
        stage = Stage.BREAK_LECTERN;
267
    }
268
269
    // The wanted entry the offer satisfies or null when none does.
270
    private Wish wishFor(MerchantOffer offer) {
271
        int price = offer.getCostA().getCount();
272
        ItemEnchantments enchantments = EnchantmentHelper.getEnchantmentsForCrafting(offer.getResult());
273
        for (Wish wish : wishes()) {
274
            if (price > wish.price()) {
275
                continue;
276
            }
277
            if (enchantments.getLevel(wish.enchantment()) >= wish.level()) {
278
                return wish;
279
            }
280
        }
281
        return null;
282
    }
283
284
    // The wanted list parsed against the enchantment registry of this world.
285
    private List<Wish> wishes() {
286
        List<Wish> result = new ArrayList<>();
287
        var registry = mc.level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT);
288
        for (String token : wanted.getValue().toLowerCase(Locale.ROOT).split("\\s+")) {
289
            if (token.isBlank()) {
290
                continue;
291
            }
292
            List<String> parts = new ArrayList<>(List.of(token.split(":")));
293
            // A trailing number is the level and two of them are the level then the price.
294
            int price = maxPrice.getInt();
295
            int level = 1;
296
            if (parts.size() > 1 && isNumber(parts.get(parts.size() - 1))) {
297
                int last = Integer.parseInt(parts.remove(parts.size() - 1));
298
                if (parts.size() > 1 && isNumber(parts.get(parts.size() - 1))) {
299
                    price = last;
300
                    level = Integer.parseInt(parts.remove(parts.size() - 1));
301
                } else {
302
                    level = last;
303
                }
304
            }
305
            Identifier id = Identifier.tryParse(String.join(":", parts));
306
            if (id == null) {
307
                continue;
308
            }
309
            int wantedLevel = level;
310
            int wantedPrice = price;
311
            registry.get(ResourceKey.create(Registries.ENCHANTMENT, id))
312
                .ifPresent(holder -> result.add(new Wish(token, holder, wantedLevel, wantedPrice)));
313
        }
314
        return result;
315
    }
316
317
    private static boolean isNumber(String text) {
318
        return !text.isEmpty() && text.chars().allMatch(Character::isDigit);
319
    }
320
321
    private void accept(MerchantMenu menu, int index, ItemStack book, Wish wish, int price) {
322
        ChatUtil.message("§bAutoLibrarian §7found §f" + book.getHoverName().getString() + "§7.");
323
        if (lockIn.isOn()) {
324
            // Buying once fixes the offers for good.
325
            menu.setSelectionHint(index);
326
            menu.tryMoveItems(index);
327
            mc.player.connection.send(new ServerboundSelectTradePacket(index));
328
            mc.gameMode.handleContainerInput(menu.containerId, RESULT_SLOT, 0, ContainerInput.QUICK_MOVE, mc.player);
329
        }
330
        updateWanted(wish, price);
331
        closeTrade();
332
        setEnabled(false);
333
    }
334
335
    // Strikes the book off the list or asks the next villager for a better price.
336
    private void updateWanted(Wish wish, int price) {
337
        if (updateBooks.is(Update.OFF)) {
338
            return;
339
        }
340
        String replacement = "";
341
        if (updateBooks.is(Update.PRICE) && price > 1) {
342
            replacement = wish.enchantment().getRegisteredName() + ":" + wish.level()
343
                + ":" + (price - 1);
344
        }
345
        List<String> kept = new ArrayList<>();
346
        boolean done = false;
347
        for (String token : wanted.getValue().split("\\s+")) {
348
            if (token.isBlank()) {
349
                continue;
350
            }
351
            if (!done && token.equalsIgnoreCase(wish.token())) {
352
                done = true;
353
                if (!replacement.isEmpty()) {
354
                    kept.add(replacement);
355
                }
356
                continue;
357
            }
358
            kept.add(token);
359
        }
360
        wanted.setValue(String.join(" ", kept));
361
        ChatUtil.message("§bAutoLibrarian §7wanted books updated.");
362
    }
363
364
    private void closeTrade() {
365
        mc.player.closeContainer();
366
        cooldown = 4;
367
    }
368
369
    private void breakLectern() {
370
        if (mc.gui.screen() != null) {
371
            return;
372
        }
373
        if (!BlockUtil.state(lectern).is(Blocks.LECTERN)) {
374
            BlockMiner.release();
375
            stage = Stage.PLACE_LECTERN;
376
            return;
377
        }
378
        int tool = ItemUtil.bestToolSlot(BlockUtil.state(lectern), 1,
379
            stack -> !ItemUtil.nearlyBroken(stack, repairMode.getInt()), InventoryUtil.HOTBAR_SIZE);
380
        if (tool != -1) {
381
            loan.select(tool);
382
        }
383
        Direction side = BlockUtil.facingSide(lectern);
384
        faceTarget.getValue().face(BlockUtil.hitPoint(lectern, side), RotationPriority.MINE);
385
        BlockMiner.mine(lectern, false, swing.getValue());
386
    }
387
388
    private void placeLectern() {
389
        if (mc.gui.screen() != null) {
390
            return;
391
        }
392
        if (BlockUtil.state(lectern).is(Blocks.LECTERN)) {
393
            stopSneaking();
394
            loan.giveBack();
395
            // The villager needs a moment to take the new job site up.
396
            cooldown = 20;
397
            stage = Stage.OPEN_TRADE;
398
            return;
399
        }
400
        if (!BlockUtil.isReplaceable(lectern)) {
401
            stage = Stage.BREAK_LECTERN;
402
            return;
403
        }
404
        int slot = InventoryUtil.findSlot(Items.LECTERN, InventoryUtil.WHOLE_INVENTORY);
405
        if (slot == -1) {
406
            ChatUtil.error("No lectern left to put back.");
407
            setEnabled(false);
408
            return;
409
        }
410
        Direction support = BlockUtil.findPlaceSupport(lectern);
411
        if (support == null) {
412
            return;
413
        }
414
        if (!loan.select(slot)) {
415
            return;
416
        }
417
        // Sneaking stops the click opening a chest or a trapdoor underneath.
418
        InputUtil.hold(mc.options.keyShift);
419
        sneaking = true;
420
        if (!mc.player.isShiftKeyDown()) {
421
            return;
422
        }
423
        BlockPos against = lectern.relative(support);
424
        faceTarget.getValue().face(BlockUtil.hitPoint(against, support.getOpposite()),
425
            RotationPriority.PLACE);
426
        if (BlockUtil.place(lectern, support, false, false)) {
427
            swing.getValue().swing(InteractionHand.MAIN_HAND);
428
        }
429
    }
430
431
    private void stopSneaking() {
432
        if (sneaking) {
433
            InputUtil.release(mc.options.keyShift);
434
            sneaking = false;
435
        }
436
    }
437
438
    @Subscribe
439
    private void onRender3D(Render3DEvent event) {
440
        if (villager != null) {
441
            event.getBatch().outlineBox(villager.getBoundingBox(), VILLAGER_COLOR, false);
442
        }
443
        if (lectern != null) {
444
            event.getBatch().outlineBlock(lectern, LECTERN_COLOR, false);
445
        }
446
        for (Entity entity : mc.level.entitiesForRendering()) {
447
            if (spent.contains(entity.getId())) {
448
                event.getBatch().outlineBox(entity.getBoundingBox(), SPENT_COLOR, false);
449
            }
450
        }
451
    }
452
}
453