Skip to main content

ghast_ext/
events.rs

1//! Events as a stream, `wait_for`, and chat helpers.
2
3use std::collections::VecDeque;
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::{Arc, Mutex};
7use std::task::{Context, Poll, Waker};
8
9use ghast_client::inventory::ClickResult;
10use ghast_client::{BlockPos, ChatMessage, GameMode, Health, TeleportEvent};
11
12use crate::executor::lock;
13use crate::find::EntityInfo;
14use crate::{Bot, Error};
15
16/// Something that happened, as delivered to [`Bot::events`] subscribers (in the order the
17/// tick saw them).
18#[derive(Debug, Clone, PartialEq)]
19#[non_exhaustive]
20pub enum Event {
21    /// A chat message ([`ghast_client::Interests::CHAT`], on by default in [`crate::Ext`]).
22    Chat(ChatMessage),
23    /// The server teleported / set back the player.
24    Teleport(TeleportEvent),
25    /// A join game packet (first join or a proxy server switch).
26    Joined,
27    /// Respawned or changed dimension.
28    Respawned,
29    /// The player died.
30    Died,
31    /// Health, food or saturation changed (the new values).
32    Health(Health),
33    /// The game mode changed.
34    GameMode(GameMode),
35    /// A container window opened (its id).
36    WindowOpened(i32),
37    /// The open window closed.
38    WindowClosed,
39    /// The player inventory changed.
40    InventoryChanged,
41    /// A click's confirm (or timeout).
42    Click(ClickResult),
43    /// A block changed ([`ghast_client::Interests::BLOCK_UPDATES`]): the version's raw state.
44    BlockUpdate {
45        /// Position.
46        pos: BlockPos,
47        /// Raw block state (see [`crate::Block`]).
48        raw: u32,
49    },
50    /// An entity appeared ([`ghast_client::Interests::ENTITIES`]; entities that existed when
51    /// the subscription started are not reported).
52    EntitySpawned(EntityInfo),
53    /// An entity is gone (despawned, out of range, killed).
54    EntityGone(i32),
55}
56
57pub(crate) struct SubState {
58    pub(crate) queue: VecDeque<Event>,
59    pub(crate) waker: Option<Waker>,
60}
61
62/// A subscription to the bot's events ([`Bot::events`]): events from the tick after it
63/// was made, buffered until read. Dropping it unsubscribes.
64pub struct Events {
65    bot: Bot,
66    session: u64,
67    state: Arc<Mutex<SubState>>,
68}
69
70impl std::fmt::Debug for Events {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.debug_struct("Events")
73            .field("buffered", &lock(&self.state).queue.len())
74            .finish()
75    }
76}
77
78impl Events {
79    /// The next event; `None` once the session ended.
80    ///
81    /// ```no_run
82    /// # async fn f(bot: ghast_ext::Bot) {
83    /// let mut events = bot.events();
84    /// while let Some(ev) = events.recv().await {
85    ///     println!("{ev:?}");
86    /// }
87    /// # }
88    /// ```
89    pub fn recv(&mut self) -> NextEvent<'_> {
90        NextEvent { events: self }
91    }
92
93    /// An event that is already buffered, without waiting.
94    ///
95    /// ```no_run
96    /// # async fn f(bot: ghast_ext::Bot) {
97    /// let mut events = bot.events();
98    /// bot.next_tick().await;
99    /// while let Some(ev) = events.try_next() { /* ... */ }
100    /// # }
101    /// ```
102    pub fn try_next(&mut self) -> Option<Event> {
103        lock(&self.state).queue.pop_front()
104    }
105}
106
107/// The future of [`Events::recv`].
108#[must_use = "futures do nothing unless awaited"]
109#[derive(Debug)]
110pub struct NextEvent<'a> {
111    events: &'a mut Events,
112}
113
114impl Future for NextEvent<'_> {
115    type Output = Option<Event>;
116
117    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Event>> {
118        let ev = &*self.events;
119        let mut st = lock(&ev.state);
120        if let Some(e) = st.queue.pop_front() {
121            return Poll::Ready(Some(e));
122        }
123        let s = ev.bot.lock();
124        if s.closed.is_some() || s.session != ev.session {
125            return Poll::Ready(None);
126        }
127        st.waker = Some(cx.waker().clone());
128        Poll::Pending
129    }
130}
131
132impl Bot {
133    /// Subscribes to the bot's events from the next tick on (buffered until read).
134    ///
135    /// ```no_run
136    /// use ghast_ext::Event;
137    /// # async fn f(bot: ghast_ext::Bot) {
138    /// let mut events = bot.events();
139    /// while let Some(ev) = events.recv().await {
140    ///     match ev {
141    ///         Event::Chat(m) => println!("chat: {}", m.plain()),
142    ///         Event::Died => bot.respawn(),
143    ///         _ => {}
144    ///     }
145    /// }
146    /// # }
147    /// ```
148    #[must_use]
149    pub fn events(&self) -> Events {
150        let state = Arc::new(Mutex::new(SubState {
151            queue: VecDeque::new(),
152            waker: None,
153        }));
154        let mut s = self.lock();
155        s.subs.push(Arc::downgrade(&state));
156        Events {
157            bot: self.clone(),
158            session: s.session,
159            state,
160        }
161    }
162
163    /// Waits for the first event (from the next tick on) that matches `pred` and returns
164    /// it. Fails with [`Error::Disconnected`] when the session ends first.
165    ///
166    /// ```no_run
167    /// use ghast_ext::Event;
168    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
169    /// bot.wait_for(|ev| matches!(ev, Event::Chat(m) if m.plain().contains("hi"))).await?;
170    /// bot.chat("hello");
171    /// # Ok(()) }
172    /// ```
173    pub async fn wait_for<F>(&self, mut pred: F) -> Result<Event, Error>
174    where
175        F: FnMut(&Event) -> bool + Send,
176    {
177        let mut ev = self.events();
178        while let Some(e) = ev.recv().await {
179            if pred(&e) {
180                return Ok(e);
181            }
182        }
183        Err(Error::Disconnected)
184    }
185
186    /// Sends a chat line or a command (`/...`) in this tick (truncated to the version's
187    /// limit like vanilla).
188    ///
189    /// ```no_run
190    /// # fn f(bot: ghast_ext::Bot) {
191    /// bot.chat("hello");
192    /// bot.chat("/spawn");
193    /// # }
194    /// ```
195    pub fn chat(&self, text: impl Into<String>) {
196        let text = text.into();
197        self.act(move |ctx| ctx.chat(text));
198    }
199
200    /// Waits for a chat message (from the next tick on) that matches `pred`.
201    ///
202    /// ```no_run
203    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
204    /// let m = bot.wait_for_chat(|m| m.plain().starts_with("<Steve>")).await?;
205    /// println!("{}", m.plain());
206    /// # Ok(()) }
207    /// ```
208    pub async fn wait_for_chat<F>(&self, mut pred: F) -> Result<ChatMessage, Error>
209    where
210        F: FnMut(&ChatMessage) -> bool + Send,
211    {
212        let mut ev = self.events();
213        while let Some(e) = ev.recv().await {
214            if let Event::Chat(m) = e
215                && pred(&m)
216            {
217                return Ok(m);
218            }
219        }
220        Err(Error::Disconnected)
221    }
222
223    /// Sends `text` and waits up to `ticks` for the first chat reply that matches `pred`
224    /// (subscribed before sending, so a fast reply is not missed).
225    ///
226    /// ```no_run
227    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
228    /// let reply = bot
229    ///     .command("/balance", |m| m.plain().contains("Balance"), 100)
230    ///     .await?;
231    /// # Ok(()) }
232    /// ```
233    pub async fn command<F>(
234        &self,
235        text: impl Into<String>,
236        mut pred: F,
237        ticks: u64,
238    ) -> Result<ChatMessage, Error>
239    where
240        F: FnMut(&ChatMessage) -> bool + Send,
241    {
242        let mut ev = self.events();
243        self.chat(text);
244        let wait = async {
245            while let Some(e) = ev.recv().await {
246                if let Event::Chat(m) = e
247                    && pred(&m)
248                {
249                    return Ok(m);
250                }
251            }
252            Err(Error::Disconnected)
253        };
254        self.timeout(ticks, wait).await?
255    }
256
257    /// Asks the server to respawn (only sent while dead).
258    ///
259    /// ```no_run
260    /// # fn f(bot: ghast_ext::Bot) {
261    /// if bot.is_dead() { bot.respawn(); }
262    /// # }
263    /// ```
264    pub fn respawn(&self) {
265        self.act(|ctx| {
266            ctx.respawn();
267        });
268    }
269
270    /// Ends the session after this tick's packets (`SessionEnd::Quit(reason)`).
271    ///
272    /// ```no_run
273    /// # fn f(bot: ghast_ext::Bot) {
274    /// bot.disconnect("bye");
275    /// # }
276    /// ```
277    pub fn disconnect(&self, reason: impl Into<String>) {
278        let reason = reason.into();
279        self.act(move |ctx| ctx.disconnect(reason));
280    }
281}