Skip to main content

ghast_ext/
screens.rs

1//! Screens a bot answers: the sign editor, the book and quill, the bed.
2
3use ghast_client::BlockPos;
4use ghast_client::common::SleepEvent;
5use ghast_client::sign::{SignEditor, SignEvent};
6
7use crate::events::Event;
8use crate::{Bot, Error};
9
10impl Bot {
11    /// The sign editor the server has open now (see [`ghast_client::sign`]).
12    ///
13    /// ```no_run
14    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
15    /// if let Some(ed) = bot.sign_editor().await? {
16    ///     println!("editing the sign at {:?}", ed.pos);
17    /// }
18    /// # Ok(()) }
19    /// ```
20    pub async fn sign_editor(&self) -> Result<Option<SignEditor>, Error> {
21        self.with(|ctx| ctx.sign_editor()).await
22    }
23
24    /// Waits up to `ticks` for the server to open the sign editor (it does right after the
25    /// player placed a sign, and on 1.20+ after a right click on a sign the player may edit);
26    /// an editor open already is returned at once. [`Error::Timeout`] when none opens.
27    ///
28    /// ```no_run
29    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
30    /// let _editor = bot.wait_sign_editor(40).await?;
31    /// bot.write_sign(&["Hello", "world"]).await?;
32    /// # Ok(()) }
33    /// ```
34    pub async fn wait_sign_editor(&self, ticks: u64) -> Result<SignEditor, Error> {
35        // subscribed before the check: an editor opened in between is still seen
36        let mut ev = self.events();
37        if let Some(ed) = self.sign_editor().await? {
38            return Ok(ed);
39        }
40        let wait = async {
41            while let Some(e) = ev.recv().await {
42                if let Event::Sign(SignEvent::Opened(ed)) = e {
43                    return Ok(ed);
44                }
45            }
46            Err(Error::Disconnected)
47        };
48        self.timeout(ticks, wait).await?
49    }
50
51    /// Writes up to four lines into the open sign editor and presses Done (see
52    /// [`ghast_client::TickContext::write_sign`]: the vanilla character filter applies).
53    /// [`Error::Sign`] without an open editor or with more than four lines.
54    pub async fn write_sign(&self, lines: &[&str]) -> Result<(), Error> {
55        let lines: Vec<String> = lines.iter().map(|l| (*l).to_owned()).collect();
56        self.with(move |ctx| {
57            let l: Vec<&str> = lines.iter().map(String::as_str).collect();
58            ctx.write_sign(&l)
59        })
60        .await?
61        .map_err(Error::Sign)
62    }
63
64    /// Edits the book and quill in the main hand (`off_hand`: the off hand) like a player:
65    /// right-clicks with it (vanilla opens the book screen; the item-use packet goes out, which
66    /// anticheats such as Grim expect before an edit), waits 5 ticks, then sends the pages with
67    /// Done (`title: None`) or Sign with the title (see
68    /// [`ghast_client::TickContext::edit_book`] and [`ghast_client::book`]). One call is one
69    /// opening of the screen.
70    /// [`Error::Book`] when the hand holds no book and quill, for too many pages or a blank
71    /// title.
72    ///
73    /// ```no_run
74    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
75    /// bot.equip("writable_book").await?;
76    /// bot.edit_book(false, &["Dear diary,\nnothing happened."], Some("Diary")).await?;
77    /// # Ok(()) }
78    /// ```
79    pub async fn edit_book(
80        &self,
81        off_hand: bool,
82        pages: &[&str],
83        title: Option<&str>,
84    ) -> Result<(), Error> {
85        let pages: Vec<String> = pages.iter().map(|p| (*p).to_owned()).collect();
86        let title = title.map(str::to_owned);
87        let held = self
88            .with(move |ctx| {
89                let s = if off_hand {
90                    ctx.inventory().offhand()
91                } else {
92                    ctx.inventory().held()
93                };
94                s.map(|s| s.id())
95            })
96            .await?;
97        if held.is_none_or(|id| crate::item_name(self.version(), id) != "writable_book") {
98            return Err(Error::Book(ghast_client::book::BookError::NoBook));
99        }
100        // Vanilla opens the book screen with a right click (the item-use packet goes out;
101        // anticheats such as Grim expect it before an edit), then the player types. (An off
102        // hand book opens when the main hand's item does nothing on a right click.)
103        self.activate_item();
104        self.next_tick().await;
105        self.deactivate_item();
106        self.wait_ticks(5).await;
107        self.with(move |ctx| {
108            let p: Vec<&str> = pages.iter().map(String::as_str).collect();
109            ctx.edit_book(off_hand, &p, title.as_deref())
110        })
111        .await?
112        .map_err(Error::Book)
113    }
114
115    /// The bed the player sleeps in, `None` when awake (see
116    /// [`ghast_client::TickContext::sleeping`]).
117    pub async fn sleeping(&self) -> Result<Option<BlockPos>, Error> {
118        self.with(|ctx| ctx.sleeping()).await
119    }
120
121    /// Right-clicks the bed at `pos` and waits up to 40 ticks for the server to put the player
122    /// in it ([`Error::NotAsleep`] when it does not: daytime, monsters near, too far, an
123    /// occupied bed — the server says why in chat). Returns the bed the server chose.
124    ///
125    /// ```no_run
126    /// use ghast_client::BlockPos;
127    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
128    /// bot.sleep_in(BlockPos::new(3, 64, 7)).await?;
129    /// bot.wait_ticks(100).await; // the sleep timer is full after 100 ticks
130    /// bot.leave_bed().await?;
131    /// # Ok(()) }
132    /// ```
133    pub async fn sleep_in(&self, pos: BlockPos) -> Result<BlockPos, Error> {
134        let mut ev = self.events();
135        self.activate_block(pos).await?;
136        let wait = async {
137            while let Some(e) = ev.recv().await {
138                if let Event::Sleep(SleepEvent::FellAsleep(bed)) = e {
139                    return Ok(bed);
140                }
141            }
142            Err(Error::Disconnected)
143        };
144        match self.timeout(40, wait).await {
145            Ok(r) => r,
146            Err(Error::Timeout) => Err(Error::NotAsleep),
147            Err(e) => Err(e),
148        }
149    }
150
151    /// Presses "Leave Bed" (see [`ghast_client::TickContext::leave_bed`]) and waits up to 40
152    /// ticks for the server to wake the player up. [`Error::NotAsleep`] when not asleep.
153    pub async fn leave_bed(&self) -> Result<(), Error> {
154        let mut ev = self.events();
155        if !self.with(|ctx| ctx.leave_bed()).await? {
156            return Err(Error::NotAsleep);
157        }
158        let wait = async {
159            while let Some(e) = ev.recv().await {
160                if let Event::Sleep(SleepEvent::WokeUp) = e {
161                    return Ok(());
162                }
163            }
164            Err(Error::Disconnected)
165        };
166        self.timeout(40, wait).await?
167    }
168
169    /// Closes the open sign editor without typing (see
170    /// [`ghast_client::TickContext::close_sign`]). [`Error::Sign`] without an open editor.
171    pub async fn close_sign(&self) -> Result<(), Error> {
172        self.with(|ctx| ctx.close_sign())
173            .await?
174            .map_err(Error::Sign)
175    }
176}