ghast-ext 0.5.6

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
//! Screens a bot answers: the sign editor, the book and quill, the bed.

use ghast_client::BlockPos;
use ghast_client::common::SleepEvent;
use ghast_client::sign::{SignEditor, SignEvent};

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

impl Bot {
    /// The sign editor the server has open now (see [`ghast_client::sign`]).
    ///
    /// ```no_run
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// if let Some(ed) = bot.sign_editor().await? {
    ///     println!("editing the sign at {:?}", ed.pos);
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn sign_editor(&self) -> Result<Option<SignEditor>, Error> {
        self.with(|ctx| ctx.sign_editor()).await
    }

    /// Waits up to `ticks` for the server to open the sign editor (it does right after the
    /// player placed a sign, and on 1.20+ after a right click on a sign the player may edit);
    /// an editor open already is returned at once. [`Error::Timeout`] when none opens.
    ///
    /// ```no_run
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// let _editor = bot.wait_sign_editor(40).await?;
    /// bot.write_sign(&["Hello", "world"]).await?;
    /// # Ok(()) }
    /// ```
    pub async fn wait_sign_editor(&self, ticks: u64) -> Result<SignEditor, Error> {
        // subscribed before the check: an editor opened in between is still seen
        let mut ev = self.events();
        if let Some(ed) = self.sign_editor().await? {
            return Ok(ed);
        }
        let wait = async {
            while let Some(e) = ev.recv().await {
                if let Event::Sign(SignEvent::Opened(ed)) = e {
                    return Ok(ed);
                }
            }
            Err(Error::Disconnected)
        };
        self.timeout(ticks, wait).await?
    }

    /// Writes up to four lines into the open sign editor and presses Done (see
    /// [`ghast_client::TickContext::write_sign`]: the vanilla character filter applies).
    /// [`Error::Sign`] without an open editor or with more than four lines.
    pub async fn write_sign(&self, lines: &[&str]) -> Result<(), Error> {
        let lines: Vec<String> = lines.iter().map(|l| (*l).to_owned()).collect();
        self.with(move |ctx| {
            let l: Vec<&str> = lines.iter().map(String::as_str).collect();
            ctx.write_sign(&l)
        })
        .await?
        .map_err(Error::Sign)
    }

    /// Edits the book and quill in the main hand (`off_hand`: the off hand) like a player:
    /// right-clicks with it (vanilla opens the book screen; the item-use packet goes out, which
    /// anticheats such as Grim expect before an edit), waits 5 ticks, then sends the pages with
    /// Done (`title: None`) or Sign with the title (see
    /// [`ghast_client::TickContext::edit_book`] and [`ghast_client::book`]). One call is one
    /// opening of the screen.
    /// [`Error::Book`] when the hand holds no book and quill, for too many pages or a blank
    /// title.
    ///
    /// ```no_run
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// bot.equip("writable_book").await?;
    /// bot.edit_book(false, &["Dear diary,\nnothing happened."], Some("Diary")).await?;
    /// # Ok(()) }
    /// ```
    pub async fn edit_book(
        &self,
        off_hand: bool,
        pages: &[&str],
        title: Option<&str>,
    ) -> Result<(), Error> {
        let pages: Vec<String> = pages.iter().map(|p| (*p).to_owned()).collect();
        let title = title.map(str::to_owned);
        let held = self
            .with(move |ctx| {
                let s = if off_hand {
                    ctx.inventory().offhand()
                } else {
                    ctx.inventory().held()
                };
                s.map(|s| s.id())
            })
            .await?;
        if held.is_none_or(|id| crate::item_name(self.version(), id) != "writable_book") {
            return Err(Error::Book(ghast_client::book::BookError::NoBook));
        }
        // Vanilla opens the book screen with a right click (the item-use packet goes out;
        // anticheats such as Grim expect it before an edit), then the player types. (An off
        // hand book opens when the main hand's item does nothing on a right click.)
        self.activate_item();
        self.next_tick().await;
        self.deactivate_item();
        self.wait_ticks(5).await;
        self.with(move |ctx| {
            let p: Vec<&str> = pages.iter().map(String::as_str).collect();
            ctx.edit_book(off_hand, &p, title.as_deref())
        })
        .await?
        .map_err(Error::Book)
    }

    /// The bed the player sleeps in, `None` when awake (see
    /// [`ghast_client::TickContext::sleeping`]).
    pub async fn sleeping(&self) -> Result<Option<BlockPos>, Error> {
        self.with(|ctx| ctx.sleeping()).await
    }

    /// Right-clicks the bed at `pos` and waits up to 40 ticks for the server to put the player
    /// in it ([`Error::NotAsleep`] when it does not: daytime, monsters near, too far, an
    /// occupied bed — the server says why in chat). Returns the bed the server chose.
    ///
    /// ```no_run
    /// use ghast_client::BlockPos;
    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
    /// bot.sleep_in(BlockPos::new(3, 64, 7)).await?;
    /// bot.wait_ticks(100).await; // the sleep timer is full after 100 ticks
    /// bot.leave_bed().await?;
    /// # Ok(()) }
    /// ```
    pub async fn sleep_in(&self, pos: BlockPos) -> Result<BlockPos, Error> {
        let mut ev = self.events();
        self.activate_block(pos).await?;
        let wait = async {
            while let Some(e) = ev.recv().await {
                if let Event::Sleep(SleepEvent::FellAsleep(bed)) = e {
                    return Ok(bed);
                }
            }
            Err(Error::Disconnected)
        };
        match self.timeout(40, wait).await {
            Ok(r) => r,
            Err(Error::Timeout) => Err(Error::NotAsleep),
            Err(e) => Err(e),
        }
    }

    /// Presses "Leave Bed" (see [`ghast_client::TickContext::leave_bed`]) and waits up to 40
    /// ticks for the server to wake the player up. [`Error::NotAsleep`] when not asleep.
    pub async fn leave_bed(&self) -> Result<(), Error> {
        let mut ev = self.events();
        if !self.with(|ctx| ctx.leave_bed()).await? {
            return Err(Error::NotAsleep);
        }
        let wait = async {
            while let Some(e) = ev.recv().await {
                if let Event::Sleep(SleepEvent::WokeUp) = e {
                    return Ok(());
                }
            }
            Err(Error::Disconnected)
        };
        self.timeout(40, wait).await?
    }

    /// Closes the open sign editor without typing (see
    /// [`ghast_client::TickContext::close_sign`]). [`Error::Sign`] without an open editor.
    pub async fn close_sign(&self) -> Result<(), Error> {
        self.with(|ctx| ctx.close_sign())
            .await?
            .map_err(Error::Sign)
    }
}