ghast v0.5.6

Going further

Async helpers (ext)

After this page you can write a bot as a script (walk there, dig this, store it, say something) and know what runs when, and when a plain Behavior is the better tool.

Turning it on

The helpers live in ghast-ext, re-exported as ghast::ext behind the ext feature. goto also needs pathfinder:

ghast = { version = "0.5", features = ["ext", "pathfinder"] }

A script-like bot

use ghast::ext::pathfinder::Goal;
use ghast::ext::{Error, Ext};
use ghast::{Account, BlockPos, Client, GameVersion, Interests};

let mut bot = Ext::new(|bot| async move {
    // Walk next to the ore, along a planned, physics-checked path.
    bot.goto(Goal::Near { pos: [12, 64, 3], radius: 2.0 }).await?;

    // Dig it: best hotbar tool, aim first, the vanilla dig time.
    let ore = BlockPos::new(12, 64, 4);
    match bot.block_at(ore).await? {
        Some(b) if b.name() == "coal_ore" => bot.dig(ore).await?,
        Some(b) => println!("not coal ore but {}", b.name()),
        None => return Err(Error::NotLoaded(ore)),
    }
    bot.wait_ticks(20).await; // let the drop fly into the inventory

    // Put the coal into the nearest chest.
    if let Some(chest) = bot.find_block("chest", 16.0).await? {
        bot.goto(Goal::Near { pos: [chest.x, chest.y, chest.z], radius: 3.0 }).await?;
        bot.open_container(chest).await?;
        let moved = bot.deposit("coal", None).await?;
        bot.close_window().await?;
        bot.chat(format!("stored {moved} coal"));
    }
    Ok(())
})
.interests(Interests::CHAT);

let client = Client::new("localhost:25565".parse()?, GameVersion::V1_8_9, Account::offline("Miner")?);
client.run(&mut bot).await?;
if let Some(Err(e)) = bot.result() {
    eprintln!("bot failed: {e}");
}

Ext::new takes a factory that is called once per session with a Bot handle; its future is the main task. When it returns, the session ends (WhenDone::Disconnect, the default) or the bot stays online (.when_done(WhenDone::Stay)). Item and block names follow the connection's version: on 1.8.9 the coal item is coal and a log is log.

How async meets the tick loop

Ext is itself a Behavior with a small single-threaded executor inside. Nothing runs between ticks. On every tick, Ext::tick polls the tasks that are ready. A task reaches the game only through Bot::with: it hands over a closure, the executor runs it with that tick's TickContext, and resumes the task in the same tick.

let raw = bot
    .with(|ctx| {
        let p = ctx.pose().pos;
        ctx.world().raw_block(p.x as i32, p.y as i32 - 1, p.z as i32)
    })
    .await?;

So every helper obeys the same rules as hand-written code from the tick model:

  • every action is written inside tick, before the tick's single movement packet, in call order;
  • dig and place are refused unless the sent crosshair is on the block, so the helpers aim first and act on a later tick;
  • clicks wait while the player turns or while another click is in flight;
  • rotation is in whole mouse counts;
  • while the server is silent the behaviour, and every task with it, is on hold.

Several with calls in a row cost no ticks. Time passes only through wait_ticks(n), next_tick(), sleep(duration) (rounded up to 50 ms ticks) and the helpers that wait for the game.

The executor is ghast's own, not tokio's: tasks are polled only inside ticks. A task must not block, and it cannot keep the TickContext across an .await, because the context lives only inside the closure. The client itself still runs on tokio as usual.

What the helpers cover

grouphelpers
lookinglook, look_at, look_at_block
handsdig, dig_with, place, activate_block, consume, attack, swing
itemscount, find_item, equip, equip_for_block, toss, click
containersopen_container, container_items, deposit, withdraw, close_window
worldblock_at, find_block, find_blocks, find_entities, nearest_entity, player
chat and eventschat, command, wait_for_chat, wait_for, events
movingwalk_straight_to, follow_straight, goto, follow_path

There are also helpers for signs, books, beds, fishing (fish) and riding (mount, dismount). Entity helpers need Interests::ENTITIES (player names also PLAYER_LIST) in .interests(..); set it up front, since a tracker started late misses entities that already exist.

Errors, timeouts and tasks

Helpers fail with ghast::ext::Error when the world changes under them: a teleport or setback (Teleported, unless .interrupt_on_teleport(false)), a death (Died, or turn on .auto_respawn(true)), an unloaded block (NotLoaded), no path (NoPath). Nothing is left half-done: buttons are released and a window the helper opened is closed again.

bot.timeout(ticks, fut) gives up with Error::Timeout and drops the future, which cancels it and releases its keys. bot.spawn(fut) runs another task in the same executor:

bot.timeout(200, bot.dig(BlockPos::new(0, 63, 0))).await??;

let b = bot.clone();
let guard = bot.spawn(async move {
    loop {
        if b.is_dead() { b.respawn(); }
        b.wait_ticks(20).await;
    }
});
guard.abort();

One task should own the look and the movement keys at a time: two tasks aiming in the same tick override each other (the last set_aim wins), and a turning look blocks clicks.

When to use a plain Behavior

Use ext for jobs that are a sequence of steps with waiting in between: gather, store, craft, answer chat. Write a plain Behavior when the bot reacts every tick to what it sees, such as fighting, dodging or steering a mount by hand, or when you want full control over which packet goes out in which tick. The two mix: bot.with and bot.act reach the raw TickContext whenever a helper is missing, and Follower from the path finder works in a plain Behavior too.