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
//! Item frames with the `ghast-ext` helpers: finds the nearest item frame, equips `--held NAME`,
//! right-clicks the frame to put the item in ([`Bot::interact`]), right-clicks again to turn
//! it, then left-clicks to knock it out ([`Bot::attack`]) and looks for the dropped item.
//! After each step it runs that step's `--check-put` / `--check-turn` / `--check-knock`
//! command (the bot must be op) and prints the server's answers, so a script can confirm the
//! result on the server's side. `lab/item_frame.sh` drives it.
//!
//! Output lines (for scripts): `FRAME <id> <name> <x> <y> <z>`, `PUT`, `TURN`, `KNOCK`,
//! `DROP <item id> <count>` (the nearest item entity after the knock), `CHAT[<step>] <text>`
//! for every chat line after a step (the checks' answers), `FAIL <step> <error>`.
//!
//! ```text
//! cargo run -p ghast --release --features ext --example item_frame -- \
//!     --host 127.0.0.1 --port 25636 --username GhastBot9 --version 26.3 --minutes 1 \
//!     --held diamond
//! ```

mod support;

use ghast::Interests;
use ghast::ext::{Bot, Error, Event, Ext, WhenDone};

/// The example's own options (the rest are the examples' common ones).
#[derive(Debug, Clone)]
struct Opts {
    held: String,
    check_put: Option<String>,
    check_turn: Option<String>,
    check_knock: Option<String>,
}

impl Opts {
    fn take(args: Vec<String>) -> (Opts, Vec<String>) {
        let mut o = Opts {
            held: "diamond".into(),
            check_put: None,
            check_turn: None,
            check_knock: None,
        };
        let mut rest = Vec::new();
        let mut it = args.into_iter();
        while let Some(a) = it.next() {
            match a.as_str() {
                "--held" => o.held = it.next().expect("--held NAME"),
                "--check-put" => o.check_put = it.next(),
                "--check-turn" => o.check_turn = it.next(),
                "--check-knock" => o.check_knock = it.next(),
                _ => rest.push(a),
            }
        }
        (o, rest)
    }
}

/// Runs `cmd` (without the `/`) and prints the chat lines that follow as `CHAT[<step>] <text>`:
/// until 20 ticks after the first line, at most `ticks` ticks.
async fn check(bot: &Bot, step: &str, cmd: &Option<String>, ticks: u64) {
    let Some(c) = cmd else { return };
    let mut ev = bot.events();
    bot.chat(format!("/{c}"));
    let start = bot.tick();
    let mut end = start + ticks;
    let mut first = None;
    while bot.tick() < end {
        match bot.timeout(end - bot.tick(), ev.recv()).await {
            Ok(Some(Event::Chat(m))) => {
                println!("CHAT[{step}] {}", m.plain());
                if first.is_none() {
                    first = Some(bot.tick() - start);
                    end = end.min(bot.tick() + 20);
                }
            }
            Ok(Some(_)) => {}
            _ => break,
        }
    }
    if first.is_none() {
        println!("WAIT[{step}] no line in {ticks} ticks");
    }
}

/// `true` for a type name of this kind on any version (1.8's minecraft-data names are
/// `ItemFrame` and `Item`, later ones `item_frame` and `item`).
fn named(name: &str, kind: &str) -> bool {
    name.replace('_', "").eq_ignore_ascii_case(kind)
}

/// The nearest item frame within 6 blocks (the lab script summons it), waiting up to 5 s.
async fn frame(bot: &Bot) -> Result<i32, Error> {
    for _ in 0..100 {
        if let Some(f) = bot
            .nearest_entity(|e| named(e.name, "itemframe"), 6.0)
            .await?
        {
            println!(
                "FRAME {} {} {} {} {}",
                f.id, f.name, f.pos.x, f.pos.y, f.pos.z
            );
            return Ok(f.id);
        }
        bot.wait_ticks(1).await;
    }
    Err(Error::Timeout)
}

async fn run(bot: Bot, o: Opts) -> Result<(), Error> {
    // the join's packets, and the lab script's frame and items
    bot.wait_ticks(100).await;
    let id = match frame(&bot).await {
        Ok(id) => id,
        Err(e) => {
            println!("FAIL frame {e}");
            return Ok(());
        }
    };
    if let Err(e) = bot.equip(o.held.as_str()).await {
        println!("FAIL equip {e}");
    }
    bot.wait_ticks(5).await;
    match bot.interact(id).await {
        Ok(()) => println!("PUT"),
        Err(e) => println!("FAIL put {e}"),
    }
    bot.wait_ticks(10).await;
    check(&bot, "put", &o.check_put, 100).await;
    match bot.interact(id).await {
        Ok(()) => println!("TURN"),
        Err(e) => println!("FAIL turn {e}"),
    }
    bot.wait_ticks(10).await;
    check(&bot, "turn", &o.check_turn, 100).await;
    match bot.attack(id).await {
        Ok(()) => println!("KNOCK"),
        Err(e) => println!("FAIL knock {e}"),
    }
    bot.wait_ticks(20).await;
    match bot.nearest_entity(|e| named(e.name, "item"), 4.0).await? {
        Some(d) => {
            let (item, count) = d.item.unwrap_or((-1, 0));
            println!("DROP {item} {count}");
        }
        None => println!("FAIL drop no item entity near"),
    }
    check(&bot, "knock", &o.check_knock, 100).await;
    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("item_frame")
        .interests(Interests::CHAT | Interests::ENTITIES)
        .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 });
}