ghast-client 0.5.6

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! [`TickContext`]'s screens: the inventory and window clicks, the special menus (anvil, loom,
//! mount, buttons, trades), opening and closing the inventory, the server's dialogs and the
//! sign editor.

use super::*;

impl TickContext<'_> {
    /// The inventory: player slots, cursor, the open window, the pending click.
    #[must_use]
    pub fn inventory(&self) -> &ghast_inventory::Inventory {
        &self.core.inv
    }

    /// Clicks in the open screen (`window_click`, written now). Refused (nothing sent) while
    /// the player is dead ([`ClickRefused::Dead`]), while the player is turning (the look changed in the last movement step or an aim is set for
    /// this tick: clicks only while still) or when the inventory refuses it (one click in
    /// flight, same-tick packet order, unpredictable result, …). The result arrives in
    /// [`TickEvents::inventory`] on a later tick.
    pub fn click(&mut self, click: ghast_inventory::Click) -> Result<ClickTicket, ClickRefused> {
        self.still()?;
        let o = self
            .core
            .inv
            .click(click)
            .map_err(ClickRefused::Inventory)?;
        // the screen's own packets of this click (1.16.5 anvil rename_item) go first
        for s in self.core.inv.take_screen_packets() {
            self.core.out.push(Outbound::Inventory(s));
        }
        let ticket = match &o {
            ghast_inventory::Outgoing::Click(p) => ClickTicket {
                window_id: i32::from(p.window_id),
                action: p.action,
            },
            // 26.x: no confirm exists; the inventory reports the click under ghast's own
            // action number once it settled (or the server corrected it).
            ghast_inventory::Outgoing::ContainerClick(p) => ClickTicket {
                window_id: p.window_id,
                action: p.action,
            },
            // the 26.x creative screen's packets: applied at once, no result will follow
            _ => ClickTicket {
                window_id: -1,
                action: -1,
            },
        };
        self.core.out.push(Outbound::Inventory(o));
        Ok(ticket)
    }

    /// Whether [`TickContext::click`] would refuse right now for a reason other than the click
    /// itself, without sending or changing anything: [`ClickRefused::Dead`],
    /// [`ClickRefused::Turning`] (the look changed in the last movement step, or an aim is set
    /// for this tick — check after this tick's `set_aim`), or the inventory's own reason
    /// ([`ghast_inventory::Inventory::can_click`]: a click in flight, a resync, a click or open
    /// earlier in this tick, no screen open).
    pub fn can_click(&self) -> Result<(), ClickRefused> {
        self.still()?;
        self.core.inv.can_click().map_err(ClickRefused::Inventory)
    }

    /// Clicks and opening the inventory need a living player that is not turning.
    pub(super) fn still(&self) -> Result<(), ClickRefused> {
        if self.core.dead {
            return Err(ClickRefused::Dead);
        }
        if self.core.turned || self.core.aimed {
            return Err(ClickRefused::Turning);
        }
        Ok(())
    }

    /// Renames the item in the open anvil (26.1 `rename_item`, written now; nothing is sent
    /// when the name did not change or the input slot is empty). An empty name removes a
    /// custom name.
    pub fn anvil_rename(&mut self, name: &str) -> Result<(), ClickRefused> {
        if let Some(o) = self
            .core
            .inv
            .anvil_rename(name)
            .map_err(ClickRefused::Inventory)?
        {
            self.core.out.push(Outbound::Inventory(o));
        }
        Ok(())
    }

    /// Selects a banner pattern in the open loom (26.1 `container_button_click`, written now;
    /// nothing is sent for a pattern the loom does not offer).
    pub fn select_loom_pattern(&mut self, index: i32) -> Result<(), ClickRefused> {
        #[cfg(ghast_modern)]
        if let Some(o) = self
            .core
            .inv
            .select_loom_pattern_modern(index)
            .map_err(ClickRefused::Inventory)?
        {
            self.core.out.push(Outbound::Inventory(o));
        }
        #[cfg(not(ghast_modern))]
        let _ = index;
        Ok(())
    }

    /// 1.8 – 1.16.5: what the open mount screen's saddle and armor slots take, read off the
    /// mount entity (see [`ghast_inventory::Inventory::set_mount_rules`]); until then clicks that
    /// need them (a saddle, horse armor or carpet into those slots) are refused. Nothing is sent.
    pub fn set_mount_rules(&mut self, rules: Option<ghast_inventory::MountRules>) {
        self.core.inv.set_mount_rules(rules);
    }

    /// 1.16.5: presses a menu button the way its screen does (stonecutter recipe, loom pattern,
    /// lectern page / take book; `enchant_item` written now when the menu takes it). The
    /// stonecutter and the loom update their result like the client.
    pub fn click_button(&mut self, index: i32) -> Result<(), ClickRefused> {
        if let Some(o) = self
            .core
            .inv
            .click_button(index)
            .map_err(ClickRefused::Inventory)?
        {
            self.core.out.push(Outbound::Inventory(o));
        }
        Ok(())
    }

    /// Selects a trade in the open villager screen (1.8 / 1.12 `MC|TrSel`, 1.16.5 / 26.1
    /// `select_trade`, written now; the output is looked up again for that offer and, from
    /// 1.16.5 on, the payment slots are refilled like the real screen).
    pub fn select_trade(&mut self, index: i32) -> Result<(), ClickRefused> {
        let o = self
            .core
            .inv
            .select_trade(index)
            .map_err(ClickRefused::Inventory)?;
        self.core.out.push(Outbound::Inventory(o));
        Ok(())
    }

    /// Opens the player inventory GUI (1.8: the "open inventory" client command; 1.16: nothing
    /// is sent). Window 0 clicks need it open. Refused like [`TickContext::click`] while the
    /// player is dead or turning (a screen opened mid-turn would refuse every click until the
    /// player is still anyway).
    pub fn open_inventory(&mut self) -> Result<(), ClickRefused> {
        self.still()?;
        // The keys held from now are released by the new screen (1.16.5 passes later presses).
        self.core.screen_keys = None;
        if let Some(o) = self
            .core
            .inv
            .open_inventory()
            .map_err(ClickRefused::Inventory)?
        {
            self.core.out.push(Outbound::Inventory(o));
        }
        // 1.8 – 1.16.5 creative mode: the creative screen's listener broadcasts right after
        let echo = self.core.inv.take_creative_echo_legacy();
        if !echo.is_empty() {
            self.core
                .out
                .push(Outbound::Inventory(ghast_inventory::Outgoing::Creative(
                    echo,
                )));
        }
        Ok(())
    }

    /// Closes the open GUI (`close_window` with its id; 0 for the player inventory).
    pub fn close_window(&mut self) -> Result<(), ClickRefused> {
        let o = self.core.inv.close().map_err(ClickRefused::Inventory)?;
        self.core.out.push(Outbound::Inventory(o));
        // Vanilla closeHandledScreen: the container ends on the client too.
        self.core.open_window = 0;
        Ok(())
    }

    /// The sign editor the server has open now (`open_sign_entity`; see [`crate::sign`]).
    /// While it is open the movement keys are released and the mouse buttons are up.
    #[must_use]
    pub fn sign_editor(&self) -> Option<crate::sign::SignEditor> {
        self.core.sign.map(|s| s.editor)
    }

    /// Types up to four lines into the open sign editor and presses Done: the lines go
    /// through the vanilla screen's character filter ([`crate::sign::vanilla_line`]; missing
    /// lines are empty) and `update_sign` is written now, in call order with the other
    /// actions, before this tick's movement packet. The editor closes.
    ///
    /// ```no_run
    /// # fn f(ctx: &mut ghast_client::TickContext<'_>) {
    /// if ctx.sign_editor().is_some() {
    ///     let _ = ctx.write_sign(&["Hello", "from", "ghast"]);
    /// }
    /// # }
    /// ```
    ///
    /// # Errors
    /// [`crate::sign::SignError::NotOpen`] without an open editor,
    /// [`crate::sign::SignError::TooManyLines`] for more than four lines (nothing is sent).
    pub fn write_sign(&mut self, lines: &[&str]) -> Result<(), crate::sign::SignError> {
        let l = crate::sign::lines(lines)?;
        let s = self
            .core
            .sign
            .take()
            .ok_or(crate::sign::SignError::NotOpen)?;
        self.core.rare = self.core.sleeping.is_some();
        self.core.out.push(Outbound::UpdateSign {
            pos: s.editor.pos,
            front: s.editor.front,
            lines: l,
        });
        Ok(())
    }

    /// Closes the open sign editor without typing (Done or Escape): vanilla sends the text the
    /// screen started with; ghast sends four empty lines (see [`crate::sign`]: it does not
    /// keep sign text), written now.
    ///
    /// # Errors
    /// [`crate::sign::SignError::NotOpen`] without an open editor.
    pub fn close_sign(&mut self) -> Result<(), crate::sign::SignError> {
        self.write_sign(&[])
    }

    /// The bed the player sleeps in (its head block), `None` when awake. While asleep the
    /// sleep screen is open: the movement keys and mouse buttons do nothing, the look does not
    /// turn (1.16.5+ also levels the pitch to 0), and the player lies on the bed
    /// (`TickEvents::sleep` reports falling asleep and waking up).
    #[must_use]
    pub fn sleeping(&self) -> Option<ghast_protocol::BlockPos> {
        self.core.sleeping
    }

    /// The sleep timer (`sleepTimer` / `sleepCounter`): ticks asleep, at most 100 (the server
    /// skips the night once every player has slept 100 ticks).
    #[must_use]
    pub fn sleep_ticks(&self) -> u8 {
        if self.core.sleeping.is_some() {
            self.core.sleep_ticks
        } else {
            0
        }
    }

    /// Presses the sleep screen's "Leave Bed" button: `entity_action` `STOP_SLEEPING`, written
    /// now (the server wakes the player up and moves it next to the bed; the client stays
    /// asleep until then). `false` (nothing sent) when not asleep.
    pub fn leave_bed(&mut self) -> bool {
        let c = &mut *self.core;
        if c.sleeping.is_none() {
            return false;
        }
        c.out.push(Outbound::EntityAction {
            entity_id: c.entity_id,
            action: crate::common::EntityAction::LeaveBed,
        });
        true
    }

    /// Edits the book and quill in the main hand (or the off hand) as the vanilla book screen
    /// does when the pages are typed and Done is pressed (`title: None`), or Sign, the title
    /// and Finalize (`title: Some`): the pages and title go through the screen's filter and
    /// limits, the version's packet is written now (in call order, before this tick's
    /// movement packet) and the held stack changes as vanilla's does. See [`crate::book`].
    /// Vanilla opens the screen with a right click (the item use goes out first): anticheats
    /// such as Grim flag an edit without that use, and Paper kicks edits less than 20 ticks
    /// apart (`ghast_ext::Bot::edit_book` does the right click).
    ///
    /// ```no_run
    /// # fn f(ctx: &mut ghast_client::TickContext<'_>) {
    /// let _ = ctx.edit_book(false, &["Page one", "Page two"], Some("My book"));
    /// # }
    /// ```
    ///
    /// # Errors
    /// [`crate::book::BookError`]: no book and quill in that hand, too many pages, a blank
    /// title, the off hand on 1.8.9. Nothing is sent then.
    pub fn edit_book(
        &mut self,
        off_hand: bool,
        pages: &[&str],
        title: Option<&str>,
    ) -> Result<(), crate::book::BookError> {
        use crate::book::{BookEdit, BookError, BookRules};
        let c = &mut *self.core;
        let rules = c.opts.caps.book;
        if off_hand && rules == BookRules::Legacy18 {
            return Err(BookError::OffHand);
        }
        let (writable, written) =
            crate::book::book_items(c.opts.caps.data).ok_or(BookError::NoBook)?;
        let held = if off_hand {
            c.inv.offhand()
        } else {
            c.inv.held()
        }
        .filter(|s| s.id() == writable)
        .ok_or(BookError::NoBook)?
        .clone();
        let (pages, title) = crate::book::prepare(rules, pages, title)?;
        let slot = if off_hand {
            40
        } else {
            i32::from(c.inv.selected())
        };
        let (stack, after) = match rules {
            BookRules::Pages => {
                // Done updates the held book's content; Sign leaves it to the server
                #[cfg(ghast_modern)]
                let after = if title.is_none() {
                    crate::book::modern_stack(&held, &pages, c.opts.caps.protocol)
                } else {
                    None
                };
                #[cfg(not(ghast_modern))]
                let after = None;
                (None, after)
            }
            _ => {
                let s = crate::book::nbt_stack(
                    rules,
                    &held,
                    &pages,
                    title.as_deref(),
                    &c.opts.name,
                    written,
                );
                (Some(s.clone()), Some(s))
            }
        };
        if let Some(s) = after {
            c.inv.set_hand(off_hand, Some(s));
        }
        c.out.push(Outbound::EditBook(Box::new(BookEdit {
            slot,
            pages,
            title,
            stack,
        })));
        Ok(())
    }

    /// The dialog the server has open now (26.1+, only with [`Interests::DIALOGS`]; see
    /// [`crate::dialog`]).
    #[must_use]
    pub fn dialog(&self) -> Option<&crate::dialog::Dialog> {
        self.core.dialog.as_deref()
    }

    /// Dialogs the server showed and closed since the behaviour's previous tick, in arrival
    /// order (26.1+, only with [`Interests::DIALOGS`]; [`TickContext::dialog`] is the one open
    /// now). Like [`TickContext::events`], kept while the behaviour is on hold.
    #[must_use]
    pub fn dialog_events(&self) -> &[crate::dialog::DialogEvent] {
        &self.core.dialogs
    }

    /// Answers the open dialog the way vanilla does for that button (or Escape): the packets
    /// vanilla sends are written now, in call order with the other actions (`chat_command`
    /// for a command that needs no confirmation, `custom_click_action` for a custom action;
    /// client-only actions send nothing), and the dialog closes, stays or is replaced as its
    /// `after_action` and the action say.
    pub fn answer_dialog(
        &mut self,
        answer: &crate::dialog::DialogAnswer,
    ) -> Result<crate::dialog::DialogOutcome, crate::dialog::DialogRefused> {
        use crate::dialog::{CommandCheck, DialogOutcome, DialogRefused, DialogSent, Effect, Next};
        let d = self.core.dialog.clone().ok_or(DialogRefused::NoDialog)?;
        let (effect, mut next) = crate::dialog::resolve(&d, answer)?;
        let sent = match effect {
            Effect::Nothing => DialogSent::Nothing,
            Effect::Custom { id, payload } => {
                self.core.out.push(Outbound::CustomClickAction {
                    id: id.clone(),
                    payload: crate::dialog::payload_nbt(payload.as_ref()),
                });
                DialogSent::Custom(id)
            }
            Effect::Command(command) => match ((self.commands)(&command), answer.confirms()) {
                (CommandCheck::NoIssues, _)
                | (CommandCheck::ParseErrors | CommandCheck::PermissionsRequired, true) => {
                    self.core.out.push(Outbound::DialogCommand(command.clone()));
                    DialogSent::Command(command)
                }
                (CommandCheck::SignatureRequired, true) => {
                    // "Suggest command": the player sends it from the chat line.
                    self.core.out.push(Outbound::Chat(format!("/{command}")));
                    DialogSent::Command(command)
                }
                (check, _) => {
                    // The confirmation screen returns to the dialog when cancelled.
                    next = Next::Stay;
                    DialogSent::CommandHeld { command, check }
                }
            },
        };
        let (open, waiting) = match next {
            Next::Stay => (Some(d.clone()), false),
            Next::Closed => (None, false),
            Next::Waiting => (None, true),
            Next::Open(n) => (Some(n), false),
        };
        if let Some(n) = &open
            && !Arc::ptr_eq(n, &d)
        {
            self.core
                .dialogs_pending
                .push(crate::dialog::DialogEvent::Shown(n.clone()));
        }
        self.core.dialog = open.clone();
        Ok(DialogOutcome {
            sent,
            open,
            waiting,
        })
    }
}