Plugin structure for bots

A bot plugin looks at the game once per game tick, queues an action, and checks on a later tick that it happened.

Which hook runs when

Every hook runs on the game's thread, one at a time. The full list is on Plugin.

HookRunsUse it to
The main chunkOnce, when the plugin loads.Build the plugin object, tables and constants.
startUpEach time the plugin is enabled, including when the client starts with it enabled.Reset your state.
onGameTickOnce per game tick, every 600 ms.Decide and act. A bot's loop belongs here.
onClientTickOnce per client cycle, every 20 ms, while logged in.What cannot wait for the next tick. It runs about 30 times per game tick, so keep it cheap.
onGameStateChangedWhen the game state changes, such as a login or a logout.Reset what a logout makes stale. Compare event:getGameState() with GameState.LOGGED_IN.
Other on<Event> hooksWhen that event happens.Note what happened, and leave the deciding to onGameTick.
sidePanelEvery UI frame while the panel shows.Show status. A button press may act.
renderOverlay(draw, layer)Once per layer per frame, which is three calls.Draw. It cannot act.
shutDownEach time the plugin is disabled.Clean up. No more events arrive, and its tasks are cancelled.

Start with onGameTick. What the server owns, such as hitpoints, the inventory and where NPCs stand, changes on the tick, so a loop that runs once per tick sees each change once. Reach for onClientTick only when a tick is too long to wait.

onClientTick does not run on the login screen. For work there, use onGameStateChanged or timer:every(ms, fn).

Start and Stop

A config item of type "startStop" is a plugin's run switch: a boolean, drawn on the plugin's settings page as a Start button, and as a Stop button while it runs. Enabling a plugin runs startUp but does not press Start, so a hook that acts reads the switch first and does nothing while it is false.

local Config = ConfigGroup("goblinfighter", {
    ConfigItem {
        keyName = "run",
        name = "Start/Stop",
        description = "Fight goblins",
        type = "startStop",
        default = false,
    },
})

local plugin = Plugin.new({ name = "Goblin Fighter" })
local config = configManager:getConfig(Config)

function plugin:onGameTick(_event: GameTick)
    -- Enabled is not started: do nothing until the player presses Start.
    if not config:run() then
        return
    end
    local goblin = scene:npcs():named("Goblin"):interactable():nearest()
    if goblin and not player:isInteracting() then
        goblin:interact("Attack")
    end
end

The switch never outlives the session. A restart, turning the plugin off, or switching profiles puts it back to Stop, so every run begins with the player pressing Start.

While a plugin runs with its switch at Start, the player's own mouse does not reach the game in that client. Bento can keep the player's keyboard from the game as well. Both are options in Bento's Settings: blocking the mouse is on by default, and blocking the keyboard is off. Only the game stops hearing the player. Your plugin's actions still reach it, and Bento's own panels, the Stop button, and plugins' own hotkeys and key listeners keep working, so the player can always stop a run.

Give a plugin a Start/Stop only if it plays the game itself, by queuing actions such as interact, walkTo or bank:withdraw. A plugin that only reads, draws or notifies must not have one: while it is "running", the player is locked out of their own client. Turning such a plugin on and off is all the switch it needs.

The main chunk

The main chunk is the plugin's constructor. It runs once, when the plugin loads, before the plugin starts and before a game is attached. It builds the plugin object and returns it.

It cannot act, because there is nothing to act on yet. Everything that reaches the game goes through a lowercase global such as player, scene or bank, and using one in the chunk raises. Capitalised globals such as ItemID, Skill and WorldPoint are constants and constructors, so they work there, and so does reading your config with configManager:getConfig.

-- Fine: your own constants and tables.
local FOOD = ItemID.SHARK
local seen = {}

-- Raises: the chunk runs before a game is attached.
local carried = player:inventory():itemAmount(FOOD)

function plugin:startUp()
    -- Fine: a callback has the game.
    log:info("carrying {} food", player:inventory():itemAmount(FOOD))
end

Tasks

A hook cannot wait, because it holds up the game until it returns. A task is a coroutine that can wait: the client resumes it once per game tick, after that tick's onGameTick has reached every plugin.

  • task(fn, ...) runs fn now, inside the calling callback, up to its first wait. Each game tick after that runs it to its next wait. It returns a Task. Call it from a callback.
  • sleepTicks(n) suspends the task for n game ticks, one if you leave it out. n must be a whole number.
  • waitUntil(pred, timeoutTicks) checks pred now and once per game tick, for at most timeoutTicks ticks. It returns whether pred came true. Both arguments are required.

sleepTicks and waitUntil run only in the task's own code. Anywhere else they raise. That rules out a hook, the main chunk, and a function the client calls back for you, such as a table.sort comparator.

local trip: Task? = nil

