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