ghast-ext 0.5.5

Sequential, mineflayer-style async helpers (look, dig, place, equip, containers, chat, events, find) on top of the ghast bot library's deterministic tick model
Documentation
//! Fishing: cast, wait for a bite, reel in (see [`ghast_client::fishing`] for what the client
//! knows about the bobber and how exact the bite is on each version).

use ghast_client::fishing::{Bobber, FishingEvent};
use ghast_client::{Buttons, Interests};

use crate::events::Event;
use crate::{Bot, Error};

/// Ticks a cast or a reel-in waits for the server's answer.
const ANSWER_TICKS: u64 = 40;

impl Bot {
    /// The bot's own fishing bobber, while one is out (see
    /// [`ghast_client::TickContext::fishing`]).
    ///
    /// ```no_run
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// if let Some(b) = bot.bobber().await? {
    ///     println!("bobber {} at {:?}, biting: {}", b.id, b.position, b.biting);
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn bobber(&self) -> Result<Option<Bobber>, Error> {
        self.with(|ctx| ctx.fishing().copied()).await
    }

    /// 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.
    ///
    /// ```no_run
    /// use ghast_client::Vec3;
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// bot.equip("fishing_rod").await?;
    /// bot.look_at(Vec3::new(10.5, 62.0, 4.5)).await?;
    /// let bobber = bot.cast().await?;
    /// # let _ = bobber;
    /// # Ok(()) }
    /// ```
    pub async fn cast(&self) -> Result<Bobber, Error> {
        self.ensure_tracking().await;
        let mut ev = self.events();
        let mark = self.mark();
        self.with(|ctx| -> Result<(), Error> {
            if ctx.fishing().is_some() {
                return Err(Error::AlreadyCast);
            }
            rod_held(ctx)
        })
        .await??;
        self.rod_click().await?;
        let wait = async {
            while let Some(e) = ev.recv().await {
                if let Event::Fishing(FishingEvent::Cast { .. }) = e
                    && let Some(b) = self.bobber().await?
                {
                    return Ok(b);
                }
            }
            Err(Error::Disconnected)
        };
        let r = self.timeout(ANSWER_TICKS, wait).await?;
        self.check(mark)?;
        r
    }

    /// 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.
    ///
    /// ```no_run
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// bot.cast().await?;
    /// bot.wait_for_bite(20 * 60).await?;
    /// bot.reel_in().await?;
    /// # Ok(()) }
    /// ```
    pub async fn wait_for_bite(&self, ticks: u64) -> Result<(), Error> {
        let mut ev = self.events();
        let Some(b) = self.bobber().await? else {
            return Err(Error::NoBobber);
        };
        if b.biting {
            return Ok(());
        }
        let id = b.id;
        let wait = async {
            while let Some(e) = ev.recv().await {
                match e {
                    Event::Fishing(FishingEvent::Bite { id: i }) if i == id => return Ok(()),
                    Event::Fishing(FishingEvent::Gone { id: i }) if i == id => {
                        return Err(Error::NoBobber);
                    }
                    _ => {}
                }
            }
            Err(Error::Disconnected)
        };
        self.timeout(ticks, wait).await?
    }

    /// 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.
    pub async fn reel_in(&self) -> Result<(), Error> {
        let mut ev = self.events();
        let Some(b) = self.bobber().await? else {
            return Err(Error::NoBobber);
        };
        self.with(|ctx| rod_held(ctx)).await??;
        self.rod_click().await?;
        let id = b.id;
        let wait = async {
            loop {
                if self.bobber().await?.is_none_or(|b| b.id != id) {
                    return Ok(());
                }
                match ev.recv().await {
                    Some(Event::Fishing(FishingEvent::Gone { id: i })) if i == id => {
                        return Ok(());
                    }
                    Some(_) => {}
                    None => return Err(Error::Disconnected),
                }
            }
        };
        self.timeout(ANSWER_TICKS, wait).await?
    }

    /// 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.
    ///
    /// ```no_run
    /// use ghast_client::Vec3;
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// 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;
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn fish(&self, ticks: u64) -> Result<(), Error> {
        let rod = self
            .held_item()
            .await?
            .is_some_and(|s| crate::item_name(self.version(), s.id()) == "fishing_rod");
        if !rod {
            self.equip("fishing_rod").await?;
        }
        let attempt = async {
            loop {
                if self.bobber().await?.is_none() {
                    self.cast().await?;
                }
                // the outer timeout ends the wait
                match self.wait_for_bite(ticks).await {
                    Ok(()) => return self.reel_in().await,
                    Err(Error::NoBobber) => {}
                    Err(e) => return Err(e),
                }
            }
        };
        match self.timeout(ticks, attempt).await {
            Ok(r) => r,
            Err(e) => {
                if self.bobber().await.ok().flatten().is_some() {
                    let _ = self.reel_in().await;
                }
                Err(e)
            }
        }
    }

    /// Turns entity tracking on for the bobber when no tracking is on.
    async fn ensure_tracking(&self) {
        let on = self
            .with(|ctx| ctx.entities().is_some())
            .await
            .unwrap_or(true);
        if !on {
            self.require(Interests::ENTITY_TRACKING);
            self.next_tick().await;
            self.next_tick().await;
        }
    }

    /// One right click: the button down for one tick, then up.
    async fn rod_click(&self) -> Result<(), Error> {
        self.with(|ctx| {
            ctx.set_buttons(Buttons {
                left: false,
                right: true,
            });
        })
        .await?;
        self.next_tick().await;
        self.with(|ctx| ctx.set_buttons(Buttons::default())).await
    }
}

/// A fishing rod is in the main hand.
fn rod_held(ctx: &ghast_client::TickContext<'_>) -> Result<(), Error> {
    let held = ctx.inventory().held().ok_or(Error::NothingHeld)?;
    if crate::item_name(ctx.version(), held.id()) == "fishing_rod" {
        Ok(())
    } else {
        Err(Error::CannotUse)
    }
}