mod support;
use ghast::Interests;
use ghast::ext::{Bot, Error, Event, Ext, WhenDone};
#[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)
}
}
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");
}
}
fn named(name: &str, kind: &str) -> bool {
name.replace('_', "").eq_ignore_ascii_case(kind)
}
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> {
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 });
}