Repository navigation
1.20.1 KubeJS
Version: This guide applies to KubeJS 6 (Minecraft 1.20.1 Forge).
Rat Worker integrates with KubeJS (optional). Server scripts get three events, a RatWorker binding, and can define whole new tasks with no Java.
General rules:
- Task ids without a namespace get
kubejs:increate(...). In binding calls a bare id is tried asratworker:first, thenkubejs:. - Script tasks are cleared and rebuilt on every
/reload. - Rhino: use
let(notconst) inside loops; compare levels by dimension, not with.equals; read Java lists withsize()andget(i).
WorkerEvents.<name>(event => { ... }) in kubejs/server_scripts/.
| Event | Fields and methods |
|---|---|
registerTasks |
create(id) returns a task builder (below) |
gainXp |
worker, task (id of the running task), amount (writable); cancel() gives no XP |
learn |
worker, task, player; cancel() refuses the manual (it is not used up) |
manuals |
add(item, task, xp), add(item, task): any item teaches a task; xp 0 = free, -1 = the task's learnXp
|
-
gainXpfires for every whole XP point a worker earns from work. -
learnfires when a player uses a training manual and the worker has the XP, before anything is spent.
WorkerEvents.registerTasks(event => {
event.create('chop') // id kubejs:chop
.title('Chop wood')
.icon('minecraft:iron_axe')
.onTick(ctx => { /* ... */ })
})| Method | Meaning |
|---|---|
title(text), description(text)
|
Shown in the command screen. Without them the lang keys task.<ns>.<id> and .desc are used. |
icon(item) |
Icon in the task list. |
cost(food, water) |
Drain multipliers while running. |
range(n), speed(n)
|
Task radius, walking speed multiplier. |
learnXp(n), xpRate(n)
|
XP needed with a manual, XP gain multiplier. |
number(key, value) |
Any extra number, read with ctx.number(key), overridable from a datapack. |
innate(true) |
Known by every worker, no manual needed. |
idle(true) |
Drains at the idle rate and gives no XP (like Hold position). |
requires(ingredient) |
The worker must hold or carry a matching item to start. |
speedBranch(true) |
Adds the Speed upgrade to this task. |
stage(name) |
Stage name for STAGES unlock mode. |
canStart(ctx => ...) |
Return a text to refuse the start (shown as the reason), nothing to allow it. |
onStart(ctx => ...), onTick(ctx => ...), onStop(ctx => ...)
|
Lifecycle. onTick runs every few ticks while the task runs; never loop over large areas in one call. |
A manual for a script task: RatWorker.tome('chop') or ratworker:tome{Task:"kubejs:chop"}.
| Member | Result |
|---|---|
worker, level, owner
|
the worker entity, its level, the online owner (or null) |
state |
NBT saved with the worker; keep your task's data here |
inventory |
the worker's 27-slot inventory |
hunger, thirst, ticks, cooldownFactor
|
meters, ticks run, 1 or more when hungry/thirsty |
number(key) |
task number (default, datapack, config) |
branch('speed') |
level of a branch for this task (hunger, thirst, speed, health, strength) |
cooldown(key, ticks) |
true once per period, scaled by cooldownFactor and the speed branch |
moveTo(pos[, distance]) |
'arrived', 'moving' or 'failed' (stuck or no path several times) |
stopTask(reason), setStatus(text)
|
stop with a reason; status line in the command screen |
holdUse(pos), holdAttack(pos), holdSneak()
|
start holding right-click / left-click (mining) / sneak |
press('use' or 'attack', pos) |
one click |
release(action), releaseAll(), isHeld(action)
|
input state; everything is released when the task stops |
useItemOn(pos) |
right-click a block with the main-hand item |
useItemOn(pos, slot) |
right-click a block with the item of an inventory slot |
breakBlock(pos) |
break a block now with the main-hand tool |
pickupItems(radius) |
pick up dropped items into the inventory |
attackNearest('#entity_type_tag', radius) |
walk to and hit the nearest matching entity (never players) |
deposit(stack), takeFromSupply(ingredient, count)
|
supply container access |
All inputs act as a player would, with the owner's rights: targets must be within 4.5 blocks, players are never targeted, and containers other than the linked supply cannot be opened.
| Call | Result |
|---|---|
config.get(key) |
server config value, read-only; preset keys return the resolved value |
spawn(level, pos, player, name, skin) |
new worker owned by the player (limits ignored); skin may be null |
isWorker(entity) |
true for a worker |
getXp(w), setXp(w, n), addXp(w, n)
|
worker XP |
knows(w, task), learn(w, task), forget(w, task)
|
learned tasks |
getNode(w, node), setNode(w, node, level)
|
upgrade levels: health, strength, <task>#hunger, <task>#thirst, <task>#speed
|
tome(task), tome(task, xp)
|
the built-in manual for the task (with its own XP cost) |
startTask(w, task) |
'' on success, else the reason |
stopTask(w), currentTask(w)
|
stop; id of the running task ('' if none) |
setNeeds(w, food, water) |
set both meters |
purity(stack), drinkThirst(stack)
|
drink purity (-1 not a drink, 0 to 2) and water value |
unlock(player, taskOrStage) |
STAGES mode unlock record |
message(w, text) |
chat message to the owner |
A crank rewritten with holdUse, a wood-chopping task, and progression hooks. Everything is switched off with ENABLED = false. Save in kubejs/server_scripts/:
let ENABLED = false
WorkerEvents.registerTasks(event => {
if (!ENABLED) return
// Same job as the built-in crank, written in KubeJS.
event.create('crank_js')
.title('Turn crank (script)')
.icon('create:hand_crank')
.cost(1.5, 1.5)
.learnXp(30)
.speedBranch(true)
.onStart(ctx => {
let found = null
let best = 1e9
let origin = ctx.worker.blockPosition()
BlockPos.betweenClosed(origin.offset(-8, -3, -8), origin.offset(8, 3, 8)).forEach(p => {
if (ctx.level.getBlock(p).id == 'create:hand_crank') {
let d = p.distSqr(origin)
if (d < best) { best = d; found = p.immutable() }
}
})
if (found == null) { ctx.stopTask('No hand crank nearby'); return }
ctx.state.putLong('Crank', found.asLong())
})
.onTick(ctx => {
if (!ctx.state.contains('Crank')) return
let pos = BlockPos.of(ctx.state.getLong('Crank'))
if (ctx.level.getBlock(pos).id != 'create:hand_crank') { ctx.stopTask('The crank is gone'); return }
if (ctx.worker.getEyePosition().distanceTo(pos.getCenter()) > 3) {
ctx.release('use')
if (ctx.moveTo(pos, 1.8) == 'failed') ctx.stopTask('Cannot reach the crank')
return
}
ctx.holdUse(pos)
ctx.setStatus('Turning the crank')
})
// Chop logs nearby with an axe the worker carries.
event.create('chop')
.title('Chop wood')
.icon('minecraft:iron_axe')
.requires('#minecraft:axes')
.cost(1.2, 1.0)
.learnXp(40)
.onTick(ctx => {
if (!ctx.cooldown('swing', 30)) return
let origin = ctx.worker.blockPosition()
let log = null
BlockPos.betweenClosed(origin.offset(-8, 0, -8), origin.offset(8, 6, 8)).forEach(p => {
if (log == null && ctx.level.getBlock(p).hasTag('minecraft:logs')) log = p.immutable()
})
if (log == null) { ctx.setStatus('No trees left'); return }
if (ctx.moveTo(log, 2.5) != 'arrived') return
ctx.breakBlock(log)
ctx.pickupItems(4)
})
})
// Double XP while turning a crank.
WorkerEvents.gainXp(event => {
if (!ENABLED) return
if (event.task == 'ratworker:crank') event.amount = event.amount * 2
})
// The farm manual only works after a story stage.
WorkerEvents.learn(event => {
if (!ENABLED) return
if (event.task == 'ratworker:farm' && !event.player.stages.has('my_pack_greenhouse')) {
event.player.tell('The greenhouse is not running yet.')
event.cancel()
}
})
// A story worker with a fixed name and some training, from a chat trigger.
PlayerEvents.chat(event => {
if (!ENABLED) return
if (event.message == 'call nick') {
let nick = RatWorker.spawn(event.player.level, event.player.blockPosition(), event.player, 'Nick', null)
if (nick != null) {
RatWorker.learn(nick, 'crank')
RatWorker.setNode(nick, 'ratworker:crank#speed', 2)
event.player.give(RatWorker.tome('farm'))
}
}
})A manual is any item you map to a task. Create the item in a startup script and map it in a server script:
// startup_scripts
StartupEvents.registry('item', event => {
event.create('mypack:manual_crank').maxStackSize(1) // texture: kubejs/assets/mypack/textures/item/manual_crank.png
})// server_scripts
WorkerEvents.manuals(event => {
event.add('mypack:manual_crank', 'ratworker:crank', 0) // free to learn
})
ServerEvents.recipes(event => {
event.shapeless('mypack:manual_crank', ['minecraft:book', 'create:hand_crank'])
})ServerEvents.recipes(event => {
event.remove({ id: 'ratworker:tome_farm' })
event.shapeless(Item.of('ratworker:tome', '{Task:"ratworker:farm"}'),
['minecraft:book', 'minecraft:iron_hoe', 'minecraft:bone_meal', 'minecraft:water_bucket'])
})Rat Worker is released under the MIT license. Author: Stefano Manca.
Guides & Reference
Scripting & Mod API
Version Overviews