function plugin:onGameTick(_event: GameTick)
    if trip and trip:isAlive() then
        return
    end
    if player:inventory():contains(FOOD) then
        return
    end
    trip = task(function()
        if not bank:open() then
            log:warn("no bank in range")
            return
        end
        if not waitUntil(function() return bank:isOpen() end, 10) then
            log:warn("the bank did not open")
            return
        end
        bank:withdraw(FOOD, 10)
        if waitUntil(function() return player:inventory():contains(FOOD) end, 5) then
            bank:close()
        end
    end)
end

A task that raises stops, and the log has its traceback. isAlive() is then false and getError() returns the error. Your other tasks and the plugin go on. isDone() is true only when the task reached its end. cancel() stops a task, and stopping the plugin cancels all of them.

A task suits a fixed sequence. A bot that has to change its mind on any tick, to eat in the middle of a walk say, is easier as a state machine, as below. Either way, a loop with no wait in it holds up the game until the loop ends.

True means queued

true from an action means queued, not done. The call returns at once and nothing has happened yet. The NPC can die, an interface can close, or the player can log out before the action lands. So a plugin confirms by watching game state on a later tick.

-- Wrong: the shark is still in the inventory when this line runs.
if inventory:interact(FOOD, "Eat") then
    log:info("ate a shark")
end

-- Right: say what should change, and look on a later tick.
local before = inventory:itemAmount(FOOD)
if inventory:interact(FOOD, "Eat") then
    waitingFor = function()
        return player:inventory():itemAmount(FOOD) < before
    end
end

Do not queue the same action again because the state has not changed yet. Remember what you are waiting for, and how long you will wait for it. Actions.isBusy() returns whether anything you queued is still waiting, not whether it worked. Only game state shows that.

A queued action can be refused when it goes out, before any click: the target does not offer that option, the target is gone by then, or the widget is not there. Actions.refusedCount() counts your plugin's refused actions on this client. It only rises, so a count higher than when you last read it means a new refusal. Actions.lastRefusal() says why the latest one was refused, then the action, as in "'Take' is not a ground option on 'Bones': ...", and is nil until one has been. Remember the count in onGameTick. When it rises, read lastRefusal() and stop trying that target: the same click would be refused again. Actions dropped from a full tick, which Actions.droppedLastTick() counts, and clicks the game itself turns down are not refusals. Each refusal is also in the client log, under your plugin's name.

A few calls also return true when there is nothing to do: bank:open() with the bank open, player:walkTo(tile, distance) already within distance, and player:walkToArea(area) already inside the area.

How calls fail

A call fails in one of two ways, depending on whether the cause is your code or the game.

CauseResultFor example
Wrong use: bad arguments, unknown namesIt raises.sleepTicks(1.5), ui:openUrl("file:///x"), a misspelt spell name, a second terminal call on the same query.
Game state: item absent, NPC gone, interface shutfalse or nil.bank:withdraw(id, 10) with the bank shut or without the item, scene:npcs():named("Goblin"):nearest() with no goblin near.

A raise is a bug in your plugin, so fix it. false or nil reports game state, so handle it every time. An uncaught raise is confined to the callback that raised it: Limits and permissions has the details.

A name that finds nothing is game state too. named matches the whole name, ignoring case, so named("Goblin") is not a Hobgoblin; containing matches part of a name. A query that finds nothing returns nil or an empty list rather than raising.

renderOverlay cannot act: it only draws. An action called from it returns false, or raises if it is a capitalised static or an item's interact, and every machine's run returns blocked there and leaves the machine as it was.

RunStatus

Every state machine's run returns (RunStatus, string?): where it stands, and a reason when there is one.

export type RunStatus = "running" | "done" | "blocked" | "idle"
StatusMeans
runningIt is acting, or waiting for its last action to land. Call it again next tick.
doneThe goal is met.
blockedIt cannot get there until something changes. reason names what.
idleA machine that runs on a policy, such as loot or sustain, has nothing to do now. When it deferred, reason gives why.

The machines the API gives you all work this way: bank:newLoadout, grandExchange:newRestock, manager:newLoot and manager:newSustain. You give a machine its goal when you create it, then call run once per tick until it returns done or blocked.

local loadout: Loadout

function plugin:startUp()
    loadout = bank:newLoadout(EQUIPMENT, INVENTORY)
end

function plugin:onGameTick(_event: GameTick)
    local status, reason = loadout:run()
    if status == "blocked" then
        log:warn("cannot finish the loadout: {}", reason)
    end
end

Have your own machines return (RunStatus, string?) too, so a plugin can stack them.

A worked plugin

This is src/main.luau in full, for adapting. It shows the shape: it has not been tuned for any particular place in the game, so set the constants and test it on your own account first.

--!strict

