Skip to content

Instantly share code, notes, and snippets.

@LatvianModder
Last active April 20, 2024 23:50
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LatvianModder/9f5f8cb4121fda4141dbd2cfd5b3d5c9 to your computer and use it in GitHub Desktop.
Save LatvianModder/9f5f8cb4121fda4141dbd2cfd5b3d5c9 to your computer and use it in GitHub Desktop.
KubeJS Scripts
// This is not actually executable code.
// This just shows that there are different ways to write things,
// you chose whichever looks best/fits better your needs.
// Note: 'data' is only available in 1.12.2 and represents item metadata or damage
// Items
// If string is used, it parses it as /give would.
'minecraft:stone_sword' // Stone Sword
'minecraft:stone_sword 1 10' // Stone Sword with damage 10
'minecraft:apple 30' // 30 Apples
'minecraft:compass {display:{Name:\"Spawn\"}}' // Compass with display name 'Spawn'
// If {} object is used, item key is required. Optional keys are data, count, nbt, caps.
{item: 'minecraft:stone_sword'}
{item: 'minecraft:stone_sword', data: 10}
{item: 'minecraft:apple', count: 30}
{item: 'minecraft:compass', nbt: {display: {Name: 'Spawn'}}}
// If item.of() is used, any of previous methods will work within () but you can also change values with functions. Sometimes this is shorter.
item.of('minecraft:stone_sword')
item.of('minecraft:stone_sword').data(10)
item.of('minecraft:apple').count(30)
item.of('minecraft:compass').name('Spawn')
item.of('minecraft:compass').name('Spawn').count(30) // You can chain functions in any order. See Item Stack docuemntation for full list of functions.
// Fluids
'water' // Water
'water 500' // 500 mB of Water
// If {} object is used, fluid key is required. Optional keys are amount and nbt.
{fluid: 'water'}
{fluid: 'water', amount: 500}
// This script adds new block and explains how to add model and name for it
// Listen to block registry event
events.listen('block.registry', function (event) {
// Register new block, test_block with glass material and hardness 0.5
event.create('test_block').material(block.material.glass).hardness(0.5).add()
})
// Listen to item registry event
events.listen('item.registry', function (event) {
// Register item for test_block (not required, but recommended. Only some vanilla blocks don't have item form, like portal block)
event.createBlockItem('test_block').add()
})
// Listen to Crafting Table recipe event
events.listen('recipes.crafting_table', function (event) {
// Add shapeless recipe for test_block
event.addShapeless('test_block', [ 'minecraft:stone', 'minecraft:dirt' ])
})
/*
Create kubejs/resources/lang/en_us.lang file and add:
tile.kubejs.test_block.name=Test Block
Place block texture in kubejs/resources/textures/blocks/test_block.png
Blocks need model and state mapping files for texture to work, just like vanilla.
State mapping file: kubejs/resources/blockstates/test_block.json
{
"variants": {
"normal": [{"model": "kubejs:test_block"}]
}
}
Block model file: kubejs/resources/models/block/test_block.json
{
"parent": "block/cube_all",
"textures": {
"all": "kubejs:blocks/test_block"
}
}
*/
// This script changes a java variable in ProjectE mod by accessing code directly
// Listen to post-init event, after all mods have loaded
events.listen('postinit', function (event) {
// Loads Java class field
var devEnvField = utils.field('moze_intel.projecte.PECore', 'DEV_ENVIRONMENT')
// Changes public static boolean DEV_ENVIRONMENT of PECore class to false
devEnvField.staticSet(false)
})
// This script removes all items from world every 30 minutes
// Create item whitelist filter that won't be deleted with clearlag
var whitelist = ingredient.matchAny([
'minecraft:diamond', // Adds diamond to whitelist
'minecraft:gold_ingot',
ingredient.mod('tinkersconstruct'), // Adds all items from tinkerscontruct to whitelist
'minecraft:emerald'
])
// Create variable for last clearlag result
var lastClearLagResult = utils.newList()
// Create variable for total number of items
var lastTotalClearLagResult = utils.newCountingMap()
// Create new function that clears lag
function clearLag (server) {
// Get a list of all entities on server with filter that only returns items
var itemList = server.getEntities('@e[type=item]')
// Create new local map for item counters
var lastResult = utils.newCountingMap()
// Clear old result lists
lastClearLagResult.clear()
lastTotalClearLagResult.clear()
// Iterate over each entity in itemList and add item counters
itemList.forEach(function (entity) {
if (!whitelist.test(entity.item)) {
// Get the name of item
var key = entity.item.name
// Add to entity count
lastResult.add(key, 1)
// Add to total item count
lastTotalClearLagResult.add(key, entity.item.count)
// Kill the item entity
entity.kill()
}
})
// Update and sort last result list
lastClearLagResult.addAll(lastResult.entries)
lastClearLagResult.sort(null)
// Tell everyone how many items will be removed
server.tell([
text.lightPurple('[ClearLag]'),
' Removed ',
lastTotalClearLagResult.totalCount,
' items. ',
text.yellow('Click here').click('command:/clearlagresults'),
' for results.'
])
}
// Listen for server load event
events.listen('server.load', function (event) {
// Log message in console
event.server.tell([ text.lightPurple('[ClearLag]'), ' Timer started, clearing lag in 30 minutes!' ])
// Schedule new task in 30 minutes
event.server.schedule(MINUTE * 30, event.server, function (callback) {
// Tell everyone on server that items will be removed
callback.data.tell([ text.lightPurple('[ClearLag]'), ' Removing all items on ground in one minute!' ])
// Schedule a subtask that will clear items in one minute
callback.data.schedule(MINUTE, callback.data, function (callback2) {
clearLag(callback2.data)
})
// Re-schedule this task for another 30 minutes (endless loop)
callback.reschedule()
})
})
// Register commands
events.listen('command.registry', function (event) {
// Register new OP command /clearlag, that instantly runs clearlag
event
.create('clearlag')
.op()
.execute(function (sender, args) {
clearLag(sender.server)
})
.add()
// Register new non-OP command /clearlagresults, that displays stats of all removed items from previous /clearlag
event
.create('clearlagresults')
.execute(function (sender, args) {
sender.tell([ text.lightPurple('[ClearLag]'), ' Last clearlag results:' ])
lastClearLagResult.forEach(function (entry) {
var total = lastTotalClearLagResult.get(entry.key)
if (entry.value == total) {
sender.tell([ text.gold(entry.key), ': ', text.red(entry.value) ])
} else {
sender.tell([ text.gold(entry.key), ': ', text.red(entry.value), ' entities, ', text.red(total), ' total' ])
}
})
})
.add()
})
// This script is peak of human evolution. Whenever someone says "Creeper" in chat, it replies with "Aw man"
// Listen to chat event
events.listen('player.chat', function (event) {
// Check if message equals creeper, ignoring case
if (event.message.trim().equalsIgnoreCase('creeper')) {
// Schedule task in 1 tick, because if you reply immidiently, it will print before player's message
event.server.scheduleInTicks(1, event.server, function (callback) {
// Tell everyone Aw man, colored green. Callback data is the server
callback.data.tell(text.green('Aw man'))
})
}
})
// With this script you can have FTB Utilities roles that change over time
events.listen('player.tick', function (event) {
// This check happens every 20 ticks, a.k.a every second
if (event.player.server && event.player.ticksExisted % 20 === 0) {
var rank = event.player.data.ftbutilities.rank
events.post('test_event', {testValue: rank.id})
var newRank = ftbutilities.getRank(rank.getPermission('promotion.next'))
if (newRank) {
var timePlayed = event.player.stats.get('stat.playOneMinute') / 20 // Seconds player has been on server
var timeRequired = newRank.getPermissionValue('promotion.timer').getInt()
if (timeRequired > 0 && timePlayed >= timeRequired && rank.addParent(newRank)) {
if (!events.postCancellable('ftbutilities.rank.promoted.' + newRank.id, {'player': event.player, 'rank': newRank})) {
event.player.tell('You have been promoted to ' + newRank.getPermission('promotion.name') + '!')
}
ftbutilities.saveRanks()
}
}
}
})
// When player gets promoted to 'trusted' rank, give them gold ingot
events.listen('ftbutilities.rank.promoted.trusted', function (event) {
// event.data.player.give('minecraft:gold_ingot')
})
/*
3 example roles in ranks.txt:
// ----- //
[player]
power: 1
default_player_rank: true
promotion.name: Player
promotion.next: newcomer
promotion.timer: 5
command.ftbutilities.rtp: false
command.ftbutilities.home: false
[newcomer]
power: 5
promotion.name: Newcomer
promotion.next: regular
promotion.timer: 15
ftbutilities.chat.name_format: <&aNewcomer &r{name}>
command.ftbutilities.rtp: true
[regular]
power: 10
promotion.name: Regular
promotion.next: trusted
promotion.timer: 30
ftbutilities.chat.name_format: <&9Regular &r{name}>
command.ftbutilities.home: true
// ----- //
After 5 seconds of play time, player will be promoted to newcomer.
After 15 seconds (or 10 since previous role) they will be promoted to regular.
After 30 seconds (or 15 since previous role) they will be promoted to trusted, etc.
*/
// This script adds new item and explains how to add model and name for it
// Listen to item registry event
events.listen('item.registry', function (event) {
// Register new item, test_item. It has enchanted item glow
event.create('test_item').glow(true).add()
})
// Listen to Crafting Table recipe event
events.listen('recipes.crafting_table', function (event) {
// Add shaped recipe for test_item, made out of 4 apples in 2x2 square
event.addShaped('test_item', ['AA', 'AA'], {
A: 'minecraft:apple'
})
})
/*
Create kubejs/resources/lang/en_us.lang file and add:
item.kubejs.test_item.name=Test Item
Place item texture in kubejs/resources/textures/items/test_item.png
Items need model file for texture to work, just like vanilla.
Item model file: kubejs/resources/models/item/test_item.json
{
"parent": "item/generated",
"textures": {
"layer0": "kubejs:items/test_item"
}
}
*/
// This script shows how to use network packets
// Listen to a player event, in this case item right-click
events.listen('item.right_click', function (event) {
// Check if item was right-clicked on client or server side
if (event.player.isServer()) {
// Send data {test: 123} to channel "test_channel_1". Channel ID can be any string, but it's recommended to keep it to snake_case [a-z_0-9].
// Receiving side will either be client (because its fired from server).
event.player.sendData('test_channel_1', {
test: 123
})
} else {
// It's not required to use a different channel ID, but it's recommended.
// Receiving side will either be server (because its fired from client).
event.player.sendData('test_channel_2', {
test: 456
})
}
})
// Listen to event that gets fired when network packet is received from server.
events.listen('player.data_from_server.test_channel_1', function (event) {
log.info(event.data.get('test').asInt()) // Prints 123
})
// Listen to event that gets fired when network packet is received from client.
events.listen('player.data_from_client.test_channel_2', function (event) {
log.info(event.data.get('test').asInt()) // Prints 456
})
// This script adds items on first time player joins, checking gamestages
// Listen to player login event
events.listen('player.logged_in', function (event) {
// Check if player doesn't have "starting_items" gamestage yet
if (!event.hasGameStage('starting_items')) {
// Add the gamestage
event.addGameStage('starting_items')
// Give some items to player
event.player.give('minecraft:stone_sword')
event.player.give({ item: 'minecraft:stone_pickaxe', data: 10 })
event.player.give({ item: 'minecraft:apple', count: 30 })
}
})
@Donaldino7712
Copy link

please don't post your example scripts here, instead post them at https://discord.com/channels/303440391124942858/1048591172165189632 instead

@liopyu
Copy link

liopyu commented Aug 6, 2023

My bad, i read this and for some reason thought it was another place to post example scripts, not sure how i missed it was to explain variants. Donald savin the day yet again!

@maxmaxmax01
Copy link

please don't post your example scripts here, instead post them at https://discord.com/channels/303440391124942858/1048591172165189632 instead

discord link expired

@liopyu
Copy link

liopyu commented Feb 8, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment