### Example Script (1.19.2+ and 1.18.2 and below) Source: https://kubejs.com/wiki/addons/blood-magic An example script demonstrating the usage of various Blood Magic recipe functions. ```APIDOC ```java onEvent('recipes', event => { const { altar, array, soulforge, arc, alchemytable } = event.recipes.bloodmagic alchemytable('minecraft:gold_ingot', ['minecraft:iron_ingot', 'minecraft:iron_ingot', 'minecraft:iron_ingot', 'minecraft:iron_ingot']).upgradeLevel(2) altar('minecraft:carrot', 'minecraft:apple') arc('minecraft:netherite_ingot', 'minecraft:iron_ingot', 'minecraft:iron_pickaxe', [Item.of('minecraft:cobblestone').withChance(0.4)]) array('minecraft:spruce_planks', 'minecraft:oak_planks', 'minecraft:birch_planks') soulforge('minecraft:stone', ['minecraft:gold_ore', 'minecraft:diamond_ore', 'minecraft:iron_ore']).drain(1) }) ``` ``` -------------------------------- ### Example Script Source: https://kubejs.com/wiki/addons/tinkers-construct Demonstrates how to use the casting table and casting basin recipe definitions within a KubeJS event. ```APIDOC ## Example Script (1.19.2+ / 1.18.2 and below) ```APIDOC onEvent('recipes', event => { const { casting_table, casting_basin } = event.recipes.tconstruct // Casting Table example with a single-use cast casting_table('minecraft:carrot', 'minecraft:water').singleUseCast('nugget') // Casting Basin example with default cast and fluid amount casting_basin('minecraft:coal_block', 'minecraft:lava') // Casting Basin example with a specific cast and fluid casting_basin('minecraft:emerald', 'minecraft:water').cast('#forge:dusts/emerald') }) ``` ``` -------------------------------- ### RecipeViewerEvents.addEntries Example Source: https://kubejs.com/wiki/events/RecipeViewerEvents/addEntries This example demonstrates how to use RecipeViewerEvents.addEntries to add a new item recipe. The event handler receives an 'event' object with an 'add' method to define the recipe. ```APIDOC ## RecipeViewerEvents.addEntries ### Description Allows adding custom recipes to the recipe viewer. ### Method Signature `RecipeViewerEvents.addEntries(type, eventHandler)` ### Parameters - **type** (string) - The type of recipe to add (e.g., 'item'). - **eventHandler** (function) - A callback function that receives an event object with methods to define the recipe. ### Example Usage ```javascript RecipeViewerEvents.addEntries('item', event => { event.add('minecraft:stone_sword[custom_data={a:2},enchantment_glint_override=true,damage=40]'); }); ``` ### Event Object Methods #### add(recipeString) - **recipeString** (string) - A string representing the recipe to be added. This can include item IDs, NBT data, and enchantments. ``` -------------------------------- ### Recipe JSON Insertion Example Source: https://kubejs.com/wiki/addons/probejs Demonstrates direct insertion of recipe JSONs using ProbeJS, simplifying recipe creation. ```javascript event.recipes.kubejs.custom_recipe({"type": "minecraft:smelting", "ingredient": {"item": "minecraft:iron_ore"}, "result": "minecraft:iron_ingot", "experience": 0.7, "cookingtime": 200}); ``` -------------------------------- ### Add Freezing Recipe Source: https://kubejs.com/wiki/addons/garnished Use this to add a freezing recipe. This example shows how to create powder snow from water. ```javascript event.recipes.garnished.freezing('minecraft:powder_snow_bucket', 'minecraft:water_bucket', 200).id('garnished_kubejs:freezing/powder_snow_bucket_from_water_bucket') ``` -------------------------------- ### Tinkers Construct Example Script Source: https://kubejs.com/wiki/addons/tinkers-construct An example script demonstrating the creation of casting table and casting basin recipes with various modifiers. ```javascript onEvent('recipes', event => { const { casting_table, casting_basin } = event.recipes.tconstruct casting_table('minecraft:carrot', 'minecraft:water').singleUseCast('nugget') casting_basin('minecraft:coal_block', 'minecraft:lava') casting_basin('minecraft:emerald', 'minecraft:water').cast('#forge:dusts/emerald') }) ``` -------------------------------- ### Example Fluid Sound Registration Source: https://kubejs.com/wiki/tutorials/fluid-registry Demonstrates how to register a sound event for a specific fluid action, such as filling a bucket. ```javascript sound($SoundActions.BUCKET_FILL, $SoundEvents.AMETHYST_BLOCK_BREAK) ``` -------------------------------- ### Create Splashing Recipe (Multiple Outputs) Source: https://kubejs.com/wiki/addons/create Adds a splashing recipe with multiple potential outputs. This example shows how to define a list of items as outputs. ```javascript ServerEvents.recipes(event => { event.recipes.create.splashing(['minecraft:wheat', 'minecraft:oak_sapling'], 'minecraft:potato') }) ``` -------------------------------- ### Example Blood Magic Script Source: https://kubejs.com/wiki/addons/blood-magic Demonstrates how to use various Blood Magic recipe functions within a KubeJS event. ```javascript onEvent('recipes', event => { const { altar, array, soulforge, arc, alchemytable } = event.recipes.bloodmagic alchemytable('minecraft:gold_ingot', ['minecraft:iron_ingot', 'minecraft:iron_ingot', 'minecraft:iron_ingot', 'minecraft:iron_ingot']).upgradeLevel(2) altar('minecraft:carrot', 'minecraft:apple') arc('minecraft:netherite_ingot', 'minecraft:iron_ingot', 'minecraft:iron_pickaxe', [Item.of('minecraft:cobblestone').withChance(0.4)]) array('minecraft:spruce_planks', 'minecraft:oak_planks', 'minecraft:birch_planks') soulforge('minecraft:stone', ['minecraft:gold_ore', 'minecraft:diamond_ore', 'minecraft:iron_ore']).drain(1) }) ``` -------------------------------- ### Create Custom Sword Item Source: https://kubejs.com/wiki/tutorials/item-registry This example shows how to create a custom sword item, specifying its type and tier, and setting its base attack damage. ```javascript // You can specify item type as 2nd argument in create(), some types have different available methods event.create('custom_sword', 'sword').tier('diamond').attackDamageBaseline(10) ``` -------------------------------- ### removeEntries Example Source: https://kubejs.com/wiki/events/RecipeViewerEvents/removeEntries An example demonstrating how to use RecipeViewerEvents.removeEntries to remove various types of recipes. ```APIDOC ## removeEntries ### Description Allows for the removal of specific recipes based on item ID or ingredient. ### Method `RecipeViewerEvents.removeEntries(type, callback)` ### Parameters #### Path Parameters - `type` (string) - The type of recipe to remove (e.g., 'item'). - `callback` (function) - A function that receives an event object with a `remove` method. ### Request Example ```javascript RecipeViewerEvents.removeEntries('item', event => { event.remove('minecraft:tipped_arrow') event.remove('minecraft:splash_potion') event.remove(Ingredient.of('minecraft:lingering_potion').except('minecraft:lingering_potion[potion_contents={potion:"minecraft:night_vision"}]')) event.remove('minecraft:beetroot_seeds') }) ``` ### Response #### Success Response (200) This event does not return a value, but modifies the recipe list. #### Response Example N/A ``` -------------------------------- ### FTBQuestsEvents.started Source: https://kubejs.com/wiki/addons/ftb-xmod-compat Executes code when a player starts a quest. It sends a server-wide message indicating the quest start. ```javascript FTBQuestsEvents.started('quest_id', event => { event.server.tell('A player started a quest!') }) ``` -------------------------------- ### Registering a Basic GUI Source: https://kubejs.com/wiki/addons/screenjs This is for creating completely separate, basic GUIs that are not tied to specific blocks or entities. It has a minimal setup. ```javascript StartupEvents.registry('menu', event => { event.create('name_here' /*name can be anything*/) /*default parameter set*/ }) ``` -------------------------------- ### Registering Fluids with StartupEvents Source: https://kubejs.com/wiki/tutorials/fluid-registry-legacy Use StartupEvents to register new fluids. This example shows how to create basic thick and thin fluids, fluids with custom textures, and fluids with modified bucket items. Supports various texture and property configurations. ```javascript StartupEvents.registry('fluid', event => { // Basic "thick" (looks like lava) fluid with red tint event.create('thick_fluid') .thickTexture(0xFF0000) .bucketColor(0xFF0000) .displayName('Thick Fluid') // Basic "thin" (looks like water) fluid with cyan tint, has no bucket and is not placeable event.create('thin_fluid') .thinTexture(0xFF0000) .bucketColor(0x00FFFF) .displayName('Thin Fluid') .noBucket() .noBlock() // Fluid with custom textures event.create('strawberry_cream') .displayName('Strawberry Cream') .stillTexture('kubejs:block/strawberry_still') .flowingTexture('kubejs:block/strawberry_flow') .bucketColor(0xFF33FF) // Fluid with a modified bucket item const tacoSauce = event .create('taco_sauce') .thickTexture(0xff0000) .bucketColor(0xff0000) tacoSauce.bucketItem.group('food') }) ``` -------------------------------- ### Example Dripstone Dripping Configuration Source: https://kubejs.com/wiki/tutorials/fluid-registry Configures a fluid to drip from Pointed Dripstone, including particle effects and sounds when filling cauldrons. ```javascript addDripstoneDripping(1, $ParticleTypes.DRIPPING_DRIPSTONE_LAVA, 'minecraft:lava_cauldron', $SoundEvents.POINTED_DRIPSTONE_DRIP_LAVA) ``` -------------------------------- ### Sequenced Assembly with Item.of and withChance Source: https://kubejs.com/wiki/addons/create This example shows an alternative way to define outputs for sequenced assembly recipes using `Item.of().withChance()`. This method allows for more granular control over the probability of each output item. ```javascript ServerEvents.recipes(event => { event.recipes.create.sequenced_assembly( // Outputs: [ Item.of('create:precision_mechanism').withChance(130), // Main output, will appear in JEI as the result Item.of('create:golden_sheet').withChance(8), // Rest of these items will be considered Random Salvage Item.of('create:andesite_alloy').withChance(8), Item.of('create:cogwheel').withChance(5), Item.of('create:shaft').withChance(2), Item.of('create:crushed_gold_ore').withChance(2), Item.of('2x minecraft:gold_nugget').withChance(2), ``` -------------------------------- ### FTBQuestsEvents.started Source: https://kubejs.com/wiki/addons/ftb-xmod-compat Executes code when a player starts a quest. Requires a quest ID. ```APIDOC ## FTBQuestsEvents.started ### Description Executes code when a player starts a quest. ### Method `FTBQuestsEvents.started(quest_id, event_handler)` ### Parameters #### Path Parameters - **quest_id** (string) - Required - The ID of the quest to listen for. #### Event Handler - **event** (object) - The event object containing server and player information. - **server** (object) - Server-side information. - **tell**(message: string) - Sends a message to all players on the server. ### Example ```javascript FTBQuestsEvents.started('quest_id', event => { event.server.tell('A player started a quest!') }) ``` ``` -------------------------------- ### Item Snippet Example Source: https://kubejs.com/wiki/addons/probejs Example of how ProbeJS generates code snippets for items, enabling autocompletion for item IDs. ```javascript event.recipes.kubejs.shaped("minecraft:iron_ingot", ["aaa", "a a", "aaa"], {"a": "minecraft:iron_ingot"}); ``` -------------------------------- ### Registering a Menu for Entities Source: https://kubejs.com/wiki/addons/screenjs Use this to create a custom GUI that opens when interacting with a specific entity. It's a simpler setup compared to block entities. ```javascript StartupEvents.registry('menu', event => { event.create('snow_golem' /*name can be anything*/, 'entity') /*default parameter set*/ .setEntity('minecraft:snow_golem') // the enity type that should open this GUI on right-click }) ``` -------------------------------- ### Create Thin Fluid Source: https://kubejs.com/wiki/tutorials/fluid-registry Use the 'thin' argument to create a fluid with a transparent texture. This example demonstrates adding dripstone dripping behavior. ```javascript const $SoundEvents = Java.loadClass('net.minecraft.sounds.SoundEvents') const $ParticleTypes = Java.loadClass('net.minecraft.core.particles.ParticleTypes') StartupEvents.registry('fluid', event => { event.create('water_clone', 'thin') .displayName('Water Clone') .type(type => type.addDripstoneDripping(1, $ParticleTypes.DRIPPING_DRIPSTONE_WATER, 'minecraft:water_cauldron', $SoundEvents.POINTED_DRIPSTONE_DRIP_WATER) ) }) ``` -------------------------------- ### Create Sequenced Assembly Recipe Example Source: https://kubejs.com/wiki/addons/create Defines a sequenced assembly recipe for a precision mechanism. Use this to create multi-step crafting processes where intermediate items are important. Ensure the transitional item is registered. ```javascript event.recipes.create.deploying('create:incomplete_precision_mechanism', ['create:incomplete_precision_mechanism', 'create:cogwheel',]) event.recipes.create.deploying('create:incomplete_precision_mechanism', ['create:incomplete_precision_mechanism', 'create:large_cogwheel',]) event.recipes.create.deploying('create:incomplete_precision_mechanism', ['create:incomplete_precision_mechanism', 'minecraft:iron_nugget',]) ``` ```javascript event.recipes.create.sequenced_assembly( // Outputs: [ Item.of('minecraft:iron_ingot').withChance(1), Item.of('minecraft:clock').withChance(1) ], // Input: 'create:golden_sheet', // Sequence: [ // The transitional item set by `transitionalItem('create:incomplete_large_cogwheel')` is the item used during the intermediate stages of the assembly // Like a normal recipe function, it's used as a sequence step in this array. Input and output have the transitional item event.recipes.create.deploying('create:incomplete_precision_mechanism', ['create:incomplete_precision_mechanism', 'create:cogwheel',]), event.recipes.create.deploying('create:incomplete_precision_mechanism', ['create:incomplete_precision_mechanism', 'create:large_cogwheel',]), event.recipes.create.deploying('create:incomplete_precision_mechanism', ['create:incomplete_precision_mechanism', 'minecraft:iron_nugget',]) ] ) .transitionalItem('create:incomplete_precision_mechanism') // Set the transitional item .loops(5) // Set the number of loops ``` -------------------------------- ### Create Thick Fluid Source: https://kubejs.com/wiki/tutorials/fluid-registry Use the 'thick' argument to create a fluid with a grayscale texture. This example sets the display name, tint, and dripstone dripping behavior. ```javascript const $SoundEvents = Java.loadClass('net.minecraft.sounds.SoundEvents') const $ParticleTypes = Java.loadClass('net.minecraft.core.particles.ParticleTypes') StartupEvents.registry('fluid', event => { event.create('lava_clone', 'thick') .displayName('Lava Clone') .tint(0xff6600) .type(type => type.addDripstoneDripping(1, $ParticleTypes.DRIPPING_DRIPSTONE_LAVA, 'minecraft:lava_cauldron', $SoundEvents.POINTED_DRIPSTONE_DRIP_LAVA) ) }) ``` -------------------------------- ### Rich Item Display Example Source: https://kubejs.com/wiki/addons/probejs Illustrates ProbeJS's capability for rich item display, providing detailed information on hover (requires VSCode extension v4.8.0+). ```javascript event.item.addTooltip("minecraft:diamond", "A precious gem."); ``` -------------------------------- ### Adding Tooltips Source: https://kubejs.com/wiki/events/ItemEvents/modifyTooltips Demonstrates how to add simple text tooltips to items based on filters, with an example of conditional display based on player input. ```APIDOC ## ItemEvents.modifyTooltips.add ### Description Adds text lines to an item's tooltip. Can be filtered by item ID or a regular expression. Optionally accepts requirements for display. ### Methods - `event.add(filter, Text[])` - `event.add(filter, TooltipRequirements, Text[])` ### Parameters #### `filter` - Type: `String | RegExp` - Description: The item ID or a regular expression to match item IDs. #### `TooltipRequirements` (Optional) - Type: `Object` - Description: An object specifying conditions for the tooltip to be displayed. - `shift` (boolean): If true, requires the shift key to be pressed. - `ctrl` (boolean): If true, requires the ctrl key to be pressed. - `alt` (boolean): If true, requires the alt key to be pressed. - `advanced` (boolean): If true, requires advanced tooltips to be enabled (F3+H). - `creative` (boolean): If true, requires the player to be in creative mode. - `stages` (Object): An object with stage names as keys and boolean values to check player stages. #### `Text[]` - Type: `Text[]` - Description: An array of Text objects to be displayed as tooltip lines. ### Example ```javascript ItemEvents.modifyTooltips(event => { // Show this tooltip for all red blocks event.add(/minecraft:red_/, Text.red('Red!')) // Only show this text when shift is not pressed event.add('minecraft:campfire', {shift: false}, Text.gray('Campfire :D')) // Only show this text when shift is pressed event.add('minecraft:campfire', {shift: true}, Text.gray('Campfire :(')) }) ``` ``` -------------------------------- ### Add Multiple Machines to a Recipe Source: https://kubejs.com/wiki/addons/kubejs-tfmg To specify multiple machines for a recipe, simply add them as additional arguments to the `.machines()` method. This example requires three electrodes. ```javascript .machines("tfmg:electrode", "tfmg:electrode", "tfmg:electrode") ``` -------------------------------- ### Create Sequenced Assembly Spore Blossom Recipe Source: https://kubejs.com/wiki/addons/create Defines a sequenced assembly recipe for spore blossoms and related items. This example demonstrates using a constant for the transitional item and includes various crafting steps like pressing, deploying, filling, and cutting. ```javascript const transitional = 'kubejs:incomplete_spore_blossom' // Making a constant to store the transitional item makes the code more readable event.recipes.create.sequenced_assembly( // Outputs: [ Item.of('minecraft:spore_blossom').withChance(16), // Main output, will appear in JEI as the result Item.of('minecraft:flowering_azalea_leaves').withChance(16), // Rest of these items will be considered Random Salvage Item.of('minecraft:azalea_leaves').withChance(2), 'minecraft:oak_leaves', 'minecraft:spruce_leaves', 'minecraft:birch_leaves', 'minecraft:jungle_leaves', 'minecraft:acacia_leaves', 'minecraft:dark_oak_leaves' ], // Input: 'minecraft:flowering_azalea_leaves', // Sequence: [ // The transitional item is a constant, that is 'kubejs:incomplete_spore_blossom' and is used during the intermediate stages of the assembly. // Like a normal recipe function, is used as a sequence step in this array. Input and output have the transitional item. event.recipes.create.pressing(transitional, transitional), event.recipes.create.deploying(transitional, [transitional, 'minecraft:hanging_roots']), event.recipes.create.filling(transitional, [transitional, Fluid.of('minecraft:water', 420)]), event.recipes.create.deploying(transitional, [transitional, 'minecraft:moss_carpet']) event.recipes.create.cutting(transitional, transitional), ] ) .transitionalItem(transitional) // Set the transitional item .loops(2) // Set the number of loops ``` -------------------------------- ### Make Goats Milkable with Bucket Source: https://kubejs.com/wiki/tutorials/item-interactions Handle entity interaction events to customize player interactions with entities. This example makes goats milkable using a bucket, consuming the bucket and giving milk. ```javascript ItemEvents.entityInteracted('minecraft:bucket', event => { if(event.target.type != 'minecraft:goat') return event.item.count-- event.player.giveInHand('minecraft:milk_bucket') event.target.playSound('minecraft:entity.cow.milk') }) ``` ```javascript onEvent('item.entity_interact', event => { if (event.target.type != 'minecraft:goat' || event.item.id != 'minecraft:bucket') return event.item.count-- event.player.giveInHand('minecraft:milk_bucket') event.target.playSound('minecraft:entity.cow.milk') }) ``` -------------------------------- ### Registering Fluids with onEvent Source: https://kubejs.com/wiki/tutorials/fluid-registry-legacy An alternative method using onEvent for fluid registration, functionally similar to StartupEvents. This example demonstrates creating fluids with custom properties and textures, including specific notes for 1.18.2. ```javascript onEvent('fluid.registry', event => { // Basic "thick" (looks like lava) fluid with red tint event.create('thick_fluid') .thickTexture(0xFF0000) .bucketColor(0xFF0000) .displayName('Thick Fluid') // Basic "thin" (looks like water) fluid with cyan tint, has no bucket and is not placeable event.create('thin_fluid') .thinTexture(0xFF0000) .bucketColor(0x00FFFF) .displayName('Thin Fluid') .noBucket() // 1.18.2 only .noBlock() // 1.18.2 only // Fluid with custom textures event.create('strawberry_cream') .displayName('Strawberry Cream') .stillTexture('kubejs:block/strawberry_still') .flowingTexture('kubejs:block/strawberry_flow') .bucketColor(0xFF33FF) // Fluid with a modified bucket item const tacoSauce = event .create('taco_sauce') .thickTexture(0xff0000) .bucketColor(0xff0000) tacoSauce.bucketItem.group('food') }) ``` -------------------------------- ### Adding Farmers Delight Cutting Recipes Source: https://kubejs.com/wiki/addons/farmers-delight Add custom cutting recipes in `server_scripts/`. This example shows how to cut cobblestone using a pickaxe, yielding stone and a chance for flint. ```javascript ServerEvents.recipes(event => { event.recipes.farmersdelight.cutting( 'minecraft:cobblestone', '#minecraft:pickaxes', // tool [ // results "minecraft:stone", ChanceResult.of("minecraft:flint", 0.75) ], // '' // sound ) event.recipes.farmersdelight.cooking( "meals", // recipe book tab - valid values: meals, drinks, misc ["minecraft:cobblestone"], "minecraft:stone", // output 30, // exp 10, // cookTime "minecraft:bowl" // container ) }) ``` -------------------------------- ### Register a Custom Beneficial Mob Effect Source: https://kubejs.com/wiki/tutorials/mob-effect-registry Use StartupEvents.registry to create a new beneficial mob effect. This example shows how to set its color, define its effect on entity tick, and modify attributes. ```javascript StartupEvents.registry('mob_effect', event => { event.create('custom_effect') // Create the effect under "kubejs:custom_effect" .color(0x000000) // Sets the color of the Effect's Particles. .beneficial() // Categorizes the Effect as Beneficial. .effectTick((entity, lvl) => { // This useful for reoccurring logic while the entity is under the effect. // Heal the entity once a second scaled by the effect's level, much like regeneration. if (entity.age % 20 != 0) return entity.heal(1 * lvl) }) // modifyAttribute is useful to scale an entity's attributes only lasting while under the effect .modifyAttribute('minecraft:generic.attack_damage', 'e0f4e796-3d3d-11ee-be56-0242ac183754',//Some random UUID which serves as the effect's unique instance 1, // The amount to increase/decrease by "multiply_base" // The operation to perform ) }) ``` -------------------------------- ### JavaScript Code Formatting Example Source: https://kubejs.com/wiki/contributing Demonstrates correct formatting for JavaScript code, including semicolon usage and array iteration. Note the specific case where a semicolon is required to prevent misinterpretation of subsequent code. ```javascript console.log('Hello, world!') // Here, a semicolon is needed in order for code to be not parsed as: // console.log('Hello, world!')['minecraft:stone', 'minecraft:cobblestone'].forEach(item => {}) ;['minecraft:stone', 'minecraft:cobblestone'].forEach(item => {}) ``` -------------------------------- ### Cancel chat message Source: https://kubejs.com/wiki/tutorials/chat Use PlayerEvents.chat to intercept and cancel messages. This example cancels messages starting with '!some_command' and replies to the player. ```javascript PlayerEvents.chat(event => { // Check if message starts with "!some_command" if (event.message.startsWith('!some_command')) { // Reply to the player and cancel the event event.player.tell('Hi!') event.cancel() } }) ``` ```javascript onEvent('player.chat', event => { // Check if message starts with "!some_command" if (event.message.startsWith('!some_command')) { // Reply to the player and cancel the event event.player.tell('Hi!') event.cancel() } }) ``` -------------------------------- ### Change Another Mod's Display Name Source: https://kubejs.com/wiki/tutorials/changing-mod-names You can also change the display names of other mods installed in your modpack. This example shows how to change the name of 'botania'. ```javascript Platform.mods.botania.name = 'Plant Tech Mod' ``` -------------------------------- ### removeEntriesCompletely Example Source: https://kubejs.com/wiki/events/RecipeViewerEvents/removeEntriesCompletely An example of how to use the RecipeViewerEvents.removeEntriesCompletely event to remove a specific recipe entry. ```APIDOC ## RecipeViewerEvents.removeEntriesCompletely ### Description This event is used to completely remove entries from the RecipeViewer. It takes a type and a callback function. ### Parameters #### Path Parameters - **type** (string) - Required - The type of recipe to remove (e.g., 'item', 'fluid'). #### Callback Function - **event** (object) - Required - An event object with methods to manipulate recipes. - **remove** (function) - Removes a specific recipe. - **recipeId** (string) - Required - The ID of the recipe to remove. ### Example ```javascript RecipeViewerEvents.removeEntriesCompletely('item', event => { event.remove('minecraft:stick') }); ``` ``` -------------------------------- ### Registering a Menu for Any Block Source: https://kubejs.com/wiki/addons/screenjs This snippet shows how to create a custom GUI that opens when interacting with a specific block. It requires setting up item handlers and input slots. ```javascript StartupEvents.registry('menu', event => { event.create('grass_block' /*name can be anything*/, 'block') /*default parameter set*/ .addItemHandler(9) // adds an item handler. .addItemHandler(1) .inputSlotIndices(0) .setBlock('minecraft:grass_block') // the block that should open this GUI on right-click }) ``` -------------------------------- ### Fluid Snippet Example Source: https://kubejs.com/wiki/addons/probejs Example of ProbeJS generating code snippets for fluids, facilitating autocompletion for fluid IDs. ```javascript event.recipes.kubejs.fluid_transposer("kubejs:fluid_transposer", "minecraft:water", "minecraft:lava", 1000); ``` -------------------------------- ### Register Items with Dynamic Tinting and Models Source: https://kubejs.com/wiki/tutorials/item-registry Use StartupEvents.registry('item', ...) to create new items. You can set textures, apply colors based on index or NBT data, and define custom models. ```javascript StartupEvents.registry('item', event => { // Old style with just setting color by index still works! event.create('old_color_by_index') .textureJson({ layer0: 'minecraft:item/paper', layer1: 'minecraft:item/ghast_tear' }) .color(0, '#70F00F') .color(1, '#00FFF0') event.create('cooler_sword', 'sword') .displayName('Test Cooler Sword') .texture('minecraft:item/iron_sword') /** * Example by storing the color in the nbt of the itemstack * You have to return -1 to apply no tint. * * You can test this through: /give @p kubejs:cooler_sword{color:"#ff0000"} */ .color(itemstack => itemstack.nbt && itemstack.nbt.color ? itemstack.nbt.color : -1) event.create('test_item') .displayName('Test Item') .textureJson({ layer0: 'minecraft:item/beef', layer1: 'minecraft:item/ghast_tear' }) /** * If you want to apply the color to a specific layer, you can use the tintIndex * tintIndex is the texture layer index from the model: layer0 -> 0, layer1 -> 1, etc. * U can use the `Color` wrapper for some default colors * * This example will apply the color to the ghast_tear texture. */ .color((itemstack, tintIndex) => tintIndex == 1 ? Color.BLUE : -1) // Set a texture for a specific layer event.create('test_sword', 'sword') .displayName('Test Sword') .texture('layer0', 'minecraft:item/bell') // Directly set your custom model json event.create('test_something') .displayName('Test something') .modelJson({ parent: 'minecraft:block/anvil' }) }) ``` -------------------------------- ### Create Rectangle using Command Alternative Source: https://kubejs.com/wiki/tutorials/painter-api Demonstrates the command-line alternative for creating a rectangle using the Painter API. ```bash /kubejs painter @p {example: {type: 'rectangle', x: 10, y: 10, w: 20, h: 20}} ``` -------------------------------- ### Update an Existing Rectangle with Painter API Source: https://kubejs.com/wiki/tutorials/painter-api Update an existing object by providing its ID and new properties. This example updates the 'example' rectangle's x-position. ```javascript event.player.paint({example: {x: 50}}) ``` -------------------------------- ### Create Deploying Recipes Source: https://kubejs.com/wiki/addons/create Defines deploying recipes using the Deployer. Requires exactly two inputs and supports chance-based outputs and keeping the held item. ```javascript ServerEvents.recipes(event => { event.recipes.create.deploying('minecraft:diamond', ['minecraft:coal_block', 'minecraft:sand']) event.recipes.create.deploying(['minecraft:diamond', 'minecraft:emerald'], ['minecraft:coal_block', 'minecraft:sand']).keepHeldItem() event.recipes.create.deploying(['minecraft:diamond', CreateItem.of('minecraft:diamond', 0.5)], ['minecraft:coal_block', 'minecraft:sand']) }) ``` ```javascript ServerEvents.recipes(event => { event.recipes.create.deploying('minecraft:diamond', ['minecraft:coal_block', 'minecraft:sand']) event.recipes.create.deploying(['minecraft:diamond', 'minecraft:emerald'], ['minecraft:coal_block', 'minecraft:sand']).keepHeldItem() event.recipes.create.deploying(['minecraft:diamond', Item.of('minecraft:diamond').withChance(0.5)], ['minecraft:coal_block', 'minecraft:sand']) }) ``` -------------------------------- ### Register Paxel Item (1.19.2+) Source: https://kubejs.com/wiki/addons/paxeljs Use StartupEvents.registry to register a new item with the 'paxel' tool type for versions 1.19.2 and above. Ensure this runs during the startup phase. ```javascript StartupEvents.registry('item', event => { event.create('cool_paxel', 'paxel') }) ``` -------------------------------- ### Build, Validate, and Add Recipes Source: https://kubejs.com/wiki/addons/applied-kjs Build recipe JSON first, validate it, and then add it to the game. ```APIDOC ### #Build JSON first, validate, then add You can also build recipe JSON first and inspect it before adding it: ``` ServerEvents.recipes(event => { const json = AE2Recipes.inscriberPress( 'minecraft:gold_ingot', 'ae2:logic_processor_press', 'ae2:printed_logic_processor' ) AE2Recipes.validateOrThrow(json) console.log('AE2 recipe JSON:', AE2Recipes.stringify(json)) AE2Recipes.add(event, json, 'kubejs:ae2/inscriber/printed_logic_processor') }) ``` ``` -------------------------------- ### Get Associated Block Source: https://kubejs.com/wiki/concepts/item-stack Retrieves the associated Block object if the ItemStack is a BlockItem, otherwise returns null. ```javascript item.block ``` -------------------------------- ### Get First Matching Item Source: https://kubejs.com/wiki/concepts/ingredient The .first property resolves the ingredient and returns the first item stack that matches it. ```javascript ingredient.first ``` -------------------------------- ### Apply Attributes to Entities (EntityJS) Source: https://kubejs.com/wiki/addons/irons-spells If EntityJS is installed, use `EntityJSEvents.attributes` for a more streamlined way to apply attributes to entities. ```javascript EntityJSEvents.attributes(event => { event.allTypes.forEach(type => { event.modify(type, (a) => { a.add('kubejs:test_spell_power') a.add('kubejs:test_spell_resistance') }) }) }) ``` -------------------------------- ### Create Item with Properties Source: https://kubejs.com/wiki/tutorials/item-registry Demonstrates creating an item with chained builder methods to set its maximum stack size and enable glowing. ```javascript // You can chain builder methods as much as you like event.create('test_item_2').maxStackSize(16).glow(true) ``` -------------------------------- ### Registering a Custom Command with ServerEvents.customCommand Source: https://kubejs.com/wiki/events/ServerEvents/basicCommand An alternative method to register commands using ServerEvents.customCommand. This example demonstrates healing the player. ```javascript ServerEvents.customCommand('heal', event => { // Will heal the player event.player.heal() }) ``` -------------------------------- ### FTBChunksEvents.after Source: https://kubejs.com/wiki/addons/ftb-xmod-compat Executes code after a chunk-related operation (claim, unclaim, load, unload). This example announces chunk claims to the server. ```javascript FTBChunksEvents.after("claim", (event) => { const chunkPos = event.chunk.pos.chunkPos const player = event.player.username event.server.tell( Component.aqua(player) .append(Component.literal(" has claimed Chunk at: ")) .append(Component.green(chunkPos)) ) }) ``` -------------------------------- ### FTBQuestsEvents.customTask Source: https://kubejs.com/wiki/addons/ftb-xmod-compat Adds custom logic to tasks in FTB Quests. This example progresses a quest every 20 seconds during a thunderstorm. ```javascript FTBQuestsEvents.customTask('custom_task_id', event => { event.maxProgress = 100 // Sets the Progress Count. event.setCheckTimer(20) // Checks for progress every 1 second (20 ticks). event.setCheck((task, player) => { if(player.level.thundering) { //Checks if it is Thundering at a player. task.progress++ // Adds progress to the quest. } }) }) ``` -------------------------------- ### Create Basic Item Source: https://kubejs.com/wiki/tutorials/item-registry Use this to create a basic item. The texture must be placed in kubejs/assets/kubejs/textures/item/test_item.png. Custom models can be created in Blockbench and placed in kubejs/assets/kubejs/models/item/test_item.json. ```javascript // Listen to item registry event StartupEvents.registry('item', event => { // The texture for this item has to be placed in kubejs/assets/kubejs/textures/item/test_item.png // If you want a custom item model, you can create one in Blockbench and put it in kubejs/assets/kubejs/models/item/test_item.json event.create('test_item') }) ``` -------------------------------- ### Dump Game Data with ProbeJS Source: https://kubejs.com/wiki/addons/probejs Run this command in-game to generate KubeJS typings. This is the first step to enabling Intellisense in VSCode. ```bash /probejs dump ``` -------------------------------- ### Add Campfire Cooking Recipe with XP and Time Source: https://kubejs.com/wiki/tutorials/recipes Use `event.campfireCooking()` for Campfire recipes. Specify output, input, XP, and cooking time in ticks (e.g., 600 ticks for 30 seconds). ```javascript event.campfireCooking('minecraft:torch', 'minecraft:stick', 0.35, 600) ``` -------------------------------- ### Create a Simple Ponder Scene Source: https://kubejs.com/wiki/addons/ponder-for-kubejs Demonstrates how to create a basic Ponder scene with a structure, idle time, entity creation, text display, and controls. Use for 1.18 with `onEvent("ponder.registry", event => { ... })`. ```javascript // for 1.18 pls use: onEvent("ponder.registry", event => { ... }) Ponder.registry((event) => { event.create("minecraft:paper").scene("our_first_scene", "First example scene", (scene, util) => { /** * Shows the whole structure. * Alternatively, `scene.showBasePlate()` can be used to show the base plate. * Useful for animating different parts of the structure. */ scene.showStructure(); /** * Encapsulate the structure bounds to given positions. This is useful if the custom structure has no proper bounds. * scene.showStructure() automatically encapsulates the bounds. */ // scene.encapsulateBounds(blockPos) /** * idle(ticks) or idleSeconds(seconds) is used to wait for a certain amount of time. * 20 ticks = 1 second */ scene.idle(10); /** * `.createEntity()` returns an entity link from Create which will be used * as reference in the future * [x, y, z] is the position but any KubeJS way to represent a position can be used. * * Don't modify the entity directly! */ const creeperLink = scene.world.createEntity("creeper", [2.5, 1, 2.5]); /** * 50 -> the tick length of the instruction * [x, y, z] -> the position that the text should point at */ scene .text(60, "Example text", [2, 2.5, 2.5]) /** * Optional | Sets the color of the text. * Possible values: * - PonderPalette.WHITE, PonderPalette.BLACK * - PonderPalette.RED, PonderPalette.GREEN, PonderPalette.BLUE * - PonderPalette.SLOW, PonderPalette.MEDIUM, PonderPalette.FAST * - PonderPalette.INPUT, PonderPalette.OUTPUT */ .colored(PonderPalette.RED) /** * Optional | Places the text closer to the target position. */ .placeNearTarget() /** * Optional | Adds a keyframe to the scene. */ .attachKeyFrame(); /** * 120 -> the tick length of the instruction * [x, y, z] -> the position that the controls should point at * "down" -> the direction that is used by the controls for pointing */ scene .showControls(60, [2.5, 3, 2.5], "down") /** * Uses mouse right click as icon. * Alternatively, `.leftClick()` can be used * or `.showing(icon)` for a custom icon. */ .rightClick() // Defines the item that should be shown with the icon. .withItem("shears") /** * Optional | Defines that controls are only shown when sneaking. * `.whileSneaking()` and `.withCTRL()` can not be used simultaneously. */ .whileSneaking() /** * Optional | Defines that controls are only shown when holding CTRL. * `.whileSneaking()` and `.withCTRL()` can not be used simultaneously. */ .whileCTRL(); }); }); ``` -------------------------------- ### Disable Dropping Cobblestone Source: https://kubejs.com/wiki/tutorials/item-interactions The dropped event allows you to cancel the dropping of specific items. This example disables dropping cobblestone and is applicable to 1.19.2+ and 1.18.2 and below. ```javascript ItemEvents.dropped('minecraft:cobblestone', e => e.cancel()) ``` -------------------------------- ### Change Creative Tab Icon and Display Name Source: https://kubejs.com/wiki/tutorials/creative-tabs Modify the icon and display name of an existing creative tab. This example targets the 'functional_blocks' tab. ```javascript StartupEvents.modifyCreativeTab('minecraft:functional_blocks', event => { // Change tab icon event.icon = 'kubejs:example_block' // Change display name. Technically supports formatting, but it's not recommended event.displayName = Text.darkRed('Functional Blocks!') }) ``` -------------------------------- ### Register World Transmutations with ProjectE Source: https://kubejs.com/wiki/addons/projecte Define world transmutation recipes using `ProjectEEvents.registerWorldTransmutations` in startup scripts. This allows specific blocks to transform into others when transmuted. ```javascript ProjectEEvents.registerWorldTransmutations(event => { event.transform('minecraft:tnt', 'minecraft:oak_planks') }) ``` -------------------------------- ### Registering a Basic Command with ServerEvents.basicCommand Source: https://kubejs.com/wiki/events/ServerEvents/basicCommand Use ServerEvents.basicCommand to register a new command. The 'icons' command takes player input and displays text icons. Requires KubeJS version 1.21+ for event.input. ```javascript ServerEvents.basicCommand('icons', event => { // Will print KubeJS icons from their characters, try `/icons BCDEFIJKNTWY` event.server.tell(TextIcons.icon(event.input)) }) ``` ```javascript ServerEvents.basicCommand('heal', event => { // Will heal the player event.player.heal() }) ``` -------------------------------- ### Prevent Recipe Auto-Generation (Manual Only) Source: https://kubejs.com/wiki/addons/create Prevents automatic recipe generation for a specific recipe by appending '_manual_only' to its ID. This example shows it for a shapeless recipe. ```javascript ServerEvents.recipes(event => { event.shapeless('minecraft:wet_sponge', ['minecraft:water_bucket', 'minecraft:sponge']).id('kubejs:moisting_the_sponge_manual_only') }) ``` -------------------------------- ### Listen for Server Recipe Events (KubeJS) Source: https://kubejs.com/wiki/tutorials/recipes Register a callback function to the `ServerEvents.recipes` event to modify recipes. This code should be placed in your `server_scripts/` folder. The callback function receives an `event` object that allows recipe manipulation. ```javascript /* * ServerEvents.recipes(callback) is a function that accepts another function, * called the "callback", as a parameter. The callback gets run when the * server is working on recipes, and then we can make our own changes. * When the callback runs, it is also known as the event "firing". */ // Listen for the "recipes" server event. ServerEvents.recipes(event => { // You can replace `event` with any name you like, as // long as you change it inside the callback too! // This part, inside the curly braces, is the callback. // You can modify as many recipes as you like in here, // without needing to use ServerEvents.recipes() again. console.log('Hello! The recipe event has fired!') }) ``` -------------------------------- ### Add a Smithing Recipe (2 Inputs) Source: https://kubejs.com/wiki/tutorials/recipes Adds a smithing recipe using `event.smithing()` for versions requiring only two input arguments: the output item and the item to be upgraded, along with the upgrade item. ```javascript event.smithing( 'minecraft:netherite_ingot', 'minecraft:iron_ingot', // arg 2: the item to be upgraded 'minecraft:black_dye' // arg 3: the upgrade item ) ``` -------------------------------- ### Add Custom FarmersDelight Cutting Recipe Source: https://kubejs.com/wiki/tutorials/recipes Use `event.custom()` with a JSON object to define modded recipes. This example adds a recipe for slicing cake on a cutting board. ```javascript event.custom({ type: 'farmersdelight:cutting', ingredients: [ { item: 'minecraft:cake' } ], tool: { tag: 'forge:tools/knives' }, result: [ { item: 'farmersdelight:cake_slice', count: 7 } ] }) ``` -------------------------------- ### Create a New Creative Tab Source: https://kubejs.com/wiki/tutorials/creative-tabs Register a new creative tab with a custom icon and content. This example creates a 'dirt' tab containing various dirt-related blocks. ```javascript StartupEvents.registry('creative_mode_tab', event => { event.create('dirt').icon(() => 'minecraft:dirt').content(() => [ 'minecraft:dirt', 'minecraft:grass_block', 'minecraft:podzol', 'minecraft:coarse_dirt', 'minecraft:rooted_dirt' ]) }) ``` -------------------------------- ### Create Filling Recipe Source: https://kubejs.com/wiki/addons/create Defines a filling recipe using the Spout. Requires an item and a fluid as inputs, and an item as output. ```javascript ServerEvents.recipes(event => { event.recipes.create.filling('minecraft:water_bucket', [Fluid.of('minecraft:water'), 'minecraft:bucket']) }) ``` -------------------------------- ### Registering Custom Recipe Subtypes Source: https://kubejs.com/wiki/events/RecipeViewerEvents/registerSubtypes Use this event to define custom components that should differentiate recipe entries. For example, items with different 'custom_data' can be treated as distinct entries. ```javascript RecipeViewerEvents.registerSubtypes('item', event => { // Stone swords with different 'custom_data' components are now considered different entries event.useComponents('minecraft:stone_sword', 'custom_data') }) ```