pub struct Bot { /* private fields */ }Expand description
A handle to the bot for async tasks: cheap to clone, Send + Sync.
Reads of the per-tick snapshot (Bot::pose, Bot::health, …) are synchronous.
Everything that touches the world, the inventory or the server goes through
Bot::with (or a helper built on it) and runs inside the tick.
Handles work best in tasks the Ext executor polls (Ext::new, Bot::spawn):
those resume within the same tick. A handle moved into a task of another executor (e.g.
a tokio task reading stdin) works too, one tick later.
Implementations§
Source§impl Bot
impl Bot
Sourcepub async fn dig(&self, pos: BlockPos) -> Result<(), Error>
pub async fn dig(&self, pos: BlockPos) -> Result<(), Error>
Digs the block at pos: selects the fastest hotbar tool, turns until the server
has the crosshair on the block (aim first), then holds the left button for the
vanilla dig time (tool, efficiency, haste / fatigue, water, not on ground) and
releases it once the block is gone. The player should stand still meanwhile.
Fails with Error::NothingToDig (air), Error::Unbreakable,
Error::OutOfReach, Error::LostTarget, Error::Teleported /
Error::Died or Error::Timeout. The client predicts the broken block as air;
if the server disagrees it sends the block back (see Bot::block_at).
use ghast_client::BlockPos;
bot.dig(BlockPos::new(2, 64, 0)).await?;Sourcepub async fn dig_with(
&self,
pos: BlockPos,
opts: DigOptions,
) -> Result<(), Error>
pub async fn dig_with( &self, pos: BlockPos, opts: DigOptions, ) -> Result<(), Error>
Bot::dig with options.
use ghast_client::{BlockPos, Face};
use ghast_ext::DigOptions;
bot.dig_with(BlockPos::new(2, 64, 0), DigOptions::default().best_tool(false).face(Face::Up)).await?;Sourcepub async fn place(&self, against: BlockPos, face: Face) -> Result<(), Error>
pub async fn place(&self, against: BlockPos, face: Face) -> Result<(), Error>
Places the held block against against’s face (the new block goes to
face.offset(against)): turns until the server has the crosshair on that face, sends
the right click at the crosshair’s hit point, and waits until the block appears.
Fails with Error::NoSupport (air), Error::Occupied (the target is not air /
liquid, or the player stands in it), Error::WouldActivate (a chest, door, … :
the click would use it), Error::NothingHeld, Error::OutOfReach,
Error::NotPlaced (the server refused) and the usual interrupts.
use ghast_client::{BlockPos, Face};
bot.equip("cobblestone").await?;
bot.place(BlockPos::new(2, 63, 0), Face::Up).await?; // on top of the block at y 63Sourcepub async fn activate_block(&self, pos: BlockPos) -> Result<(), Error>
pub async fn activate_block(&self, pos: BlockPos) -> Result<(), Error>
Right-clicks pos (opens a chest, flips a lever, uses a door, …): turns until the
server has the crosshair on the block, then sends the click. Returns once it was sent;
see Bot::open_container to wait for a window.
use ghast_client::BlockPos;
bot.activate_block(BlockPos::new(5, 64, 5)).await?; // a leverSourcepub async fn consume(&self) -> Result<(), Error>
pub async fn consume(&self) -> Result<(), Error>
Uses the held item until it is done: eats / drinks (food needs a non-full food bar;
golden apples always), with the right button held until the server ends the use.
Fails with Error::CannotUse when the use does not start. Look away from
containers / doors first (the right click would use them; checked:
Error::WouldActivate).
if bot.health().food < 18 {
bot.equip("bread").await?;
bot.consume().await?;
}Sourcepub fn activate_item(&self)
pub fn activate_item(&self)
Starts using the held item (right button held: draw a bow, block with a sword /
shield, start eating). Release it with Bot::deactivate_item. While the held item
cools down (Bot::held_cooldown) the held button only sends its packets, every 4
ticks, like vanilla (Bot::wait_cooldown waits for the end).
bot.equip("bow").await?;
bot.activate_item();
bot.wait_ticks(20).await; // full draw
bot.deactivate_item(); // shootSourcepub fn deactivate_item(&self)
pub fn deactivate_item(&self)
Releases the mouse buttons (ends an item use, stops digging).
bot.deactivate_item();Sourcepub fn left_click(&self)
pub fn left_click(&self)
Clicks the left button once in this tick’s (or the next tick’s) key handling, like a
vanilla mouse click: attacks the entity the crosshair is on, starts a dig, or misses
(then the 10-tick miss delay holds back the clicks after it in the same tick). Several
calls before a tick are several clicks in it. See
TickContext::press.
bot.left_click();
bot.left_click(); // two clicks in one tickSourcepub async fn attack(&self, id: i32) -> Result<(), Error>
pub async fn attack(&self, id: i32) -> Result<(), Error>
Attacks entity id: turns until the server’s crosshair is on it, then attacks
(refused by the client unless it is). Needs ghast_client::Interests::ENTITIES.
A living entity that already died (EntityInfo::alive false: its body stays for
the death animation) is not attacked: Error::NoSuchEntity, like one that is gone
(vanilla would let the hit through, but it does nothing and costs the swing).
if let Some(z) = bot.nearest_entity(|e| e.name == "zombie", 4.0).await? {
bot.attack(z.id).await?;
}Sourcepub async fn interact(&self, id: i32) -> Result<(), Error>
pub async fn interact(&self, id: i32) -> Result<(), Error>
Right clicks entity id once: turns until this tick’s crosshair and the server’s view
are on it, presses the right button for that tick and releases it. The client sends
what vanilla sends for the click (the interact packet per hand, the held item’s use
where the entity passes the click). Needs ghast_client::Interests::ENTITIES.
An item frame takes the held item when it is empty and turns its item otherwise
(Bot::attack knocks the item out); a villager opens its trades, a sheep is sheared,
a mob takes a name tag. The server’s answer is not waited for.
Errors: Error::NoSuchEntity (gone or dead), Error::EntityOutOfReach (more than
3 blocks from the eyes to its box), Error::Timeout (3 s without the crosshair on it).
if let Some(frame) = bot.nearest_entity(|e| e.name == "item_frame", 3.0).await? {
bot.interact(frame.id).await?; // put the held item in, or turn it
bot.attack(frame.id).await?; // take it out again
}Source§impl Bot
impl Bot
Sourcepub fn events(&self) -> Events
pub fn events(&self) -> Events
Subscribes to the bot’s events from the next tick on (buffered until read).
use ghast_ext::Event;
let mut events = bot.events();
while let Some(ev) = events.recv().await {
match ev {
Event::Chat(m) => println!("chat: {}", m.plain()),
Event::Died => bot.respawn(),
_ => {}
}
}Sourcepub async fn wait_for<F>(&self, pred: F) -> Result<Event, Error>
pub async fn wait_for<F>(&self, pred: F) -> Result<Event, Error>
Waits for the first event (from the next tick on) that matches pred and returns
it. Fails with Error::Disconnected when the session ends first.
use ghast_ext::Event;
bot.wait_for(|ev| matches!(ev, Event::Chat(m) if m.plain().contains("hi"))).await?;
bot.chat("hello");Sourcepub fn chat(&self, text: impl Into<String>)
pub fn chat(&self, text: impl Into<String>)
Sends a chat line or a command (/...) in this tick (truncated to the version’s
limit like vanilla).
bot.chat("hello");
bot.chat("/spawn");Sourcepub async fn wait_for_chat<F>(&self, pred: F) -> Result<ChatMessage, Error>
pub async fn wait_for_chat<F>(&self, pred: F) -> Result<ChatMessage, Error>
Waits for a chat message (from the next tick on) that matches pred.
let m = bot.wait_for_chat(|m| m.plain().starts_with("<Steve>")).await?;
println!("{}", m.plain());Sourcepub async fn command<F>(
&self,
text: impl Into<String>,
pred: F,
ticks: u64,
) -> Result<ChatMessage, Error>
pub async fn command<F>( &self, text: impl Into<String>, pred: F, ticks: u64, ) -> Result<ChatMessage, Error>
Sends text and waits up to ticks for the first chat reply that matches pred
(subscribed before sending, so a fast reply is not missed).
let reply = bot
.command("/balance", |m| m.plain().contains("Balance"), 100)
.await?;Sourcepub async fn tab_complete(
&self,
text: impl Into<String>,
) -> Result<TabCompletion, Error>
pub async fn tab_complete( &self, text: impl Into<String>, ) -> Result<TabCompletion, Error>
Asks the server to complete text and waits up to 100 ticks (5 s) for its answer
(Error::Timeout after that). The request is raw (see
ghast_client::TickContext::tab_complete): commands with their leading /.
let c = bot.tab_complete("/ti").await?;
for m in &c.matches {
println!("{}", m.text);
}Sourcepub async fn hud(&self) -> Result<Option<Hud>, Error>
pub async fn hud(&self) -> Result<Option<Hud>, Error>
What the HUD shows now (None without ghast_client::Interests::HUD).
if let Some(hud) = bot.hud().await? {
for bar in hud.boss_bars() {
println!("{} {:.0}%", bar.title.plain(), bar.progress * 100.0);
}
}Sourcepub fn respawn(&self)
pub fn respawn(&self)
Asks the server to respawn (only sent while dead).
if bot.is_dead() { bot.respawn(); }Sourcepub fn disconnect(&self, reason: impl Into<String>)
pub fn disconnect(&self, reason: impl Into<String>)
Ends the session after this tick’s packets (SessionEnd::Quit(reason)).
bot.disconnect("bye");Source§impl Bot
impl Bot
Sourcepub fn tick(&self) -> u64
pub fn tick(&self) -> u64
Ticks this behaviour ran in the current session (it does not advance while the server is silent and the behaviour is on hold).
let t = bot.tick();
bot.wait_ticks(20).await;
assert!(bot.tick() >= t + 20);Sourcepub fn version(&self) -> GameVersion
pub fn version(&self) -> GameVersion
The protocol version of the session.
if bot.version() == ghast_client::GameVersion::V1_8_9 { /* ... */ }Sourcepub fn pose(&self) -> Pose
pub fn pose(&self) -> Pose
The client pose at the start of this tick.
let p = bot.pose().pos;
println!("at {:.1} {:.1} {:.1}", p.x, p.y, p.z);Sourcepub fn sent(&self) -> Pose
pub fn sent(&self) -> Pose
The pose the server has (the last movement packet): what it judges actions against.
let server_yaw = bot.sent().yaw;Sourcepub fn health(&self) -> Health
pub fn health(&self) -> Health
Health, food and saturation.
if bot.health().food < 15 { /* eat */ }Sourcepub fn world_time(&self) -> Option<WorldTime>
pub fn world_time(&self) -> Option<WorldTime>
The world’s time at the start of this tick: game time and the dimension’s time of day
(None before the server’s first update_time).
let night = bot
.world_time()
.and_then(|t| t.time_of_day())
.is_some_and(|t| (13_000..23_000).contains(&t));Sourcepub fn is_dead(&self) -> bool
pub fn is_dead(&self) -> bool
The player is dead (see Bot::respawn).
if bot.is_dead() { bot.respawn(); }Sourcepub fn game_mode(&self) -> GameMode
pub fn game_mode(&self) -> GameMode
Game mode.
let creative = bot.game_mode() == ghast_client::GameMode::Creative;Sourcepub fn held_cooldown(&self) -> Option<ItemCooldown>
pub fn held_cooldown(&self) -> Option<ItemCooldown>
The cooldown of the held stack, while it cools down (1.9+: an ender pearl after a throw,
chorus fruit, a shield the server disabled, a 26.x use_cooldown; see
ghast_client::cooldown). A right click with it does nothing but its packets until
then. Always None on 1.8.9.
if let Some(c) = bot.held_cooldown() {
println!("{} ticks left", c.ticks_left);
}Sourcepub async fn wait_cooldown(&self) -> Result<(), Error>
pub async fn wait_cooldown(&self) -> Result<(), Error>
Waits until the held stack no longer cools down (Bot::held_cooldown; at once when
it does not).
bot.equip("ender_pearl").await?;
bot.wait_cooldown().await?;
bot.activate_item(); // thrown, not refusedSourcepub fn open_window(&self) -> Option<i32>
pub fn open_window(&self) -> Option<i32>
Id of the open container window.
if bot.open_window().is_some() { /* a chest is open */ }Sourcepub fn dimension(&self) -> String
pub fn dimension(&self) -> String
The current dimension ("0" / "-1" / "1" on 1.8, the world name on 1.16).
let nether = bot.dimension() == "-1";Sourcepub fn with<R, F>(&self, f: F) -> With<R> ⓘ
pub fn with<R, F>(&self, f: F) -> With<R> ⓘ
Runs f with this tick’s TickContext and returns its result. From a task the
Ext executor polls, f runs in the same tick (before the movement packet), so
several with calls in a row cost no ticks. Actions inside f follow the usual
rules (set_aim only for this tick, aim first and act on a later tick, …).
A panic in f resumes in the awaiting task. Fails with Error::Disconnected once
the session ended.
let (stone, raw) = bot
.with(|ctx| {
let p = ghast_client::BlockPos::new(0, 63, 0);
(ctx.world().raw_block(p.x, p.y, p.z), ctx.broken())
})
.await?;Sourcepub fn act<F>(&self, f: F)
pub fn act<F>(&self, f: F)
Queues f for this tick (or the next one) without waiting for it: requests run in
the order they were made. For fire-and-forget actions.
bot.act(|ctx| ctx.swing());Sourcepub fn wait_ticks(&self, n: u64) -> WaitTicks ⓘ
pub fn wait_ticks(&self, n: u64) -> WaitTicks ⓘ
Waits n behaviour ticks (0 returns at once). Resolves at once when the session
ended.
bot.wait_ticks(20).await; // one secondSourcepub fn next_tick(&self) -> WaitTicks ⓘ
pub fn next_tick(&self) -> WaitTicks ⓘ
Waits for the next tick.
loop {
if bot.health().health < 10.0 { break; }
bot.next_tick().await;
}Sourcepub fn sleep(&self, d: Duration) -> WaitTicks ⓘ
pub fn sleep(&self, d: Duration) -> WaitTicks ⓘ
Waits about d of game time, in whole ticks (50 ms each, rounded up).
bot.sleep(std::time::Duration::from_secs(2)).await;Sourcepub fn timeout<F: Future>(&self, ticks: u64, fut: F) -> Timeout<F> ⓘ
pub fn timeout<F: Future>(&self, ticks: u64, fut: F) -> Timeout<F> ⓘ
Runs fut and gives up after ticks ticks with Error::Timeout (fut is dropped,
which cancels it; helpers release their buttons when dropped).
let pos = ghast_client::BlockPos::new(3, 64, 0);
bot.timeout(200, bot.dig(pos)).await??;Sourcepub async fn wait_until<F>(&self, cond: F) -> Result<(), Error>
pub async fn wait_until<F>(&self, cond: F) -> Result<(), Error>
Waits until cond holds, checked once per tick with the tick’s context (also at
once).
bot.wait_until(|ctx| ctx.pose().on_ground).await?;Sourcepub fn spawn<T, F>(&self, fut: F) -> JoinHandle<T> ⓘ
pub fn spawn<T, F>(&self, fut: F) -> JoinHandle<T> ⓘ
Runs fut as another task of this bot (polled by the same executor, inside the
ticks). It is cancelled when the session ends. The handle gives its result.
let b = bot.clone();
let guard = bot.spawn(async move {
loop {
if b.is_dead() { b.respawn(); }
b.wait_ticks(20).await;
}
});
// ... later
guard.abort();Sourcepub fn require(&self, interests: Interests)
pub fn require(&self, interests: Interests)
Asks the helpers’ packet groups on top of the configured Ext::interests (e.g.
Interests::ENTITIES for entity helpers). Better set up front with
Ext::interests: a tracker started late misses entities that already exist.
bot.require(ghast_client::Interests::BLOCK_UPDATES);Source§impl Bot
impl Bot
Sourcepub async fn block_at(&self, pos: BlockPos) -> Result<Option<Block>, Error>
pub async fn block_at(&self, pos: BlockPos) -> Result<Option<Block>, Error>
The block at pos; None when its column is not loaded (never air by guess).
use ghast_client::BlockPos;
if let Some(b) = bot.block_at(BlockPos::new(0, 63, 0)).await? {
println!("{}", b.name());
}Sourcepub async fn find_blocks(
&self,
what: impl Into<BlockMatch>,
max_distance: f64,
count: usize,
) -> Result<Vec<BlockPos>, Error>
pub async fn find_blocks( &self, what: impl Into<BlockMatch>, max_distance: f64, count: usize, ) -> Result<Vec<BlockPos>, Error>
Up to count blocks matching what within max_distance of the eyes, nearest first
(loaded columns only). what is a name, an array of names or a predicate on
Block. The search runs inside one tick: keep max_distance modest (32 blocks is
~270k positions; all-air sections are skipped).
let ores = bot.find_blocks(|b: ghast_ext::Block| b.is_ore(), 32.0, 10).await?;
let chests = bot.find_blocks("chest", 16.0, 1).await?;
let logs = bot.find_blocks(["log", "log2"], 24.0, 64).await?;Sourcepub async fn find_block(
&self,
what: impl Into<BlockMatch>,
max_distance: f64,
) -> Result<Option<BlockPos>, Error>
pub async fn find_block( &self, what: impl Into<BlockMatch>, max_distance: f64, ) -> Result<Option<BlockPos>, Error>
The nearest block matching what within max_distance (see Bot::find_blocks).
if let Some(chest) = bot.find_block("chest", 16.0).await? { /* ... */ }Sourcepub async fn find_entities<F>(
&self,
pred: F,
radius: f64,
) -> Result<Vec<EntityInfo>, Error>
pub async fn find_entities<F>( &self, pred: F, radius: f64, ) -> Result<Vec<EntityInfo>, Error>
Tracked entities (not the bot) within radius of the bot matching pred, nearest
first. Needs ghast_client::Interests::ENTITIES (crate::Ext::interests);
empty without it.
let zombies = bot.find_entities(|e| e.name == "zombie", 16.0).await?;Sourcepub async fn nearest_entity<F>(
&self,
pred: F,
radius: f64,
) -> Result<Option<EntityInfo>, Error>
pub async fn nearest_entity<F>( &self, pred: F, radius: f64, ) -> Result<Option<EntityInfo>, Error>
The nearest tracked entity within radius matching pred (see
Bot::find_entities).
let player = bot.nearest_entity(|e| e.name == "player", 32.0).await?;Sourcepub async fn entity(&self, id: i32) -> Result<Option<EntityInfo>, Error>
pub async fn entity(&self, id: i32) -> Result<Option<EntityInfo>, Error>
A tracked entity by id.
if let Some(e) = bot.entity(id).await? { println!("{:?}", e.pos); }Sourcepub async fn player(&self, name: &str) -> Result<Option<EntityInfo>, Error>
pub async fn player(&self, name: &str) -> Result<Option<EntityInfo>, Error>
The player entity with this tab-list name (needs ghast_client::Interests::ENTITIES
and ghast_client::Interests::PLAYER_LIST).
if let Some(p) = bot.player("Steve").await? { println!("Steve at {:?}", p.pos); }Source§impl Bot
impl Bot
Sourcepub async fn bobber(&self) -> Result<Option<Bobber>, Error>
pub async fn bobber(&self) -> Result<Option<Bobber>, Error>
The bot’s own fishing bobber, while one is out (see
ghast_client::TickContext::fishing).
if let Some(b) = bot.bobber().await? {
println!("bobber {} at {:?}, biting: {}", b.id, b.position, b.biting);
}Sourcepub async fn cast(&self) -> Result<Bobber, Error>
pub async fn cast(&self) -> Result<Bobber, Error>
Casts the held fishing rod: one right click (a held button would repeat the use every
four ticks), then waits up to 40 ticks for the server’s bobber. Asks for entity
tracking (Interests::ENTITY_TRACKING) when no tracking is on. Aim first (the server
throws the bobber along the look the movement packets carry). Error::NothingHeld /
Error::CannotUse without a rod in the main hand, Error::AlreadyCast when a
bobber is out (reel it in first), Error::Timeout when no bobber appears.
use ghast_client::Vec3;
bot.equip("fishing_rod").await?;
bot.look_at(Vec3::new(10.5, 62.0, 4.5)).await?;
let bobber = bot.cast().await?;Sourcepub async fn wait_for_bite(&self, ticks: u64) -> Result<(), Error>
pub async fn wait_for_bite(&self, ticks: u64) -> Result<(), Error>
Waits up to ticks for a fish to bite our bobber (exact on 1.16.5 and 26.x, the
splash-sound heuristic on 1.8.9 and 1.12.2: see ghast_client::fishing). A bite that
is still on returns at once. Error::NoBobber without a bobber or when it goes away
while waiting, Error::Timeout when nothing bites in time.
bot.cast().await?;
bot.wait_for_bite(20 * 60).await?;
bot.reel_in().await?;Sourcepub async fn reel_in(&self) -> Result<(), Error>
pub async fn reel_in(&self) -> Result<(), Error>
Reels the bobber in: one right click with the rod, then waits up to 40 ticks for the
server to remove the bobber (a fish that bit lands in the inventory a little later:
the server throws the catch towards the player as an item entity). Error::NoBobber
without a bobber, Error::Timeout when it stays.
Sourcepub async fn fish(&self, ticks: u64) -> Result<(), Error>
pub async fn fish(&self, ticks: u64) -> Result<(), Error>
One catch: holds a fishing rod (equips one when the hand has none), casts along the
current look, waits for a bite and reels in. A bobber that goes away without a bite
(it landed on the ground, the fish got away and the server removed it) is cast again.
Gives up after ticks in all (Error::Timeout, the bobber reeled in again). The
catch flies to the player as an item entity; watch the inventory for it.
use ghast_client::Vec3;
bot.look_at(Vec3::new(10.5, 62.0, 4.5)).await?; // at the water
for _ in 0..10 {
bot.fish(20 * 120).await?;
bot.wait_ticks(10).await;
}Source§impl Bot
impl Bot
Sourcepub async fn goto(&self, goal: Goal) -> Result<(), Error>
pub async fn goto(&self, goal: Goal) -> Result<(), Error>
Walks to goal along a path planned by ghast_pathfinder with the default
Config (sprinting, gap jumps, swimming, ladders; no digging or placing) and
followed by its Follower: every plan is first run through the vanilla-exact
physics, moves the simulation fails are planned around, and the follower replans when
it gets stuck or leaves the path.
Fails with Error::NoPath when no path exists (or the start is not loaded),
Error::Stuck after too many replans, and the usual interrupts (teleport / death,
see crate::Ext::interrupt_on_teleport). Unloaded terrain is never treated as air:
a goal beyond it is approached through partial paths. Dropping the future releases
the keys.
A long plan is spread over several ticks (by default at most 2000 nodes and 5 ms of
planning per tick, see FollowConfig::budget); the bot stands still meanwhile and
the client keeps sending its movement packet every tick.
use ghast_ext::pathfinder::Goal;
bot.goto(Goal::Block([20, 64, -5])).await?;
bot.goto(Goal::Near { pos: [0, 64, 0], radius: 3.0 }).await?;Sourcepub async fn goto_with(
&self,
follower: Follower,
goal: Goal,
) -> Result<(), Error>
pub async fn goto_with( &self, follower: Follower, goal: Goal, ) -> Result<(), Error>
Bot::goto with a configured Follower (planner options such as digging or
placing, controller options, replan budget).
use ghast_ext::pathfinder::{Config, DigCost, FollowConfig, Follower, Goal, Pathfinder};
let pf = Pathfinder::new(Config::default().with_dig(Some(DigCost::default())));
let follower = Follower::new(pf, FollowConfig::default());
bot.goto_with(follower, Goal::Xz { x: 100, z: 40 }).await?;Sourcepub async fn follow_path(&self, id: i32, range: f64) -> Result<(), Error>
pub async fn follow_path(&self, id: i32, range: f64) -> Result<(), Error>
Follows entity id along planned paths (the planner and follower of Bot::goto),
staying within range blocks of it: through mazes, over gaps, around walls (unlike
Bot::follow_straight, which walks in a straight line). The bot plans again when the entity
has moved more than range (at least 2) blocks from where the current path goes, at
most one plan at a time; within range it stands and looks at the entity. When the
entity is out of reach (flying, across a gap too wide), the bot walks to the reachable
block closest to it and waits there until the entity moves.
Runs until the entity is gone (Error::NoSuchEntity) or the task is cancelled (e.g.
with Bot::timeout or crate::JoinHandle::abort). Needs
ghast_client::Interests::ENTITIES. Dropping the future releases the keys.
if let Some(p) = bot.player("Steve").await? {
let _ = bot.timeout(20 * 60, bot.follow_path(p.id, 2.0)).await; // one minute
}Sourcepub async fn follow_path_with(
&self,
follower: Follower,
id: i32,
range: f64,
) -> Result<(), Error>
pub async fn follow_path_with( &self, follower: Follower, id: i32, range: f64, ) -> Result<(), Error>
Bot::follow_path with a configured Follower.
Source§impl Bot
impl Bot
Sourcepub async fn count(&self, item: impl Into<ItemMatch>) -> Result<i32, Error>
pub async fn count(&self, item: impl Into<ItemMatch>) -> Result<i32, Error>
The window-0 slots / counts are read in the tick: total count of matching items in the player inventory (hotbar, main, armour, off hand).
let n = bot.count("cobblestone").await?;Sourcepub async fn find_item(
&self,
item: impl Into<ItemMatch>,
) -> Result<Option<(usize, Stack)>, Error>
pub async fn find_item( &self, item: impl Into<ItemMatch>, ) -> Result<Option<(usize, Stack)>, Error>
The PlayerInventory index (0–8 hotbar, 9–35 main) of the first matching stack,
hotbar first, and a copy of the stack.
if let Some((index, stack)) = bot.find_item("bread").await? {
println!("{} bread in slot {index}", stack.count());
}Sourcepub async fn held_item(&self) -> Result<Option<Stack>, Error>
pub async fn held_item(&self) -> Result<Option<Stack>, Error>
The held stack (a copy).
let held = bot.held_item().await?;Sourcepub fn select_slot(&self, slot: u8)
pub fn select_slot(&self, slot: u8)
Selects hotbar slot slot (0 … 8) in this tick.
bot.select_slot(2);Sourcepub async fn equip(&self, item: impl Into<ItemMatch>) -> Result<u8, Error>
pub async fn equip(&self, item: impl Into<ItemMatch>) -> Result<u8, Error>
Holds a matching item: selects it when it is in the hotbar; otherwise swaps it from the main inventory into the hotbar (an empty hotbar slot, else the held one) with a number-key click in the inventory screen (opened and closed again unless a container is open), then selects it. Returns the hotbar slot.
bot.equip("diamond_pickaxe").await?;
bot.equip(|s: &ghast_client::inventory::Stack| s.id() == 278).await?;Sourcepub async fn equip_for_block(&self, pos: BlockPos) -> Result<u8, Error>
pub async fn equip_for_block(&self, pos: BlockPos) -> Result<u8, Error>
Selects the hotbar tool that digs pos fastest, first bringing a faster one from the
main inventory into the hotbar if there is one. Returns the hotbar slot.
use ghast_client::BlockPos;
let p = BlockPos::new(1, 60, 1);
bot.equip_for_block(p).await?;
bot.dig(p).await?;Sourcepub async fn swap_to_hotbar(
&self,
index: usize,
hotbar: u8,
) -> Result<(), Error>
pub async fn swap_to_hotbar( &self, index: usize, hotbar: u8, ) -> Result<(), Error>
Swaps PlayerInventory index index with hotbar slot hotbar (number-key click).
Uses the open container if there is one, else opens the inventory screen for it and
closes it again.
bot.swap_to_hotbar(20, 0).await?; // main slot 20 <-> hotbar 0Sourcepub async fn drop_slot(&self, index: usize, all: bool) -> Result<(), Error>
pub async fn drop_slot(&self, index: usize, all: bool) -> Result<(), Error>
Drops the stack at PlayerInventory index index (all of it, or one with
all = false), with a Q click in the inventory screen.
bot.drop_slot(9, true).await?;Sourcepub async fn toss(&self, item: impl Into<ItemMatch>) -> Result<i32, Error>
pub async fn toss(&self, item: impl Into<ItemMatch>) -> Result<i32, Error>
Drops every matching stack from the hotbar and main inventory; returns how many items were dropped.
let n = bot.toss("rotten_flesh").await?;Sourcepub async fn click(&self, click: Click) -> Result<(), Error>
pub async fn click(&self, click: Click) -> Result<(), Error>
Sends a window click in the open screen and waits for the server’s confirm. Retries
(one tick at a time) while the click must wait: the look is turning (clicks only
while still), another click is in flight, or the same-tick packet rules forbid it.
Fails with Error::Click for refusals that will not go away (no screen, invalid
slot, unpredictable result), Error::ClickRejected or Error::ClickTimedOut.
use ghast_client::inventory::Click;
bot.click(Click::QuickMove { slot: 0, right: false }).await?; // shift-click slot 0Sourcepub async fn close_window(&self) -> Result<(), Error>
pub async fn close_window(&self) -> Result<(), Error>
Closes the open GUI (container or inventory screen).
bot.close_window().await?;Sourcepub async fn open_container(&self, pos: BlockPos) -> Result<Container, Error>
pub async fn open_container(&self, pos: BlockPos) -> Result<Container, Error>
Right-clicks the container at pos (chest, furnace, …) and waits for its window.
if let Some(pos) = bot.find_block("chest", 5.0).await? {
let chest = bot.open_container(pos).await?;
bot.deposit("cobblestone", None).await?;
bot.close_window().await?;
}Sourcepub async fn container_items(&self) -> Result<Vec<(usize, Stack)>, Error>
pub async fn container_items(&self) -> Result<Vec<(usize, Stack)>, Error>
The open container’s slots (index, stack copy), container part only.
for (slot, stack) in bot.container_items().await? {
println!("{slot}: {} x{}", stack.id(), stack.count());
}Sourcepub async fn deposit(
&self,
item: impl Into<ItemMatch>,
max: Option<i32>,
) -> Result<i32, Error>
pub async fn deposit( &self, item: impl Into<ItemMatch>, max: Option<i32>, ) -> Result<i32, Error>
Shift-clicks matching stacks from the player part of the open container into it,
whole stacks, until at least max items moved (None: all). Returns how many items
left the player inventory (it stops when the container is full).
let moved = bot.deposit("cobblestone", Some(128)).await?;Sourcepub async fn withdraw(
&self,
item: impl Into<ItemMatch>,
max: Option<i32>,
) -> Result<i32, Error>
pub async fn withdraw( &self, item: impl Into<ItemMatch>, max: Option<i32>, ) -> Result<i32, Error>
Shift-clicks matching stacks from the open container into the player inventory,
whole stacks, until at least max items moved (None: all). Returns how many items
arrived.
let got = bot.withdraw("bread", Some(16)).await?;Source§impl Bot
impl Bot
Sourcepub async fn look_at(&self, point: Vec3) -> Result<(), Error>
pub async fn look_at(&self, point: Vec3) -> Result<(), Error>
Turns to look at point in whole mouse counts (sensitivity GCD, at most 14° yaw /
10.5° pitch per tick, like a player’s mouse) and returns once the server has the final
look. The eyes are re-read every tick, so it also works while moving.
use ghast_client::Vec3;
bot.look_at(Vec3::new(10.5, 65.0, -3.5)).await?;Sourcepub async fn look(&self, yaw: f32, pitch: f32) -> Result<(), Error>
pub async fn look(&self, yaw: f32, pitch: f32) -> Result<(), Error>
Turns to an absolute yaw / pitch (degrees; pitch clamped to ±89.5 like the client) and returns once the server has the final look.
bot.look(90.0, 0.0).await?; // face -XSourcepub async fn look_at_block(
&self,
pos: BlockPos,
face: Option<Face>,
) -> Result<BlockHit, Error>
pub async fn look_at_block( &self, pos: BlockPos, face: Option<Face>, ) -> Result<BlockHit, Error>
Turns until the crosshair (as the server judges it, from the sent pose) is on pos
(on face, if given) and returns the hit. Fails with Error::OutOfReach when no
visible point of the block is within reach (4.5).
use ghast_client::BlockPos;
let hit = bot.look_at_block(BlockPos::new(2, 63, 0), None).await?;
println!("on face {:?} at {:?}", hit.face, hit.hit);Sourcepub async fn predict_throw(
&self,
throw: Throw,
max_ticks: u32,
) -> Result<Option<ThrowPrediction>, Error>
pub async fn predict_throw( &self, throw: Throw, max_ticks: u32, ) -> Result<Option<ThrowPrediction>, Error>
Where a throw or a bow shot from the current pose would fly: the expected path (no random
spread) and its first block hit within max_ticks ticks, from the version’s
oracle-proven launch and projectile physics (all six versions; see
ghast_client::TickContext::predict_throw). None when the version has no such item
or the bow was not drawn long enough. Entities in the way are not seen.
use ghast_client::throw::Throw;
bot.look(30.0, -20.0).await?;
if let Some(p) = bot.predict_throw(Throw::Bow { ticks_held: 20 }, 100).await?
&& let Some(hit) = p.hit
{
println!("the arrow sticks in {:?} after {} ticks", hit.block, hit.tick);
}Source§impl Bot
impl Bot
Sourcepub async fn walk_straight_to(
&self,
goal: Vec3,
range: f64,
) -> Result<(), Error>
pub async fn walk_straight_to( &self, goal: Vec3, range: f64, ) -> Result<(), Error>
Walks in a straight line until within range blocks (horizontally) of goal:
turns toward it (whole mouse counts), holds forward (sprinting while more than 3
blocks away), and jumps when blocked. No path planning: for open ground. Fails with
Error::Stuck after 3 s without progress, or when teleported / dead.
use ghast_client::Vec3;
bot.walk_straight_to(Vec3::new(10.5, 64.0, 3.5), 0.5).await?;Sourcepub async fn follow_straight(&self, id: i32, range: f64) -> Result<(), Error>
pub async fn follow_straight(&self, id: i32, range: f64) -> Result<(), Error>
Follows entity id, staying within range blocks of it, with the straight walker
(see Bot::walk_straight_to): for open ground. To follow through mazes, over gaps
and around walls use Bot::follow_path (feature pathfinder). Runs until the entity is gone
(Error::NoSuchEntity), the walker is stuck, or the task is cancelled (e.g. with
Bot::timeout or crate::JoinHandle::abort). Needs
ghast_client::Interests::ENTITIES.
if let Some(p) = bot.player("Steve").await? {
let _ = bot.timeout(20 * 60, bot.follow_straight(p.id, 2.0)).await; // one minute
}Sourcepub async fn follow(&self, id: i32, range: f64) -> Result<(), Error>
👎Deprecated since 0.5.3: the name hides that it walks a straight line: use follow_straight, or follow_path (feature pathfinder) to follow along planned paths
pub async fn follow(&self, id: i32, range: f64) -> Result<(), Error>
the name hides that it walks a straight line: use follow_straight, or follow_path (feature pathfinder) to follow along planned paths
Follows entity id in a straight line: the same as Bot::follow_straight.
Sourcepub fn set_controls(&self, controls: Controls)
pub fn set_controls(&self, controls: Controls)
Sets the movement keys (kept until changed) in this tick.
use ghast_client::Controls;
bot.set_controls(Controls { forward: true, jump: true, ..Controls::NONE });
bot.wait_ticks(10).await;
bot.set_controls(Controls::NONE);Source§impl Bot
impl Bot
Sourcepub async fn vehicle(&self) -> Result<Option<Ride>, Error>
pub async fn vehicle(&self) -> Result<Option<Ride>, Error>
What the bot rides now (None on foot): the vehicle’s id, type name, position,
whether the client moves it and the bot’s seat.
if let Some(r) = bot.vehicle().await? {
println!("on a {} (seat {:?}), steering: {}", r.name, r.seat, r.controlled);
}Sourcepub async fn mount(&self, id: i32) -> Result<Ride, Error>
pub async fn mount(&self, id: i32) -> Result<Ride, Error>
Boards entity id the way a player does: releases the movement keys (a sneaking
right click opens a horse’s inventory instead), turns until the crosshair is on the
entity (the server’s view too), right-clicks it and waits until the server seats the
player. Right-clicking with an item in the hand can use it on the mount instead
(food feeds a horse, a saddle saddles it): board with an empty hand. On 26.x the client
does not model yet which entity clicks a mob handles, so it also sends the held item’s
use after the click (and the off hand’s click): with a carrot / fungus on a stick that
use reaches the server after the seat and boosts the mount at once; take the stick
after boarding.
Fails with Error::NoSuchEntity (not tracked: needs
ghast_client::Interests::ENTITIES), Error::NotRideable (a type that carries
no player), Error::EntityOutOfReach (more than 3 blocks from the eyes) or
Error::NotSeated (the server did not seat the player after three clicks: no
saddle on a pig / strider / nautilus, no harness on a happy ghast, an untamed
donkey on 26.x, the seats taken, or a protected region). An untamed horse seats the
player and throws them off again a little later (taming), which this does not wait
for.
if let Some(h) = bot.nearest_entity(|e| e.name == "horse", 3.0).await? {
let ride = bot.mount(h.id).await?;
assert_eq!(ride.entity_id, h.id);
}Sourcepub async fn dismount(&self) -> Result<(), Error>
pub async fn dismount(&self) -> Result<(), Error>
Gets off: holds sneak until the client no longer rides, then releases every key (on
1.8.9, 1.12.2 and 26.x the server takes the player off when the sneak reaches it, on
1.16.5 the client also gets off one tick after the sneak). The server’s placement of
the player next to the vehicle (a teleport on most versions) does not interrupt it.
Returns at once when not riding. Fails with Error::Timeout when the server keeps
the player seated for 3 s (a plugin).
bot.dismount().await?;Sourcepub async fn ride_jump(&self, strength: f32) -> Result<f32, Error>
pub async fn ride_jump(&self, strength: f32) -> Result<f32, Error>
Charges the jump bar to strength (0 to 1, in steps of 0.1) and releases it: a horse
family mount jumps (higher with more strength), a camel or nautilus dashes. The bar
is the jump key: pressed, held one tick per 0.1 (full after 10 ticks, it falls again
when held longer), released; the client sends the riding jump with the bar on the
release. The other movement keys are kept (hold forward for a jump forward). Returns
the bar released (vanilla’s float, e.g. 0.3 for 0.25).
The jump only happens where vanilla’s does: on a saddled horse family mount or a
camel / nautilus the player controls, on the ground (a nautilus in water too), and
not while its cooldown runs (horse 10 ticks, camel 55, nautilus 40 after the last
jump: the bar does not charge then). Fails with Error::NotRiding on foot.
use ghast_client::Controls;
bot.set_controls(Controls { forward: true, ..Controls::NONE });
bot.ride_jump(0.7).await?;Sourcepub async fn dash(&self) -> Result<f32, Error>
pub async fn dash(&self) -> Result<f32, Error>
A full jump bar (Bot::ride_jump with 1.0): a camel’s or nautilus’s dash, a
horse’s highest jump.
bot.dash().await?;
bot.wait_ticks(55).await; // a camel's dash cooldownSourcepub async fn boost(&self) -> Result<(), Error>
pub async fn boost(&self) -> Result<(), Error>
Uses the carrot on a stick (pig) or warped fungus on a stick (strider, 1.16.5+) in a
hand while riding: one right click, the item use that boosts the mount (the server
starts the boost; 1.12.2+ clients then speed the pig up themselves, on 1.8.9 the
server moves the pig). Keep the crosshair off the mount and other entities / blocks
in reach (look ahead or up): a click on them would not use the item. Fails with
Error::NotRiding, Error::NoSuchItem (no stick in a hand) or
Error::CannotUse (the click would act on an entity or a block).
bot.equip("carrot_on_a_stick").await?;
bot.boost().await?;Source§impl Bot
impl Bot
Sourcepub async fn sign_editor(&self) -> Result<Option<SignEditor>, Error>
pub async fn sign_editor(&self) -> Result<Option<SignEditor>, Error>
The sign editor the server has open now (see ghast_client::sign).
if let Some(ed) = bot.sign_editor().await? {
println!("editing the sign at {:?}", ed.pos);
}Sourcepub async fn wait_sign_editor(&self, ticks: u64) -> Result<SignEditor, Error>
pub async fn wait_sign_editor(&self, ticks: u64) -> Result<SignEditor, Error>
Waits up to ticks for the server to open the sign editor (it does right after the
player placed a sign, and on 1.20+ after a right click on a sign the player may edit);
an editor open already is returned at once. Error::Timeout when none opens.
let _editor = bot.wait_sign_editor(40).await?;
bot.write_sign(&["Hello", "world"]).await?;Sourcepub async fn write_sign(&self, lines: &[&str]) -> Result<(), Error>
pub async fn write_sign(&self, lines: &[&str]) -> Result<(), Error>
Writes up to four lines into the open sign editor and presses Done (see
ghast_client::TickContext::write_sign: the vanilla character filter applies).
Error::Sign without an open editor or with more than four lines.
Sourcepub async fn edit_book(
&self,
off_hand: bool,
pages: &[&str],
title: Option<&str>,
) -> Result<(), Error>
pub async fn edit_book( &self, off_hand: bool, pages: &[&str], title: Option<&str>, ) -> Result<(), Error>
Edits the book and quill in the main hand (off_hand: the off hand) like a player:
right-clicks with it (vanilla opens the book screen; the item-use packet goes out, which
anticheats such as Grim expect before an edit), waits 5 ticks, then sends the pages with
Done (title: None) or Sign with the title (see
ghast_client::TickContext::edit_book and ghast_client::book). One call is one
opening of the screen.
Error::Book when the hand holds no book and quill, for too many pages or a blank
title.
bot.equip("writable_book").await?;
bot.edit_book(false, &["Dear diary,\nnothing happened."], Some("Diary")).await?;Sourcepub async fn sleeping(&self) -> Result<Option<BlockPos>, Error>
pub async fn sleeping(&self) -> Result<Option<BlockPos>, Error>
The bed the player sleeps in, None when awake (see
ghast_client::TickContext::sleeping).
Sourcepub async fn sleep_in(&self, pos: BlockPos) -> Result<BlockPos, Error>
pub async fn sleep_in(&self, pos: BlockPos) -> Result<BlockPos, Error>
Right-clicks the bed at pos and waits up to 40 ticks for the server to put the player
in it (Error::NotAsleep when it does not: daytime, monsters near, too far, an
occupied bed — the server says why in chat). Returns the bed the server chose.
use ghast_client::BlockPos;
bot.sleep_in(BlockPos::new(3, 64, 7)).await?;
bot.wait_ticks(100).await; // the sleep timer is full after 100 ticks
bot.leave_bed().await?;Sourcepub async fn leave_bed(&self) -> Result<(), Error>
pub async fn leave_bed(&self) -> Result<(), Error>
Presses “Leave Bed” (see ghast_client::TickContext::leave_bed) and waits up to 40
ticks for the server to wake the player up. Error::NotAsleep when not asleep.
Sourcepub async fn close_sign(&self) -> Result<(), Error>
pub async fn close_sign(&self) -> Result<(), Error>
Closes the open sign editor without typing (see
ghast_client::TickContext::close_sign). Error::Sign without an open editor.