azalea_client/
chat.rs

1//! Implementations of chat-related features.
2
3use std::{
4    sync::Arc,
5    time::{SystemTime, UNIX_EPOCH},
6};
7
8use azalea_chat::FormattedText;
9use azalea_protocol::packets::{
10    game::{
11        c_disguised_chat::ClientboundDisguisedChat,
12        c_player_chat::ClientboundPlayerChat,
13        c_system_chat::ClientboundSystemChat,
14        s_chat::{LastSeenMessagesUpdate, ServerboundChat},
15        s_chat_command::ServerboundChatCommand,
16    },
17    Packet,
18};
19use bevy_app::{App, Plugin, Update};
20use bevy_ecs::{
21    entity::Entity,
22    event::{EventReader, EventWriter},
23    prelude::Event,
24    schedule::IntoSystemConfigs,
25};
26use uuid::Uuid;
27
28use crate::{
29    client::Client,
30    packet_handling::game::{handle_send_packet_event, SendPacketEvent},
31};
32
33/// A chat packet, either a system message or a chat message.
34#[derive(Debug, Clone, PartialEq)]
35pub enum ChatPacket {
36    System(Arc<ClientboundSystemChat>),
37    Player(Arc<ClientboundPlayerChat>),
38    Disguised(Arc<ClientboundDisguisedChat>),
39}
40
41macro_rules! regex {
42    ($re:literal $(,)?) => {{
43        static RE: std::sync::LazyLock<regex::Regex> =
44            std::sync::LazyLock::new(|| regex::Regex::new($re).unwrap());
45        &RE
46    }};
47}
48
49impl ChatPacket {
50    /// Get the message shown in chat for this packet.
51    pub fn message(&self) -> FormattedText {
52        match self {
53            ChatPacket::System(p) => p.content.clone(),
54            ChatPacket::Player(p) => p.message(),
55            ChatPacket::Disguised(p) => p.message(),
56        }
57    }
58
59    /// Determine the username of the sender and content of the message. This
60    /// does not preserve formatting codes. If it's not a player-sent chat
61    /// message or the sender couldn't be determined, the username part will be
62    /// None.
63    pub fn split_sender_and_content(&self) -> (Option<String>, String) {
64        match self {
65            ChatPacket::System(p) => {
66                let message = p.content.to_string();
67                // Overlay messages aren't in chat
68                if p.overlay {
69                    return (None, message);
70                }
71                // It's a system message, so we'll have to match the content
72                // with regex
73                if let Some(m) = regex!("^<([a-zA-Z_0-9]{1,16})> (.+)$").captures(&message) {
74                    return (Some(m[1].to_string()), m[2].to_string());
75                }
76
77                (None, message)
78            }
79            ChatPacket::Player(p) => (
80                // If it's a player chat packet, then the sender and content
81                // are already split for us.
82                Some(p.chat_type.name.to_string()),
83                p.body.content.clone(),
84            ),
85            ChatPacket::Disguised(p) => (
86                // disguised chat packets are basically the same as player chat packets but without
87                // the chat signing things
88                Some(p.chat_type.name.to_string()),
89                p.message.to_string(),
90            ),
91        }
92    }
93
94    /// Get the username of the sender of the message. If it's not a
95    /// player-sent chat message or the sender couldn't be determined, this
96    /// will be None.
97    pub fn username(&self) -> Option<String> {
98        self.split_sender_and_content().0
99    }
100
101    /// Get the UUID of the sender of the message. If it's not a
102    /// player-sent chat message, this will be None (this is sometimes the case
103    /// when a server uses a plugin to modify chat messages).
104    pub fn uuid(&self) -> Option<Uuid> {
105        match self {
106            ChatPacket::System(_) => None,
107            ChatPacket::Player(m) => Some(m.sender),
108            ChatPacket::Disguised(_) => None,
109        }
110    }
111
112    /// Get the content part of the message as a string. This does not preserve
113    /// formatting codes. If it's not a player-sent chat message or the sender
114    /// couldn't be determined, this will contain the entire message.
115    pub fn content(&self) -> String {
116        self.split_sender_and_content().1
117    }
118
119    /// Create a new Chat from a string. This is meant to be used as a
120    /// convenience function for testing.
121    pub fn new(message: &str) -> Self {
122        ChatPacket::System(Arc::new(ClientboundSystemChat {
123            content: FormattedText::from(message),
124            overlay: false,
125        }))
126    }
127
128    /// Whether this message was sent with /msg (or aliases). It works by
129    /// checking the translation key, so it won't work on servers that use their
130    /// own whisper system.
131    pub fn is_whisper(&self) -> bool {
132        match self.message() {
133            FormattedText::Text(_) => false,
134            FormattedText::Translatable(t) => t.key == "commands.message.display.incoming",
135        }
136    }
137}
138
139impl Client {
140    /// Send a chat message to the server. This only sends the chat packet and
141    /// not the command packet, which means on some servers you can use this to
142    /// send chat messages that start with a `/`. The [`Client::chat`] function
143    /// handles checking whether the message is a command and using the
144    /// proper packet for you, so you should use that instead.
145    pub fn send_chat_packet(&self, message: &str) {
146        self.ecs.lock().send_event(SendChatKindEvent {
147            entity: self.entity,
148            content: message.to_string(),
149            kind: ChatKind::Message,
150        });
151        self.run_schedule_sender.send(()).unwrap();
152    }
153
154    /// Send a command packet to the server. The `command` argument should not
155    /// include the slash at the front.
156    pub fn send_command_packet(&self, command: &str) {
157        self.ecs.lock().send_event(SendChatKindEvent {
158            entity: self.entity,
159            content: command.to_string(),
160            kind: ChatKind::Command,
161        });
162        self.run_schedule_sender.send(()).unwrap();
163    }
164
165    /// Send a message in chat.
166    ///
167    /// ```rust,no_run
168    /// # use azalea_client::{Client, Event};
169    /// # async fn handle(bot: Client, event: Event) -> anyhow::Result<()> {
170    /// bot.chat("Hello, world!");
171    /// # Ok(())
172    /// # }
173    /// ```
174    pub fn chat(&self, content: &str) {
175        self.ecs.lock().send_event(SendChatEvent {
176            entity: self.entity,
177            content: content.to_string(),
178        });
179        self.run_schedule_sender.send(()).unwrap();
180    }
181}
182
183pub struct ChatPlugin;
184impl Plugin for ChatPlugin {
185    fn build(&self, app: &mut App) {
186        app.add_event::<SendChatEvent>()
187            .add_event::<SendChatKindEvent>()
188            .add_event::<ChatReceivedEvent>()
189            .add_systems(
190                Update,
191                (
192                    handle_send_chat_event,
193                    handle_send_chat_kind_event.after(handle_send_packet_event),
194                )
195                    .chain(),
196            );
197    }
198}
199
200/// A client received a chat message packet.
201#[derive(Event, Debug, Clone)]
202pub struct ChatReceivedEvent {
203    pub entity: Entity,
204    pub packet: ChatPacket,
205}
206
207/// Send a chat message (or command, if it starts with a slash) to the server.
208#[derive(Event)]
209pub struct SendChatEvent {
210    pub entity: Entity,
211    pub content: String,
212}
213
214pub fn handle_send_chat_event(
215    mut events: EventReader<SendChatEvent>,
216    mut send_chat_kind_events: EventWriter<SendChatKindEvent>,
217) {
218    for event in events.read() {
219        if event.content.starts_with('/') {
220            send_chat_kind_events.send(SendChatKindEvent {
221                entity: event.entity,
222                content: event.content[1..].to_string(),
223                kind: ChatKind::Command,
224            });
225        } else {
226            send_chat_kind_events.send(SendChatKindEvent {
227                entity: event.entity,
228                content: event.content.clone(),
229                kind: ChatKind::Message,
230            });
231        }
232    }
233}
234
235/// Send a chat packet to the server of a specific kind (chat message or
236/// command). Usually you just want [`SendChatEvent`] instead.
237///
238/// Usually setting the kind to `Message` will make it send a chat message even
239/// if it starts with a slash, but some server implementations will always do a
240/// command if it starts with a slash.
241///
242/// If you're wondering why this isn't two separate events, it's so ordering is
243/// preserved if multiple chat messages and commands are sent at the same time.
244#[derive(Event)]
245pub struct SendChatKindEvent {
246    pub entity: Entity,
247    pub content: String,
248    pub kind: ChatKind,
249}
250
251/// A kind of chat packet, either a chat message or a command.
252pub enum ChatKind {
253    Message,
254    Command,
255}
256
257pub fn handle_send_chat_kind_event(
258    mut events: EventReader<SendChatKindEvent>,
259    mut send_packet_events: EventWriter<SendPacketEvent>,
260) {
261    for event in events.read() {
262        let content = event
263            .content
264            .chars()
265            .filter(|c| !matches!(c, '\x00'..='\x1F' | '\x7F' | 'ยง'))
266            .take(256)
267            .collect::<String>();
268        let packet = match event.kind {
269            ChatKind::Message => ServerboundChat {
270                message: content,
271                timestamp: SystemTime::now()
272                    .duration_since(UNIX_EPOCH)
273                    .expect("Time shouldn't be before epoch")
274                    .as_millis()
275                    .try_into()
276                    .expect("Instant should fit into a u64"),
277                salt: azalea_crypto::make_salt(),
278                signature: None,
279                last_seen_messages: LastSeenMessagesUpdate::default(),
280            }
281            .into_variant(),
282            ChatKind::Command => {
283                // TODO: chat signing
284                ServerboundChatCommand { command: content }.into_variant()
285            }
286        };
287
288        send_packet_events.send(SendPacketEvent::new(event.entity, packet));
289    }
290}
291
292// TODO
293// MessageSigner, ChatMessageContent, LastSeenMessages
294// fn sign_message() -> MessageSignature {
295//     MessageSignature::default()
296// }