ghast v0.5.6

Getting started

First bot

In this page you build a bot from an empty Cargo project. It joins a local server in offline mode, says hello in chat, turns a quarter turn every two seconds, jumps once a second, prints the chat it receives and leaves after a minute.

A server to join

Any Minecraft server for one of the supported versions works. The simplest is a vanilla or Paper server on your own machine with online-mode=false in server.properties, so the bot can log in with an offline name and no Microsoft account. Note the version the server runs; the bot must name the same one. Online-mode servers need the microsoft feature and are covered in Accounts and proxies.

The project

cargo new hello-bot
cd hello-bot
cargo add ghast
cargo add tokio --features rt,macros,signal

Replace src/main.rs with the program below. The rest of the page goes through it part by part.

use ghast::{Account, Behavior, Client, Controls, GameVersion, Interests, TickContext};

struct Hello {
    /// The yaw the bot is turning toward.
    yaw: f32,
}

impl Behavior for Hello {
    fn name(&self) -> &str {
        "hello"
    }

    fn interests(&self) -> Interests {
        Interests::CHAT
    }

    fn start(&mut self, ctx: &mut TickContext<'_>) {
        let p = ctx.pose().pos;
        println!("joined {} at {:.1} {:.1} {:.1}", ctx.version(), p.x, p.y, p.z);
        ctx.chat("Hello from ghast!");
    }

    fn tick(&mut self, ctx: &mut TickContext<'_>) {
        for m in &ctx.events().chat {
            println!("chat: {}", m.plain());
        }
        if ctx.is_dead() {
            ctx.respawn();
            return;
        }
        // Every 2 seconds: a quarter turn to the right.
        if ctx.tick() % 40 == 0 {
            self.yaw = (self.yaw + 90.0) % 360.0;
        }
        // The aim is a target for this tick: set it every tick you want to turn.
        ctx.set_aim(self.yaw, 0.0);
        // Hold the jump key for one tick out of every 20.
        ctx.set_controls(Controls { jump: ctx.tick() % 20 == 0, ..Controls::NONE });
        // Leave after one minute (1200 ticks of 50 ms).
        if ctx.tick() >= 1200 {
            ctx.disconnect("done");
        }
    }
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let account = Account::offline("HelloBot")?;
    let client = Client::new("localhost:25565".parse()?, GameVersion::V1_8_9, account);

    let mut bot = Hello { yaw: 0.0 };
    let shutdown = async {
        let _ = tokio::signal::ctrl_c().await;
    };
    let end = client.run_until(&mut bot, shutdown).await?;
    println!("session ended: {end:?}");
    Ok(())
}

Start the server, then cargo run.

Identity

Account::offline("HelloBot") is the player the bot logs in as. The name is checked like vanilla checks it (1 to 16 characters of A-Z, a-z, 0-9 and _), so it returns a Result. The UUID is derived from the name, as in vanilla's offline mode.

Connecting and choosing the version

Client::new takes three things: the address, the game version and the account. The address parses from "host:port". The version is a GameVersion value and must match the server; ghast does not probe the server for it. Here it is V1_8_9; for a 26.3 server write GameVersion::V26_3, or parse a string such as "26.3" or "1.16.5". Everything else in the program stays the same on every version. See Versions.

A Client is only configuration. Nothing connects until you run it, and one Client can run any number of sessions one after another, which is how the afk example reconnects.

The behaviour

A behaviour is any type that implements Behavior. Only tick is required; the other methods have defaults.

  • name is used in log lines.
  • interests lists the optional packet groups the bot needs. Chat is optional: without Interests::CHAT, chat packets are dropped before they are decoded and ctx.events().chat stays empty.
  • start runs once, on the first tick the player is in the world, just before that tick's tick. Here it prints the position and sends a chat line. ctx.chat sends a chat line or a command, truncated to the version's limit.
  • tick runs every 50 ms while the player is in the world.

Inside tick the bot reads and acts through the TickContext:

  • ctx.events().chat holds the chat messages that arrived since the previous tick; plain() turns one into plain text.
  • ctx.is_dead() and ctx.respawn() handle the death screen. The afk example waits 20 ticks before respawning, because vanilla's death screen enables its buttons after 20 ticks.
  • ctx.set_aim(yaw, pitch) sets where the bot looks. The client turns toward the target in whole mouse counts, at most 14 degrees of yaw per tick by default, so a quarter turn takes several ticks. The target only holds for the tick it is set in, so the bot sets it every tick.
  • ctx.set_controls sets the movement keys. Keys stay held until you change them. The physics turns them into movement exactly as the vanilla client would, so holding jump on the ground makes the player jump.
  • ctx.tick() counts ticks since the connection entered the play state.

Why aim and keys are intents, and when actions are sent, is the subject of The tick model.

Running and stopping

client.run_until(&mut bot, shutdown) connects, logs in, runs the tick loop and returns when the session ends. It ends with a SessionEnd:

  • Quit(reason) when the behaviour calls ctx.disconnect, as this bot does after 1200 ticks;
  • Shutdown when the shutdown future completes, here on Ctrl-C;
  • Kicked { reason, .. } or ServerClosed when the server ends it;
  • Transferred { host, port } when a 26.x server transfers the bot and following transfers is off.

SessionEnd is #[non_exhaustive], so a match on it needs a _ arm. Errors such as a refused connection or a timeout come back as Err(ClientError). If you do not need a shutdown signal, client.run(&mut bot) is the same without one.

If the behaviour panics, ghast catches it, stops the behaviour and keeps the player standing and answering the server until the session ends.

Next steps

  • The tick model explains what happens in one tick and what a behaviour may do in it.
  • Async helpers (ext) shows how to write multi-step jobs (walk there, dig this, wait for that message) as straight-line async code instead of a state machine.