### Component Example Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-data-types.md An example demonstrating how to create and append styled text components. ```javascript let msg = Component.literal("Hello ") .append(Component.literal("World").withStyle(s => s.bold(true))); ``` -------------------------------- ### Example Client Script for UI and Tooltips Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-script-types.md A comprehensive example script demonstrating custom tooltips for items, modifications to screen behavior, item modifications, and initialization logic. ```javascript // client_scripts/ui_and_tooltips.js // Custom tooltips ClientEvents.TOOLTIP.listen(event => { if (event.item.id === "minecraft:diamond") { event.tooltips.push("§6Very valuable!"); event.tooltips.push("§7Found in deep caves"); } if (event.item.id.contains("mymod:")) { event.tooltips.push("§9Custom item by MyMod"); } }); // Screen modifications ClientEvents.SCREEN_OPEN.listen(event => { let screen = event.screen; if (screen && screen.getTitle) { let title = screen.getTitle().getString(); if (title.contains("Container")) { console.log("Container opened"); } } }); // Item modifications (visual only) ItemEvents.MODIFIED.listen(event => { // Modify items that have been registered }); // Startup ClientEvents.INIT.listen(event => { console.log("Client initialized!"); if (event.minecraft.level) { console.log("Already in world"); } }); ``` -------------------------------- ### Example Startup Script for Custom Items and Blocks Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-script-types.md This example demonstrates creating a custom tool item with specific properties like display name, texture, max damage, tool type, and attack speed. It also shows how to create a custom block with properties like hardness, resistance, light level, and tool requirements. ```javascript // startup_scripts/custom_items.js StartupEvents.REGISTRY("item", event => { // Create custom tool event.create("diamond_hammer") .displayName("Diamond Hammer") .texture("mymod:item/diamond_hammer") .maxDamage(2048) .tool("pickaxe", "diamond", 2.0) .attackSpeed(0.8); // Create food item event.create("magical_food") .displayName("Magical Food") .texture("mymod:item/magical_food") .food(f => { f.nutrition(8); f.saturation(0.5); f.effect(e => { e.effect("minecraft:regeneration", 200, 1); e.probability(1.0); }); }); }); StartupEvents.REGISTRY("block", event => { // Create custom block event.create("magic_ore") .displayName("Magic Ore") .texture("mymod:block/magic_ore") .hardness(3.0) .resistance(10.0) .lightLevel(0.5) .tool("pickaxe", 2); }); ``` -------------------------------- ### Listen to Client Initialization Event Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-events.md Fired when the client initializes. Use this for client-side setup. ```java EventHandler INIT ``` -------------------------------- ### Example EventGroup and EventHandler Registration Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-core.md This example demonstrates how to create a static `EventGroup` and register a server-side event handler named 'myEvent' for a custom `MyKubeEvent` class. ```java public static final EventGroup GROUP = EventGroup.of("MyEvents"); public static final EventHandler MY_EVENT = GROUP.server("myEvent", () -> MyKubeEvent.class); ``` -------------------------------- ### Player Interaction Example in KubeJS Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-data-types.md A practical example demonstrating sending a message to a player, applying a status effect, and adding an item to their inventory. ```javascript player.tell("Hello, " + player.name + "!"); player.addEffect("minecraft:speed", 600, 1); player.getInventory().add(Item.of("minecraft:diamond")); ``` -------------------------------- ### KubeJS Server Script Example: Recipes and Tags Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-script-types.md A comprehensive example of a KubeJS server script demonstrating recipe creation (shapeless, shaped, smelting), recipe removal, item and block tag modification, and handling server lifecycle and player interaction events. ```javascript // server_scripts/recipes_and_tags.js // Define recipe mappings ServerEvents.RECIPE_MAPPING_REGISTRY.listen(event => { event.register("mymod:crafting_table", "kubejs:shaped"); }); // Add recipes ServerEvents.RECIPES(event => { // Simple shapeless event.recipes.shapeless("minecraft:diamond", [ "minecraft:diamond_block" ]); // Complex shaped event.recipes.shaped("mymod:gem_block", [ "GGG", "GGG", "GGG" ], { G: "#mymod:gems" }); // Furnace recipe event.recipes.smelting("mymod:ingot", "mymod:ore") .cookingTime(200) .experience(0.7); // Remove vanilla recipe event.remove("minecraft:diamond_pickaxe"); }); // Modify tags ServerEvents.TAGS("item", event => { event.add("minecraft:logs", "mymod:mystic_log"); event.remove("minecraft:swords", "mymod:broken_sword"); }); ServerEvents.TAGS("block", event => { event.add("minecraft:mineable/pickaxe", "mymod:magic_ore"); }); // Server lifecycle ServerEvents.LOADED.listen(event => { console.log("Server loaded with " + event.server.getPlayerCount() + " players"); }); // Player interaction PlayerEvents.LOGGED_IN.listen(event => { event.player.tell("Welcome to the server!"); event.player.tell("Type §6/help§r for commands"); }); // Block interactions BlockEvents.BROKEN.listen(event => { if (event.block.id === "mymod:magic_ore") { event.level.explode(null, event.pos.x, event.pos.y, event.pos.z, 2.0, true); } }); ``` -------------------------------- ### RecipeViewerEvents.REMOVE_RECIPES Example Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-events.md Listen for events related to recipe viewers to remove specific recipes. This example shows how to remove a recipe by its resource key. ```javascript RecipeViewerEvents.REMOVE_RECIPES.listen(event => { event.remove("minecraft:diamond"); }); ``` -------------------------------- ### StartupEvents.REGISTRY Example Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-events.md Register custom items or blocks during the mod startup phase. This is a specialized version of ServerEvents.REGISTRY. ```javascript StartupEvents.REGISTRY("item", event => { event.create("my_item") .displayName("My Custom Item") .texture("mymod:item/my_item"); }); ``` -------------------------------- ### ClientEvents.INIT Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-events.md Fired when the client initializes. This event is useful for setup tasks on the client side. ```APIDOC ## ClientEvents.INIT ### Description Fired when the client initializes. ### Event Type `ClientKubeEvent` ### Properties - **event.minecraft** (Minecraft) - The Minecraft client instance. - **event.screen** (Screen) - The current screen, which may be null. ``` -------------------------------- ### KubeJS Example: Add, Remove, and Modify Recipes Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-events.md Demonstrates adding a shaped and a smelting recipe, removing a vanilla recipe by item, and replacing all diamond inputs with emeralds. ```javascript ServerEvents.RECIPES(event => { // Add shaped recipe event.recipes.shaped("mymod:custom_item", [ "ABA", "BCB", "ABA" ], { A: "minecraft:iron_ingot", B: "minecraft:diamond", C: "minecraft:gold_ingot" }); // Add furnace recipe event.recipes.smelting("mymod:cooked_ore", "mymod:raw_ore") .cookingTime(200) .experience(1.0); // Remove vanilla recipe event.remove("minecraft:diamond"); // Replace all diamonds with emeralds event.replaceInput("minecraft:diamond", "minecraft:emerald"); }); ``` -------------------------------- ### Client Script Events and Integrations Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-script-types.md Listen to various client-side events like initialization, screen opening, and tooltips. Includes an example for JEI integration and entity spawn events. ```javascript // Client events ClientEvents.INIT.listen(event => { console.log("Client initialized"); }); ClientEvents.SCREEN_OPEN.listen(event => { console.log("Screen opened: " + event.screen); }); ClientEvents.TOOLTIP.listen(event => { event.tooltips.push("§cHovered!"); }); // Item events (client side) ItemEvents.MODIFIED.listen(event => { // Modify item display }); // JEI integration (if JEI is loaded) if (loadedMods.contains("jei")) { RecipeViewerEvents.REMOVE_RECIPES.listen(event => { event.remove("minecraft:diamond"); }); } // Client entity/player events EntityEvents.SPAWN.listen(event => { console.log("Entity spawned: " + event.entity.id); }); ``` -------------------------------- ### Command Source Methods Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-commands.md Examples of using the command source object to send messages, retrieve executor information, check permissions, and execute commands. ```javascript // Send messages source.sendSuccess(Component, true/false) // true = show to ops only source.sendFailure(Component) source.sendSystemMessage(Component) // Get executor info source.getPlayer() // Player or null source.getServer() // MinecraftServer source.getLevel() // Level/ServerLevel // Permissions source.hasPermission(level) // Check permission level (0-4) // Execute commands source.executeCommand("/command here") ``` -------------------------------- ### Listening to Startup Initialization Event Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-script-types.md Listen to the StartupEvents.INIT event to execute code once during the game's initialization phase. This is useful for setup tasks that need to run before the game world is fully loaded. ```javascript StartupEvents.INIT.listen(event => { console.log("Game is initializing"); }); ``` -------------------------------- ### Logging Examples in KubeJS Scripts Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-core.md Demonstrates how to use the console object within KubeJS scripts to log messages at different severity levels. All output is appended to the script's log file. ```javascript console.info("Hello from KubeJS!"); console.warn("This might be a problem"); console.error("Error: " + error); ``` -------------------------------- ### Registering a Command with Arguments using CommandAPI Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-commands.md Register a command that accepts arguments using CommandAPI. This example defines a 'give' command that takes 'player' and 'item' as string arguments and logs them. ```javascript event.register( CommandAPI.literal("give") .then( CommandAPI.argument("player", StringArgumentType.string()) .then( CommandAPI.argument("item", StringArgumentType.string()) .executes(ctx => { let player = ctx.getArgument("player"); let item = ctx.getArgument("item"); console.log("Give " + item + " to " + player); return 1; }) ) ) ); ``` -------------------------------- ### Client Event Listeners Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-quick-reference.md Provides an example of how to listen to client-side events in KubeJS, specifically for modifying item tooltips. ```APIDOC ## Client Event Listeners ### Description Listen to and react to various events occurring on the client. ### Events - **`ClientEvents.TOOLTIP`**: Fired when an item's tooltip is being generated, allowing for modifications. ### Example ```javascript ClientEvents.TOOLTIP.listen(event => { if (event.item.id === "minecraft:diamond") { event.tooltips.push("§cVery valuable!"); } }); ``` ``` -------------------------------- ### Modify BlockState Properties Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-data-types.md An example of creating a BlockState and then modifying one of its properties to create a new state, demonstrating the `with` method. ```javascript let oak = BlockState.create("minecraft:oak_log[axis=y]"); let rotated = oak.with("axis", "x"); console.log(rotated.value("axis")); // "x" ``` -------------------------------- ### KubeJS Platform Information Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-script-types.md Retrieve details about installed mods and Minecraft versions. `Platform.isLoaded` and `Platform.isModLoaded` are aliases. ```javascript Platform.getMods() // List of all mods Platform.isLoaded(modId) // Check if mod is loaded Platform.isModLoaded(modId) // Same as above Platform.getMinecraftVersion() // "1.21.1" Platform.getModVersion(modId) // Get mod version ``` -------------------------------- ### Registering a Custom Command Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-commands.md Register custom commands using the ServerEvents.COMMAND_REGISTRY event. This example shows a simple command that sends a success message to the executor. ```javascript ServerEvents.COMMAND_REGISTRY.listen(event => { event.register( CommandAPI.literal("mycommand") .executes(ctx => { ctx.getSource().sendSuccess("Command executed!", true); return 1; }) ); }); ``` -------------------------------- ### Create and Manipulate AABB (Bounding Box) Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Demonstrates the creation of AABB objects from coordinates or positions, and provides examples of checking containment, intersections, and modifying the box. ```javascript AABB.of(minX, minY, minZ, maxX, maxY, maxZ) AABB.of(pos1, pos2) AABB.of(blockPos) // Properties aabb.minX, minY, minZ // double aabb.maxX, maxY, maxZ // double aabb.getXsize() // double: Width aabb.getYsize() // double: Height aabb.getZsize() // double: Depth aabb.getSize() // Vec3 // Methods aabb.contains(x, y, z) // boolean aabb.contains(vec3) // boolean aabb.contains(other) // boolean: Contains other AABB aabb.intersects(other) // boolean aabb.move(x, y, z) // AABB aabb.inflate(amount) // AABB: Expanded aabb.expandTowards(direction, amount) // AABB aabb.getCenter() // Vec3 ``` -------------------------------- ### Work with Block States Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/README.md Get block instances and manipulate their states. Use `Block.getBlock()` to retrieve a block and `BlockState.create()` to define specific states. ```javascript let block = Block.getBlock("minecraft:stone"); let state = BlockState.create("minecraft:oak_log[axis=y]"); state.with("axis", "x") state.getProperties() ``` -------------------------------- ### Define a Custom EventResult Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-core.md This example shows how to create a custom `EventResult` instance, specifically `DENY`, which is used to cancel an event and prevent its default behavior. ```java public static final EventResult DENY = new EventResult(false, true); ``` -------------------------------- ### Server Event Listeners Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-quick-reference.md Provides examples of how to listen to various server-side events in KubeJS, including game load, tick updates, recipe modifications, tag updates, player login, block interactions, and item crafting. ```APIDOC ## Server Event Listeners ### Description Listen to and react to various events occurring on the server. ### Events - **`ServerEvents.LOADED`**: Fired when the server has finished loading. - **`ServerEvents.TICK`**: Fired every game tick (20 times per second). - **`ServerEvents.RECIPES`**: Fired when recipes are being processed, allowing for additions or removals. - **`ServerEvents.TAGS(type)`**: Fired when tags are being processed. `type` can be 'item', 'block', etc. - **`PlayerEvents.LOGGED_IN`**: Fired when a player joins the server. - **`PlayerEvents.TICK`**: Fired for each player every game tick. - **`BlockEvents.BROKEN`**: Fired when a block is broken. - **`BlockEvents.RIGHT_CLICKED`**: Fired when a block is right-clicked by a player. - **`ItemEvents.CRAFTED`**: Fired when an item is crafted. ### Example ```javascript // Server load event ServerEvents.LOADED.listen(event => { console.log("Server loaded"); }); // Tick event (once per second) ServerEvents.TICK.listen(event => { if (event.tickCount % 20 === 0) { // Code to run once per second } }); // Player login event PlayerEvents.LOGGED_IN.listen(event => { event.player.tell("Welcome!"); }); // Block broken event BlockEvents.BROKEN.listen(event => { if (event.block.id === "minecraft:diamond_ore") { console.log("Diamond ore broken!"); } }); ``` ``` -------------------------------- ### Dynamically Generate Smelting Recipes Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-recipes.md Generate smelting recipes for a list of ores. This example iterates through an array of ore names to create corresponding smelting recipes for ingots from raw ore. ```javascript // Create recipes for all ores const ores = ["copper", "iron", "gold", "diamond"]; ores.forEach(ore => { event.recipes.smelting( `minecraft:${ore}_ingot`, `minecraft:raw_${ore}` ).experience(0.7); }); ``` -------------------------------- ### Access Server Instance Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Obtain the server instance within server events to manage player counts, access player lists, get level data, and interact with the server's game time and function manager. This is server-side only. ```javascript ServerEvents.LOADED.listen(event => { let server = event.server; // MinecraftServer // Properties & methods server.getPlayerCount() server.getMaxPlayers() server.getPlayerList() server.getPlayerList().getPlayers() server.getLevel(dimension) server.getWorldData() server.getGameTime() server.getCompressionThreshold() server.isDedicatedServer() server.getFunctionManager() }); ``` -------------------------------- ### KubeJS Example: Modifying Crafted Item Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-events.md An example of using ServerEvents.MODIFY_RECIPE_RESULT to change the output of a shaped crafting recipe. If the crafted item is a diamond, it is replaced with an emerald. ```javascript ServerEvents.MODIFY_RECIPE_RESULT("minecraft:crafting_shaped", event => { if (event.result.id === "minecraft:diamond") { event.result = Item.of("minecraft:emerald"); } }); ``` -------------------------------- ### Create Blocks with KubeJS (Startup) Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-quick-reference.md Define new blocks during the startup phase. Customize display name, texture, hardness, resistance, light level, sound type, and render type. ```javascript StartupEvents.REGISTRY("block", event => { event.create("myblock") .displayName("My Block") .texture("mymod:block/myblock") .hardness(2.0) .resistance(10.0) .lightLevel(0.5) .soundType("stone") .renderType("cutout"); }); ``` -------------------------------- ### Create a Basic Block Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-items-blocks.md Use StartupEvents.REGISTRY to create a new block with a display name, texture, and hardness. ```javascript StartupEvents.REGISTRY("block", event => { event.create("my_block") .displayName("My Block") .texture("mymod:block/my_block") .hardness(1.5); }); ``` -------------------------------- ### Get and Inspect KubeJS Blocks Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-data-types.md Demonstrates how to get a Block object by its ID and access its properties like default state, sound type, hardness, and resistance. ```javascript Block.getBlock("minecraft:stone") Block.of("minecraft:stone") // Properties block.id // String ID block.defaultBlockState // BlockState block.soundType // Sound when broken/walked on block.hardness // float: Break time block.resistance // float: Blast resistance block.speedFactor // float: Walk speed factor // Methods block.asItem() // Get item form of block block.getNameComponent() // Display name ``` -------------------------------- ### KubeJS Class Filter Configuration Source: https://github.com/kubejs-mods/kubejs/blob/2601/README.md Use a `kubejs.classfilter.txt` file to explicitly allow or deny access to Java classes and packages in KubeJS. Lines starting with '+' explicitly allow, while lines starting with '-' explicitly deny. ```diff +mymod.api // This will *explicitly allow* anything from the mymod.api package to be used in KubeJS -mymod.api.MyModAPIImpl // This will deny access to the MyModAPIImpl class, while keeping the rest of the package accessible -mymod.internal.HttpUtil // This will *explicitly deny* your class from being used in KubeJS ``` -------------------------------- ### Create Items with KubeJS (Startup) Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-quick-reference.md Use this event to define new items during the startup phase. Customize display name, texture, stack size, rarity, tooltips, and food properties. ```javascript StartupEvents.REGISTRY("item", event => { event.create("myitem") .displayName("My Item") .texture("mymod:item/myitem") .maxStackSize(64) .fireResistant() .rarity("epic") .tooltip("Tooltip line 1") .tooltip("Tooltip line 2") .food(nutrition, saturation); }); ``` -------------------------------- ### Item/ItemStack Object Properties and Methods Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Access properties and use methods on an ItemStack object to get information or modify the stack. ```APIDOC ## Item/ItemStack Object ### Description Access properties and use methods on an ItemStack object to get information or modify the stack. ### Properties - **id** (string): The item's unique identifier (e.g., "minecraft:diamond"). - **count** (int): The current number of items in the stack. - **maxStackSize** (int): The maximum number of items allowed in a single stack. - **isEmpty** (boolean): True if the stack is empty, false otherwise. - **isDamaged** (boolean): True if the item is damaged (e.g., tools), false otherwise. - **damage** (int): The current damage value of the item. - **maxDamage** (int): The maximum damage value (durability) of the item. - **enchantmentLevel** (int): The level of a specific enchantment (requires context or method). - **rarity** (Rarity enum): The rarity tier of the item. ### Methods - **copy()**: Returns a new ItemStack that is a copy of the current one. - **withCount(n: number)**: Returns a new ItemStack with the specified count. - **enchant(id: string, level: number)**: Adds or updates an enchantment on the item stack. - **removeTagKey(key: string)**: Removes a specific NBT tag or component. - **hasTag(key: string)**: Checks if the item stack has a specific NBT tag or component. - **getTag(key: string)**: Retrieves the value of a specific NBT tag or component. - **setTag(key: string, value: any)**: Sets the value of an NBT tag or component. - **getChatComponent()**: Returns a chat component representation of the item stack. - **hasEnchantment(ench: string)**: Checks if the item has a specific enchantment. ### Examples ```javascript // Accessing properties let diamondStack = Item.of("minecraft:diamond", 10); console.log(diamondStack.id); // "minecraft:diamond" console.log(diamondStack.count); // 10 // Using methods let enchantedDiamond = diamondStack.enchant("minecraft:unbreaking", 3); enchantedDiamond.setTag("display", {Name: '"Epic Diamond"'}) ``` ``` -------------------------------- ### Block State Manipulation Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-quick-reference.md Get block states, modify their properties, and inspect their values. Use Block.getBlock() and BlockState.create() for instantiation. ```javascript // Get block let block = Block.getBlock("minecraft:stone"); let state = BlockState.create("minecraft:oak_log[axis=y]"); // Modify state let newState = state.with("axis", "x"); // Check properties console.log(state.block.id); // "minecraft:oak_log" console.log(state.value("axis")); // "y" console.log(state.getMaterial()); // Material console.log(state.lightEmission()); // int ``` -------------------------------- ### Create Recipe Ingredients Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-data-types.md Illustrates creating Ingredient objects for recipe inputs, supporting single items, multiple items, tags, and custom predicates. ```javascript Ingredient.of("minecraft:diamond") ``` ```javascript Ingredient.of("minecraft:diamond", "minecraft:emerald") ``` ```javascript Ingredient.of("#minecraft:planks") ``` ```javascript Ingredient.of(["minecraft:diamond", "#minecraft:logs"]) ``` ```javascript Ingredient.of(item => item.id.contains("diamond")) ``` -------------------------------- ### Create and Style Text Components Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Demonstrates how to create literal and translatable text components, apply various text styles like bold, italic, and color, and append components. ```javascript // Create text component Component.literal("Hello") Component.literal("World").withStyle(s => s.bold(true)) Component.translatable("chat.type.text") Component.keybind("key.jump") // Styling component.withStyle(style => { style.bold(true); style.italic(true); style.underlined(true); style.strikethrough(true); style.color(ChatFormatting.RED); style.backgroundColor(ChatFormatting.BLUE); }) component.withColor(0xFF0000) // Hex color component.withColor(ChatFormatting.RED) // Predefined color component.bold() component.italic() component.underlined() component.strikethrough() component.obfuscated() // Append components component.append(other) component.copy() component.getString() // Get text content ``` -------------------------------- ### Handle Block Right-Click Interaction Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-items-blocks.md Implement custom logic for when a player right-clicks the block. This example sends a message to non-creative players. ```javascript event.create("interact_block") .rightClick(event => { if (!event.player.isCreative()) { event.player.tell("You clicked the block!"); } }); ``` -------------------------------- ### Build KubeJS from Source Source: https://github.com/kubejs-mods/kubejs/blob/2601/README.md Run this command in the root project directory to build KubeJS. The resulting JAR files will be located in the `build/libs` directory. ```sh ./gradlew build ``` -------------------------------- ### Block & BlockState Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Represents a Minecraft block and its state. Allows getting blocks by ID, accessing block properties, and manipulating block states. ```APIDOC ## Block & BlockState ### Description Represents a Minecraft block and its state. Allows getting blocks by ID, accessing block properties, and manipulating block states. ### Getting Blocks - `Block.getBlock("minecraft:diamond_ore")`: Gets a Block object by its resource location. - `Block.of("minecraft:stone")`: Gets a Block object by its resource location. ### Block Properties - `block.defaultBlockState`: The default BlockState for this block. - `block.hardness`: float - The hardness of the block. - `block.resistance`: float - The blast resistance of the block. - `block.soundType`: SoundType - The sound type associated with the block. - `block.getNameComponent()`: Returns the component name of the block. ### BlockState Methods - `state.block`: The Block object associated with this state. - `state.getProperties()`: Returns a Map of properties and their current values. - `state.getValue(property)`: Gets the value of a specific property. - `state.with(property, value)`: Returns a new BlockState with the specified property changed. - `state.getMaterial()`: Returns the Material of the block state. - `state.getMapColor()`: Returns the MapColor of the block state. - `state.lightEmission()`: int (0-15) - Returns the light emission level. - `state.isFullBlock()`: boolean - Checks if the block state represents a full block. - `state.isAir()`: boolean - Checks if the block state is air. - `state.isReplaceable()`: boolean - Checks if the block state is replaceable. ``` -------------------------------- ### Get and Play SoundEvent Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-data-types.md Retrieve SoundEvent objects using their string identifier. The `playSound` method on the level object can be used to play these sounds. ```javascript // Get sound SoundEvent.of("minecraft:entity.pig.ambient") // Play sound level.playSound(player, x, y, z, soundEvent, category, volume, pitch) ``` -------------------------------- ### Listen to Screen Open Event Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-events.md Fired when a GUI screen opens on the client. Use this to react to screen openings. ```java EventHandler SCREEN_OPEN ``` -------------------------------- ### Get and Use Enchantment Data Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-data-types.md Retrieve enchantment objects by their ID and access their properties. Use `canEnchantItem` to check if an enchantment can be applied to an item. ```javascript // Get enchantment Enchantment.get("minecraft:sharpness") // Properties enchantment.id // String ID enchantment.name // Component: Display name enchantment.minLevel // int enchantment.maxLevel // int // Check compatibility enchantment.canEnchantItem(item) // boolean ``` -------------------------------- ### Block Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-data-types.md Represents a block type in Minecraft. Allows getting block instances, accessing properties like hardness and sound, and converting to items. ```APIDOC ## Block Represents a block type. ### Get block ```javascript Block.getBlock("minecraft:stone") Block.of("minecraft:stone") ``` ### Properties - `id` (String): The unique identifier for the block. - `defaultBlockState` (BlockState): The default state of the block. - `soundType` (SoundType): The sound associated with the block (e.g., when broken or walked on). - `hardness` (float): The time it takes to break the block. - `resistance` (float): The block's resistance to explosions. - `speedFactor` (float): The factor affecting movement speed on the block. ### Methods - `asItem()`: Returns the item form of the block. - `getNameComponent()`: Returns the display name of the block as a component. ``` -------------------------------- ### Chat Component Creation and Styling Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Demonstrates how to create and style text components for use in chat messages. Includes methods for literal and translatable text, keybinds, and various styling options like bold, italic, color, and background color. ```APIDOC ## Chat & Messaging ### Component (Text) ```javascript // Create text component Component.literal("Hello") Component.literal("World").withStyle(s => s.bold(true)) Component.translatable("chat.type.text") Component.keybind("key.jump") // Styling component.withStyle(style => { style.bold(true); style.italic(true); style.underlined(true); style.strikethrough(true); style.color(ChatFormatting.RED); style.backgroundColor(ChatFormatting.BLUE); }) component.withColor(0xFF0000) // Hex color component.withColor(ChatFormatting.RED) // Predefined color component.bold() component.italic() component.underlined() component.strikethrough() component.obfuscated() // Append components component.append(other) component.copy() component.getString() // Get text content ``` ``` -------------------------------- ### Create and Manipulate ItemStacks Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-data-types.md Demonstrates creating ItemStacks with different counts and enchantments, and manipulating their properties. ```javascript Item.of("minecraft:diamond") Item.of("minecraft:diamond", 5) // With count Item.of("minecraft:diamond_sword", {enchantments: {...}}) ``` ```javascript let diamond = Item.of("minecraft:diamond"); let stack = diamond.withCount(10); let enchanted = Item.of("minecraft:diamond_sword") .enchant("minecraft:sharpness", 5); ``` -------------------------------- ### Registering Items, Blocks, and Entities in Startup Scripts Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-script-types.md Use StartupEvents.REGISTRY to register new items, blocks, entity types, and other registry entries during mod initialization. This is the primary method for adding custom game objects. ```javascript StartupEvents.REGISTRY("item", event => { event.create("my_item"); }); // Register blocks StartupEvents.REGISTRY("block", event => { event.create("my_block"); }); // Register entities StartupEvents.REGISTRY("entity_type", event => { event.create("my_entity"); }); // Other registries: minecraft:* // item, block, entity_type, item_stack_ingredient, etc. ``` -------------------------------- ### List All Recipes Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-recipes.md Logs the total number of recipes currently registered in the server. This is a basic debugging step to verify recipe loading. ```javascript ServerEvents.RECIPES.listen(event => { console.log("Total recipes: " + event.getAll().length); }); ``` -------------------------------- ### KubeJS Recipe Creation Method Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-events.md A general template for creating new recipes. Specify the recipe type, input ingredients, output item, and optional properties like cooking time and experience. ```javascript event.recipes.({ input: Ingredient, output: ItemStack, cookingTime: int, experience: float, id: string }) ``` -------------------------------- ### KubeJS Platform Utilities Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Utilize Platform utilities to get information about loaded mods, Minecraft version, and the current environment. Includes a debugging hook. ```javascript Platform.getMods() // List of all loaded mods Platform.isLoaded(modId) // Check if mod is loaded Platform.isModLoaded(modId) // Same as isLoaded Platform.getMinecraftVersion() // String: "1.21.1" Platform.getModVersion(modId) // String: Version of mod Platform.getMod(modId) // ModInfo object Platform.getEnvironmentType() // "CLIENT" or "SERVER" Platform.breakpoint(...) // Debugging hook ``` -------------------------------- ### Create Custom Items Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/README.md Register new custom items during the startup phase. Requires specifying the item ID, display name, and texture path. ```javascript StartupEvents.REGISTRY("item", event => { event.create("item_id") .displayName("Display Name") .texture("path"); }); ``` -------------------------------- ### Smithing Recipes for Upgrades Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-recipes.md Shows how to create smithing recipes for upgrading items, such as enhancing a diamond tool to its netherite equivalent. Ensure the correct smithing template is provided as an ingredient. ```javascript // Upgrade diamond tool to netherite event.recipes.smithing("minecraft:netherite_pickaxe", "minecraft:diamond_pickaxe", "minecraft:netherite_upgrade_smithing_template"); ``` -------------------------------- ### Registry Access Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Access Minecraft's registries to get references to various game elements like items, blocks, entities, and more. This is fundamental for interacting with game data. ```APIDOC ## Registry Access ### Registries Object Get access to Minecraft's registries: ```javascript // In scripts with registry access Registries.ITEM.get("minecraft:diamond") Registries.BLOCK.get("minecraft:stone") Registries.ENTITY_TYPE.get("minecraft:pig") Registries.PARTICLE_TYPE.get("minecraft:flame") Registries.SOUND_EVENT.get("minecraft:entity.pig.ambient") Registries.MOB_EFFECT.get("minecraft:speed") Registries.ENCHANTMENT.get("minecraft:sharpness") Registries.POTION.get("minecraft:speed") Registries.DAMAGE_TYPE.get("minecraft:magic") ``` ``` -------------------------------- ### KubeJSPlugin Core Initialization Hooks Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-core.md Implement these methods for core initialization phases of your KubeJS plugin. ```java void init() ``` ```java void initStartup() ``` ```java void afterInit() ``` -------------------------------- ### Stonecutting Recipes with Multiple Outputs Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-recipes.md Demonstrates how to create stonecutting recipes where a single input can yield different outputs. Use this when a block can be processed into multiple distinct items via the stonecutter. ```javascript event.recipes.stonecutting("minecraft:oak_stairs", "minecraft:oak_planks"); event.recipes.stonecutting("minecraft:oak_slab", "minecraft:oak_planks"); // Same input can produce different outputs ``` -------------------------------- ### Access Minecraft Registries Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Access Minecraft's registries to get specific game objects by their ID. This is useful for referencing items, blocks, entities, and more within your scripts. ```javascript Registries.ITEM.get("minecraft:diamond") Registries.BLOCK.get("minecraft:stone") Registries.ENTITY_TYPE.get("minecraft:pig") Registries.PARTICLE_TYPE.get("minecraft:flame") Registries.SOUND_EVENT.get("minecraft:entity.pig.ambient") Registries.MOB_EFFECT.get("minecraft:speed") Registries.ENCHANTMENT.get("minecraft:sharpness") Registries.POTION.get("minecraft:speed") Registries.DAMAGE_TYPE.get("minecraft:magic") ``` -------------------------------- ### Get and Use MobEffect Data Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-data-types.md Obtain MobEffect objects by their ID and inspect their attributes like color and type. The `formatDuration` method converts ticks into a human-readable string. ```javascript // Get effect MobEffect.get("minecraft:speed") // Properties effect.id // String ID effect.name // Component: Display name effect.color // int: RGB color effect.isBeneficial() // boolean effect.isInstant() // boolean // Duration formatting effect.formatDuration(ticks) // String: "1:30" for ticks ``` -------------------------------- ### Server Instance Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Provides access to the server instance, typically within server-side event listeners. Allows checking player counts, accessing player lists, and managing server properties. ```APIDOC ## Server Instance ### Description Provides access to the server instance, typically within server-side event listeners. Allows checking player counts, accessing player lists, and managing server properties. ### Methods & Properties - `event.server`: The server instance (MinecraftServer). - `server.getPlayerCount()`: Gets the current number of players. - `server.getMaxPlayers()`: Gets the maximum number of players allowed. - `server.getPlayerList()`: Gets the list of players. - `server.getPlayerList().getPlayers()`: Retrieves the actual player objects. - `server.getLevel(dimension)`: Gets a specific level/world by dimension. - `server.getWorldData()`: Gets the world data. - `server.getGameTime()`: Gets the total game time in ticks. - `server.getCompressionThreshold()`: Gets the network compression threshold. - `server.isDedicatedServer()`: Checks if it's a dedicated server. - `server.getFunctionManager()`: Gets the function manager. ``` -------------------------------- ### Create Custom Blocks Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/README.md Register new custom blocks during the startup phase. Requires specifying the block ID, display name, and texture path. ```javascript StartupEvents.REGISTRY("block", event => { event.create("block_id") .displayName("Display Name") .texture("path"); }); ``` -------------------------------- ### KubeJS Script Organization: By Type Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-script-types.md Recommended structure for organizing scripts by their function (startup, server, client). ```directory kubejs/ ├── startup_scripts/ │ ├── items.js │ ├── blocks.js │ ├── entities.js │ └── main.js ├── server_scripts/ │ ├── recipes.js │ ├── tags.js │ ├── events.js │ └── commands.js └── client_scripts/ ├── tooltips.js ├── screens.js └── jei.js ``` -------------------------------- ### KubeJS Direction Enum and Properties Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Access and utilize the Direction enum for various game-related operations. Includes methods for getting opposite directions, axis information, and rotational equivalents. ```javascript Direction.UP Direction.DOWN Direction.NORTH Direction.SOUTH Direction.EAST Direction.WEST // Or get by name Direction.valueOf("NORTH") // Properties dir.name // String: "north" dir.getOpposite() // Direction dir.getAxis() // Axis: X, Y, or Z dir.getAxisDirection() // int: 1 or -1 dir.getClockWise() // Direction: Rotated 90° dir.getCounterClockWise() // Direction // Step offset dir.step // BlockPos: Unit step in direction ``` -------------------------------- ### ServerEvents.BASIC_COMMAND Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-commands.md Listens for basic commands with a simpler invocation syntax, not requiring the `/kubejs` prefix. ```APIDOC ## ServerEvents.BASIC_COMMAND ### Description This event handler is for registering basic commands that can be invoked directly by their name, without needing the `/kubejs` prefix. It offers a simplified command registration process. ### Method Event Listener ### Event `ServerEvents.BASIC_COMMAND` ### Usage ```javascript ServerEvents.BASIC_COMMAND("greet").listen(event => { let player = event.player; player.tell("Hello, " + player.name + "!"); }); ``` ### Parameters * **commandName** (string): The name of the basic command to register. * **event**: An object containing event details: * **player**: The player who executed the command. * **player.name**: The name of the player. ``` -------------------------------- ### Tags Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Interact with item and block tags. You can get tag data, check if an item belongs to a tag, retrieve all items within a tag, and use string references for recipes. ```APIDOC ## Utility & Helper Objects ### Tags Access tag data: ```javascript // Get tag let planks = Tags.ITEMS.get("minecraft:planks"); // Check if item in tag let isPlank = planks.contains(Item.of("minecraft:oak_planks")); // Get all items in tag let items = planks.getValues(); // Create tag reference for recipes "#minecraft:planks" // String reference ``` ``` -------------------------------- ### KubeJS Direction Type Usage Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-data-types.md Demonstrates how to get and use direction objects in KubeJS. Includes accessing properties like name, step, and methods for rotation and axis information. ```javascript Direction.of("north") Direction.DOWN direction.name // String: "north" direction.step // BlockPos offset direction.getOpposite() // Opposite direction direction.getAxis() // Axis: X, Y, or Z direction.getClockWise() // Rotate clockwise direction.getCounterClockWise() // Rotate counter-clockwise direction.getAxisDirection() // 1 or -1 ``` -------------------------------- ### Component Creation and Styling Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-data-types.md Create text components for chat messages and tooltips, with options for translation and styling. ```javascript // Create Component.literal("Text") Component.translatable("translation.key") Component.keybind("key.jump") // Styling component.withStyle(style => { style.color(ChatFormatting.RED); style.bold(true); style.italic(true); style.underlined(true); style.strikethrough(true); }) component.withColor(0xFF0000) // Hex color component.withColor(ChatFormatting.RED) // Enum color ``` -------------------------------- ### Create and Manipulate KubeJS BlockStates Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-data-types.md Shows how to create a BlockState from a string, access its properties, and modify properties to create new states. ```javascript // Get state BlockState.create("minecraft:oak_log[axis=y]") // Properties state.block // The block type state.properties // Map of properties state.value(prop) // Get property value state.with(prop, value) // New state with changed property // Query methods state.isFullBlock() // Fills entire block space state.getMaterial() // Material type state.getMapColor() // Color on maps state.lightEmission() // Light level state.isOpaque() // Is opaque to light ``` -------------------------------- ### /kubejs reload_startup_scripts Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-commands.md Reloads all startup scripts without requiring a full game restart. Useful after modifying startup scripts that register items or blocks. ```APIDOC ## /kubejs reload_startup_scripts ### Description Reloads all startup scripts without requiring a full game restart. This command is useful after modifying startup scripts, particularly those that register new items or blocks. Note that it may not be reliable if scripts modify JVM state beyond simple registration. ### Method Command ### Endpoint /kubejs reload_startup_scripts ### Parameters None ### Usage Run this command on the server to reload startup scripts. ### Requires Server operator privileges ### Output Logs changes to `logs/kubejs/startup.log` ``` -------------------------------- ### Listen to Events Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/README.md Use this pattern to listen for and handle game events. Requires the event name to be specified. ```javascript EventName.listen(event => { // Handle event }); ``` -------------------------------- ### Access Item/ItemStack Properties Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Access various properties of an ItemStack object to get information about the item, such as its ID, count, stack size, enchantments, and NBT data. These properties are read-only for most attributes. ```javascript item.id // String: "minecraft:diamond" item.count // int: Stack size item.maxStackSize // int: Max stack size item.isEmpty // boolean item.isDamaged // boolean item.damage // int: Current damage item.maxDamage // int: Max durability item.enchantmentLevel // int item.hasEnchantment(ench) // boolean item.rarity // Rarity enum ``` -------------------------------- ### Reloading KubeJS Scripts Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-script-types.md Commands and keybinds to reload server, client, or startup scripts without restarting the game. Startup scripts require a full game restart. ```plaintext // Reload server scripts /reload // Reload client scripts F3 + T (or Ctrl+R on some keys) // Reload startup scripts Requires game restart ``` -------------------------------- ### Create Multi-Input Crafting Recipe Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-recipes.md Define a shaped crafting recipe that requires multiple different types of ingredients arranged in a specific pattern. This example uses planks, diamonds, and iron ingots. ```javascript event.recipes.shaped("mymod:crafted_item", [ "ABA", "BCB", "ABA" ], { A: "#minecraft:planks", B: "minecraft:diamond", C: "minecraft:iron_ingot" }); ``` -------------------------------- ### Create and Style Chat Components Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-quick-reference.md Components can be created using Component.literal() and then styled using methods like withStyle(), withColor(), and bold(). Components can also be appended with additional text and sent directly to a player using player.tell(). ```javascript // Create component let msg = Component.literal("Hello World"); // Style msg.withStyle(style => { style.bold(true); style.italic(false); style.color(ChatFormatting.RED); style.underlined(true); }); // Shorthand Component.literal("Red Bold") .withColor(0xFF0000) .bold(); // Append msg.append(" and more text"); // Send to player player.tell(msg); ``` -------------------------------- ### Access and Use Item Tags Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-bindings.md Interact with item tags to get tag data, check if an item belongs to a tag, retrieve all items within a tag, or use string references for recipes. ```javascript // Get tag let planks = Tags.ITEMS.get("minecraft:planks"); // Check if item in tag let isPlank = planks.contains(Item.of("minecraft:oak_planks")); // Get all items in tag let items = planks.getValues(); // Create tag reference for recipes "#minecraft:planks" // String reference ``` -------------------------------- ### Get Common KubeJS Properties Source: https://github.com/kubejs-mods/kubejs/blob/2601/_autodocs/kubejs-core.md Access common configuration properties that apply to both server and client environments. This allows for checking server-only script loading or setting maximum recipe data sizes. ```java public static CommonProperties get() public boolean serverOnly public boolean maxRecipeDataSize ```