-- Fights near a bank, eats when hurt, and fetches food when it runs out.
-- Change the constants to adapt it.

local plugin = Plugin.new({
    name = "Fight And Bank",
    description = "Fights, eats and banks.",
})

-- The run switch: Start and Stop on the plugin's settings page. Back at Stop after a restart.
local Config = ConfigGroup("fightandbank", {
    ConfigItem {
        keyName = "run",
        name = "Start/Stop",
        description = "Fight, eat and bank",
        type = "startStop",
        default = false,
    },
})
local config = configManager:getConfig(Config)

local TARGET = "Goblin"
local FOOD = ItemID.SHARK
local EAT_AT_HITPOINTS = 15
local BANK_TILE = WorldPoint.new(3269, 3167, 0) -- a tile by your bank, in the loaded scene
local WAIT_TICKS = 8

-- What the last action should change, and when to stop looking for it.
local waitingFor: (() -> boolean)? = nil
local giveUpAt = 0

local function expect(check: () -> boolean)
    waitingFor = check
    giveUpAt = client:getTickCount() + WAIT_TICKS
end

local function eat(): (RunStatus, string?)
    local inventory = player:inventory()
    local before = inventory:itemAmount(FOOD)
    if not inventory:interact(FOOD, "Eat") then
        return "blocked", "the food cannot be eaten"
    end
    expect(function()
        return player:inventory():itemAmount(FOOD) < before
    end)
    return "running", "eating"
end

local function fetchFood(): (RunStatus, string?)
    if not bank:isOpen() then
        if not bank:isNearBank() then
            player:walkTo(BANK_TILE)
            expect(function() return bank:isNearBank() end)
            return "running", "walking to the bank"
        end
        if not bank:open() then
            return "blocked", "no bank in range"
        end
        expect(function() return bank:isOpen() end)
        return "running", "opening the bank"
    end
    if player:inventory():contains(FOOD) then
        bank:close()
        expect(function() return not bank:isOpen() end)
        return "running", "closing the bank"
    end
    if not bank:withdraw(FOOD, 10) then
        return "blocked", "the bank holds no food"
    end
    expect(function() return player:inventory():contains(FOOD) end)
    return "running", "withdrawing food"
end

local function fight(): (RunStatus, string?)
    if player:isInteracting() then
        return "running", "fighting"
    end
    local target = scene:npcs():named(TARGET):interactable():nearest()
    if target == nil then
        return "idle", "nothing to fight here"
    end
    if target:interact("Attack") then
        expect(function() return player:isInteracting() end)
    end
    return "running", "attacking"
end

-- The machine: wait for the last action, then decide again from what is true now.
local function run(): (RunStatus, string?)
    if waitingFor and not waitingFor() and client:getTickCount() < giveUpAt then
        return "running", "waiting for the last action"
    end
    waitingFor = nil

    local hasFood = player:inventory():contains(FOOD)
    if bank:isOpen() or not hasFood then
        return fetchFood()
    end
    if player:currentHitpoints() <= EAT_AT_HITPOINTS then
        return eat()
    end
    return fight()
end

local status: RunStatus = "idle"
local reason: string? = nil

function plugin:onGameTick(_event: GameTick)
    if not config:run() then
        return
    end
    local nextStatus, nextReason = run()
    if nextStatus == "blocked" and status ~= "blocked" then
        log:warn("blocked: {}", nextReason)
    end
    status, reason = nextStatus, nextReason
end

function plugin:onGameStateChanged(event: GameStateChanged)
    if event:getGameState() ~= GameState.LOGGED_IN then
        waitingFor = nil
    end
end

-- A Stop forgets the wait, so the next Start decides afresh.
function plugin:onConfigChanged(event: ConfigChanged)
    if event:getGroup() == "fightandbank" and not config:run() then
        waitingFor = nil
        status, reason = "idle", nil
    end
end

function plugin:shutDown()
    waitingFor = nil
end

function plugin:sidePanel(panel: Panel)
    panel:heading("Fight And Bank")
    if not config:run() then
        panel:label("Stopped")
        return
    end
    panel:label(status .. ": " .. (reason or ""))
end

return plugin
  • It decides from game state, every tick. run holds no list of steps. If the player gets hurt or the food runs out, the next decision follows from that.
  • Each action records what it expects. expect stores a check. While the check is false and the wait has not run out, run returns running and queues nothing.
  • A wait can give up. After WAIT_TICKS it decides again from what is true now, so a lost action costs a few ticks and does not stop the bot.
  • Every step returns (RunStatus, string?). The panel shows the result, and blocked is logged once.
  • It runs only at Start. Its run switch is a "startStop" item, as in Start and Stop: onGameTick does nothing at Stop, and a Stop forgets what it was waiting for.

Eating waits like everything else here. To eat in the middle of a walk, check hitpoints before the wait.