Developer docs

Cookbook: combat and slayer

A plugin that fights NPCs: picks a target, attacks, eats, prays, loots, and (for slayer) gets a task, travels to it and banks for supplies. Read PrivBot plugin concepts first.

Node layout

Node Priority shouldExecute (read-only) execute calls
ReconnectGraceNode (optional) RECOVERY_MAX (250) Session setup pending after a reconnect session.setupStep(ctx)
DeathRecoveryNode RECOVERY_MIN (240) runState.deathRecoveryActive or polled HP is 0 recovery.step(ctx)
EscapeNode (dangerous areas) HAZARD_PRIMARY (200) A threat is present (attacker player, HP floor) safety.escapeStep(ctx)
TravelNode MOVEMENT (150) Not at the task area, and not (needsFood && canEat) navigation.step(ctx)
EatFoodNode HAZARD_SECONDARY_HIGH (95) HP below threshold and food carried supplies.eat(ctx)
RestorePrayerNode HAZARD_SECONDARY_MEDIUM (90) Prayer points low and a restore carried supplies.restore(ctx)
ProtectionPrayerNode HAZARD_SECONDARY_LOW (80) In the fight area and the wanted overhead is not showing fighting.protect(ctx)
EquipGearNode COMBAT_GEAR (70) A gear piece is carried but not worn supplies.equipStep(ctx)
LootNode COMBAT_LOOT (65) Not in combat and wanted loot in range loot.pickup(ctx)
AttackNode COMBAT_ATTACK (60) Not in combat and a live target in range fighting.attack(ctx)
BankRestockNode PREP_HIGH (35) Out of food or supplies banking.step(ctx) (see Cookbook: banking loop)
AcquireTaskNode (slayer) LOBBY_HIGH (25) No task, or the task is done tasks.acquireStep(ctx)

Notes:

  • MOVEMENT (150) outranks eating (95). The travel node therefore yields in its own gate: && !(ctx.supplies.needsFood(ctx) && ctx.supplies.canEat(ctx)). Do the same for any higher node that must not starve a lower one.
  • HAZARD_SECONDARY_LOW and COMBAT_SPECIAL are both 80. If you add a special-attack node, give it a distinct value (for example TaskPriorityBands.COMBAT_SPECIAL - 1) and comment why.

Services to write

Service Owns
fighting Target names, selection (read-only), attack + engagement proof, protection prayer, failure count
supplies Food, prayer restores, gear: thresholds, item choice from snapshots, consume/equip proof
loot Loot policy (what, capacity), pickup proof, back-off
navigation One NavigationSession per journey; cancel on Stop, death and disconnect
tasks (slayer) Getting a task from the master, reading the task text, the kill count
banking One bank operation per execute; see Cookbook: banking loop

Each has status() and reset(). MyTaskContext.resetEncounter() resets the encounter services on Start, Stop, death and disconnect.

Recipe: select and attack with engagement proof

public final class CombatService {
    private static final int ENGAGE_TIMEOUT_MS = 3_000;
    private static final int MAX_FAILED_ATTACKS = 3;
    private volatile int failedAttacks;
    private volatile String status = "";

    /** Selection (client thread): read-only. */
    public boolean canAttack(MyTaskContext ctx) {
        return !ctx.combat.isInCombat() && nearestTarget(ctx) != null;
    }

    /** Worker: re-acquire, dispatch once, prove the fight started. */
    public boolean attack(MyTaskContext ctx) {
        long epoch = ctx.runState.sessionEpoch;
        PrivNPC target = ctx.read(() -> nearestTarget(ctx));
        if (target == null) {
            status = "No target in range";
            return false;
        }
        if (!target.attack()) {
            return recordFailure("Attack on " + target.getName() + " was not accepted");
        }
        if (!ctx.sleepUntil(() -> ctx.shouldAbort(epoch) || ctx.combat.isInCombat(), ENGAGE_TIMEOUT_MS)) {
            return recordFailure("Attack on " + target.getName() + " did not start a fight");
        }
        failedAttacks = 0;
        status = "Fighting " + target.getName();
        return true;
    }

    private PrivNPC nearestTarget(MyTaskContext ctx) {
        String[] names = ctx.config.targetNames().split("\\s*,\\s*");
        return ctx.npcs.query().withName(names).alive().withinTiles(ctx.config.range()).nearest();
    }

    private boolean recordFailure(String reason) {
        status = ++failedAttacks >= MAX_FAILED_ATTACKS ? reason + " (check the target name)" : reason;
        return false;
    }

    public String status() { return status; }
    public void reset() { failedAttacks = 0; status = ""; }
}

ctx.combat.targeting() returns the shared combat engine (target lock, selectTarget(profile, predicate)) when you need more than nearest-by-name. NPC identity across ticks is always (getId(), getIndex()).

Recipe: protection prayer confirmed by the overhead

public boolean protect(MyTaskContext ctx, String prayerName) {
    long epoch = ctx.runState.sessionEpoch;
    Boolean showing = ctx.user.overheadProtection().shows(prayerName);
    if (showing == null) {
        status = "Overhead unreadable";          // cannot tell: never toggle blind
        return false;
    }
    if (showing) {
        return false;
    }
    if (!ctx.prayer.activate(prayerName)) {
        status = prayerName + " was not accepted";
        return false;
    }
    boolean on = ctx.sleepUntil(() -> ctx.shouldAbort(epoch)
            || Boolean.TRUE.equals(ctx.user.overheadProtection().shows(prayerName)), 1_200);
    status = on ? prayerName + " on" : prayerName + " did not show";
    return on;
}
// Called as: ctx.fighting.protect(ctx, "Protect from Melee")

