Created
October 20, 2023 11:42
-
-
Save Ensamisten/412e6eb009c610fe0e0b3fc9ce6bfcaf to your computer and use it in GitHub Desktop.
WriteBookCommand. Usage: Get a Book and Quill and send the command to the chat: /writebook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.github.ensamisten.forgient.command; | |
import com.mojang.brigadier.CommandDispatcher; | |
import com.mojang.brigadier.arguments.StringArgumentType; | |
import com.mojang.brigadier.context.CommandContext; | |
import net.minecraft.commands.CommandSourceStack; | |
import net.minecraft.commands.Commands; | |
import net.minecraft.nbt.CompoundTag; | |
import net.minecraft.nbt.ListTag; | |
import net.minecraft.nbt.StringTag; | |
import net.minecraft.network.chat.Component; | |
import net.minecraft.server.level.ServerPlayer; | |
import net.minecraft.world.item.ItemStack; | |
import net.minecraft.world.item.Items; | |
public class WriteBookCommand { | |
public static void register(CommandDispatcher<CommandSourceStack> dispatcher) { | |
dispatcher.register( | |
Commands.literal("writebook") | |
.then(Commands.argument("text", StringArgumentType.greedyString()) | |
.executes(WriteBookCommand::writeBook))); | |
} | |
private static int writeBook(CommandContext<CommandSourceStack> context) { | |
String text = StringArgumentType.getString(context, "text"); | |
ServerPlayer player = context.getSource().getPlayer(); | |
ItemStack heldItem = player.getMainHandItem(); | |
if (heldItem.getItem() == Items.WRITABLE_BOOK) { | |
ListTag pages = new ListTag(); | |
pages.add(StringTag.valueOf(text)); | |
CompoundTag bookTag = heldItem.getOrCreateTag(); | |
bookTag.put("pages", pages); | |
context.getSource().sendSuccess(() -> Component.literal("Text written to the book!"), true); | |
return 1; | |
} else { | |
context.getSource().sendFailure(Component.literal("You need to hold a writable book in your hand!")); | |
return 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment