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};
#[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)
}
}
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
}
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> {
bot.wait_ticks(100).await;
println!("SIGNAL {:?}", bite_signal(bot.version()));
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;
}
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 {
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 });
}