Name the prayer as the game does ("Protect from Melee"); the facades resolve the button. ctx.prayer.isActive(name) reads false when it cannot read, so it is not a safe gate for a toggle. Check ctx.prayer.mountedBook() before choosing a normal-book or curse prayer; Prayer.Book.UNKNOWN means "cannot tell".

Recipe: loot with a policy

public boolean hasLoot(MyTaskContext ctx) {          // selection
    return System.currentTimeMillis() >= backoffUntilMillis
            && ctx.groundItems.configuredDrop(policy(ctx), ctx.config.lootRange()) != null;
}

public boolean pickup(MyTaskContext ctx) {           // worker
    long epoch = ctx.runState.sessionEpoch;
    ItemContainerSnapshot before = ctx.inventory.snapshot();
    if (!before.available) {
        status = "Inventory unreadable";
        return false;
    }
    LootDrop taken =
            ctx.groundItems.takeConfiguredDrop(policy(ctx), ctx.config.lootRange());
    if (taken == null) {
        status = "Loot gone";
        return false;
    }
    int held = before.count(taken.itemId());
    boolean landed = ctx.sleepUntil(() -> {
        ItemContainerSnapshot now = ctx.inventory.snapshot();
        return ctx.shouldAbort(epoch) || (now.available && now.count(taken.itemId()) > held);
    }, 3_000);
    if (!landed) {
        backoffUntilMillis = System.currentTimeMillis() + 1_500;   // back off, do not blacklist
        status = "Pickup of " + taken.name() + " did not land";
    }
    return landed;
}

/** Runs on the client thread inside the scan: reads config and the scoped snapshot only. */
Predicate<LootDrop> policy(MyTaskContext ctx) {
    return drop -> {
        if (!wanted(ctx, drop.name())) {
            return false;
        }
        ItemContainerSnapshot carried = ctx.inventory.snapshot();
        return carried.available
                && (carried.freeSlots(28) > 0 || (drop.stackable() && carried.count(drop.itemId()) > 0));
    };
}

LootDrop is privbot.hooks.LootDrop (itemId(), name(), location(), quantity(), stackable()). It describes the stack as the scan saw it. The policy runs at scan and again at dispatch, and a non-null result from takeConfiguredDrop means the Take was sent, not that the item arrived.

Recipe: get a slayer task from a dialogue

public boolean acquireStep(MyTaskContext ctx) {
    long epoch = ctx.runState.sessionEpoch;
    String before = ctx.dialogue.getText();
    if (!ctx.npcs.interact(ctx.config.masterName(), ctx.config.assignmentOption())) {
        return fail("Talking to " + ctx.config.masterName() + " was not accepted");
    }
    // Proof: a NEW dialogue surface that names a task. Not "a dialogue is visible".
    boolean shown = ctx.sleepUntil(() -> ctx.shouldAbort(epoch)
            || parseTask(ctx.dialogue.getText(), before) != null, 5_000);
    if (!shown || ctx.shouldAbort(epoch)) {
        return fail("No task text appeared");
    }
    ctx.runState.task = parseTask(ctx.dialogue.getText(), before);
    return true;
}

/** Pure: unit test it. Rejects partial reads and the text that was already there. */
static String parseTask(String text, String before) {
    if (text == null || text.equals(before)) return null;
    int at = text.indexOf("assigned to kill");
    return at < 0 ? null : text.substring(at).trim();
}

The master's name, option and task wording differ by server; keep them in config, not constants. Also record chat (Chat.recordMessage(e.getMessage()) in onChatMessage) if the server announces the task or its completion there, and read it with ctx.chat.containsMessage(...).

Pitfalls for combat plugins

  • Do not re-click while walking to the target. The game's Attack follows it. Wait for isInCombat() with a bound instead of attacking again every tick.
  • The local player's getInteracting() can read null mid-fight on some servers. Use ctx.combat.isInCombat() or the NPC's getInteracting().
  • withName is a case-insensitive substring match. "Goblin" also matches "Goblin champion". For an exact name add .where(n -> "Goblin".equalsIgnoreCase(n.getName())).
  • Off-screen targets can be refused on some servers (attack() returns false). Walk closer and count it as a failure, not a success.
  • Death is polled, never subscribed (rule 2). After death, clear targets, pending loot and the navigation session, and stop after N deaths in a rolling window that survives disconnects.
  • Thresholds are integer math: hp * 100 < max * eatAtPercent, and only when max > 0.
  • Slayer task counts and area flags in varbits use server-assigned ids. Do not use RuneLite Varbits constants (rule 13). Translate an OSRS id with ctx.ids.varbit(osrsId), an OptionalInt that is empty when it cannot.
  • Bank and teleport support differs per server. Check ctx.capabilities first, and treat a [PrivBot API] unsupported log or a repeated false as "not available here" and stop with a reason.

The starter project's example node and its test are a teaching-size version of this layout.

Unit-test this with the testkit, see Testing plugins.