ghast 0.5.6

Headless Minecraft Java Edition client / bot library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3) with vanilla-exact behaviour: facade crate re-exporting the ghast-* crates
Documentation
//! Fishing with the `ghast-ext` helpers: holds a fishing rod, looks at the water point
//! `--water X Y Z`, then catches `--catches N` times ([`ghast::ext::Bot::fish`]: cast, wait for
//! a bite, reel in), each attempt given at most `--wait TICKS`. Prints every fishing event and
//! what each catch added to the inventory. `lab/fishing.sh` drives it.
//!
//! Output lines (for scripts): `SIGNAL <EntityData|SplashSound>`, `CAST <id>`,
//! `STATE <id> <state> <x> <y> <z>` (when the bobber settles), `BITE <id>`,
//! `BITE_ENDED <id>`, `HOOKED <id> <entity>`, `GONE <id>`, `CATCH <n> <item>...` (the items
//! the inventory gained after a reel-in), `CAUGHT <total>`, `FAIL <step> <error>`.
//!
//! ```text
//! cargo run -p ghast --release --features ext --example fishing -- \
//!     --host 127.0.0.1 --port 25636 --username GhastBot9 --version 26.3 --minutes 3 \
//!     --water 0.5 3.9 6.5 --catches 1
//! ```

mod support;

use std::cell::RefCell;
use std::collections::BTreeMap;

use ghast::ext::{Bot, Error, Event, Ext, WhenDone};
use ghast::fishing::{BobberState, FishingEvent, bite_signal};
use ghast::{Interests, Vec3};

/// The example's own options (the rest are the examples' common ones).
#[derive(Debug, Clone)]
struct Opts {
    water: Option<Vec3>,
    catches: u32,
    wait: u64,
}

impl Opts {
    fn take(args: Vec<String>) -> (Opts, Vec<String>) {
        let mut o = Opts {
            water: None,
            catches: 1,
            wait: 20 * 90,
        };
        let mut rest = Vec::new();
        let mut it = args.into_iter();
        while let Some(a) = it.next() {
            match a.as_str() {
                "--water" => {
                    let mut n =
                        || -> f64 { it.next().and_then(|v| v.parse().ok()).expect("X Y Z") };
                    o.water = Some(Vec3::new(n(), n(), n()));
                }
                "--catches" => o.catches = it.next().and_then(|v| v.parse().ok()).expect("N"),
                "--wait" => o.wait = it.next().and_then(|v| v.parse().ok()).expect("TICKS"),
                _ => rest.push(a),
            }
        }
        (o, rest)
    }
}

/// The player inventory's item counts by name (the rod left out).
async fn items(bot: &Bot) -> Result<BTreeMap<&'static str, i32>, Error> {
    let v = bot.version();
    bot.with(move |ctx| {
        let seen = RefCell::new(BTreeMap::new());
        ctx.inventory().count(|s| {
            let name = ghast::ext::item_name(v, s.id());
            if name != "fishing_rod" {
                *seen.borrow_mut().entry(name).or_insert(0) += s.count();
            }
            false
        });
        seen.into_inner()
    })
    .await
}

/// Prints the fishing events as they come, and the bobber's state once it settles.
async fn watch(bot: Bot) {
    let mut ev = bot.events();
    let mut settled = None;
    loop {
        match bot.timeout(1, ev.recv()).await {
            Ok(Some(Event::Fishing(f))) => {
                let t = bot.tick();
                match f {
                    FishingEvent::Cast { id } => println!("CAST {id} t{t}"),
                    FishingEvent::Bite { id } => println!("BITE {id} t{t}"),
                    FishingEvent::BiteEnded { id } => println!("BITE_ENDED {id} t{t}"),
                    FishingEvent::Hooked { id, entity } => println!("HOOKED {id} {entity} t{t}"),
                    FishingEvent::Unhooked { id } => println!("UNHOOKED {id} t{t}"),
                    FishingEvent::Gone { id } => println!("GONE {id} t{t}"),
                    _ => {}
                }
            }
            Ok(Some(_)) | Err(Error::Timeout) => {}
            _ => return,
        }
        if let Ok(Some(b)) = bot.bobber().await
            && b.state != BobberState::Flying
            && settled != Some(b.id)
            && b.age > 20
        {
            settled = Some(b.id);
            let [x, y, z] = b.position;
            println!("STATE {} {:?} {x:.3} {y:.3} {z:.3}", b.id, b.state);
        }
    }
}

async fn run(bot: Bot, o: Opts) -> Result<(), Error> {
    // the join's packets, and the lab script's items
    bot.wait_ticks(100).await;
    println!("SIGNAL {:?}", bite_signal(bot.version()));
    // detached: it ends with the session
    drop(bot.spawn(watch(bot.clone())));
    if let Some(w) = o.water {
        bot.look_at(w).await?;
    }
    let mut total = 0;
    for _ in 0..o.catches {
        let before = items(&bot).await?;
        if let Err(e) = bot.fish(o.wait).await {
            println!("FAIL fish {e}");
            break;
        }
        // the catch flies to the player as an item entity
        bot.wait_ticks(40).await;
        let after = items(&bot).await?;
        let gained: Vec<String> = after
            .iter()
            .filter_map(|(k, n)| {
                let d = n - before.get(k).copied().unwrap_or(0);
                (d > 0).then(|| format!("{k}x{d}"))
            })
            .collect();
        let n: usize = gained.len();
        total += n;
        println!("CATCH {n} {}", gained.join(" "));
        if n == 0 {
            // where a catch went: the item entities around
            for e in bot.find_entities(|e| e.item.is_some(), 24.0).await? {
                println!("ITEM_ENTITY {} {:?} {:?}", e.id, e.item, e.pos);
            }
        }
        bot.wait_ticks(10).await;
    }
    println!("CAUGHT {total}");
    bot.wait_ticks(20).await;
    Ok(())
}

fn main() {
    let (so, rest) = Opts::take(std::env::args().skip(1).collect());
    let opts = support::Options::parse_from(rest);
    support::init_logger(opts.verbose);
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("tokio runtime");
    let mut ext = Ext::new(move |bot| run(bot, so.clone()))
        .name("fishing")
        .interests(Interests::CHAT | Interests::ENTITY_TRACKING)
        .when_done(WhenDone::Disconnect);
    let limit = opts.limit();
    let ok = rt.block_on(async {
        let client = match opts.client() {
            Ok(c) => c,
            Err(e) => {
                log::error!("{e}");
                std::process::exit(2);
            }
        };
        let shutdown = async {
            let stop = async {
                #[cfg(unix)]
                {
                    let mut term =
                        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
                            .expect("SIGTERM handler");
                    tokio::select! {
                        _ = tokio::signal::ctrl_c() => {}
                        _ = term.recv() => {}
                    }
                }
                #[cfg(not(unix))]
                let _ = tokio::signal::ctrl_c().await;
            };
            match limit {
                Some(l) => {
                    tokio::select! {
                        () = stop => {}
                        () = tokio::time::sleep(l) => log::warn!("time limit reached"),
                    }
                }
                None => stop.await,
            }
        };
        match client.run_until(&mut ext, shutdown).await {
            Ok(e) => {
                log::info!("session ended: {e:?}; result {:?}", ext.result());
                matches!(ext.result(), Some(Ok(())))
            }
            Err(e) => {
                log::error!("session failed: {e}");
                false
            }
        }
    });
    std::process::exit(if ok { 0 } else { 1 });
}