Skip to main content

azalea_client/plugins/client_chat/
mod.rs

1//! Implementations of chat-related features.
2
3pub mod handler;
4
5use std::sync::Arc;
6
7use azalea_chat::FormattedText;
8use azalea_protocol::packets::game::{
9    c_disguised_chat::ClientboundDisguisedChat, c_player_chat::ClientboundPlayerChat,
10    c_system_chat::ClientboundSystemChat,
11};
12use bevy_app::{App, Plugin, Update};
13use bevy_ecs::prelude::*;
14use handler::{SendChatKindEvent, handle_send_chat_kind_event};
15use uuid::Uuid;
16
17pub struct ChatPlugin;
18impl Plugin for ChatPlugin {
19    fn build(&self, app: &mut App) {
20        app.add_message::<SendChatEvent>()
21            .add_message::<SendChatKindEvent>()
22            .add_message::<ChatReceivedEvent>()
23            .add_systems(
24                Update,
25                (handle_send_chat_event, handle_send_chat_kind_event).chain(),
26            );
27    }
28}
29
30/// A chat packet, either a system message or a chat message.
31#[derive(Clone, Debug, PartialEq)]
32pub enum ChatPacket {
33    System(Arc<ClientboundSystemChat>),
34    Player(Arc<ClientboundPlayerChat>),
35    Disguised(Arc<ClientboundDisguisedChat>),
36}
37
38macro_rules! regex {
39    ($re:literal $(,)?) => {{
40        static RE: std::sync::LazyLock<regex::Regex> =
41            std::sync::LazyLock::new(|| regex::Regex::new($re).unwrap());
42        &RE
43    }};
44}
45
46impl ChatPacket {
47    /// Get the message shown in chat for this packet.
48    ///
49    /// See [`Self::split_sender_and_content`] for more details about how this
50    /// works.
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    /// A convenience function to determine the username of the sender and
60    /// the content of a chat message.
61    ///
62    /// This does not preserve formatting codes.
63    ///
64    /// This function uses a few checks to attempt to split the chat message,
65    /// and is intended to work on most servers. It won't work for every server
66    /// though, so in certain cases you may have to reimplement this yourself.
67    ///
68    /// If it's not a player-sent chat message or the sender couldn't be
69    /// determined, the username part will be None.
70    ///
71    /// Also see [`Self::sender`] and [`Self::content`] if you only need one of
72    /// the parts.
73    pub fn split_sender_and_content(&self) -> (Option<String>, String) {
74        match self {
75            ChatPacket::System(p) => {
76                let message = p.content.to_string();
77                // overlay messages aren't in chat
78                if p.overlay {
79                    return (None, message);
80                }
81
82                // it's a system message, so we'll have to match the content
83                // with regex
84
85                // username surrounded by angle brackets (vanilla-like chat),
86                // and allow username prefixes like [Owner]
87                if let Some(m) = regex!(r"^<(?:\[[^\]]+?\] )?(\w{1,16})> (.+)$").captures(&message)
88                {
89                    return (Some(m[1].to_string()), m[2].to_string());
90                }
91                // username surrounded by square brackets (essentials whispers,
92                // vanilla-like /say), and allow username
93                // prefixes
94                if let Some(m) =
95                    regex!(r"^\[(?:\[[^\]]+?\] )?(\w{1,16})(?: -> me)?\] (.+)$").captures(&message)
96                {
97                    return (Some(m[1].to_string()), m[2].to_string());
98                }
99                // username without angle brackets (2b2t whispers, vanilla-like
100                // whispers)
101                if let Some(m) =
102                    regex!(r"^(\w{1,16}) whispers(?: to you)?: (.+)$").captures(&message)
103                {
104                    return (Some(m[1].to_string()), m[2].to_string());
105                }
106                // hypixel whispers
107                if let Some(m) =
108                    regex!(r"^From (?:\[[^\]]+\] )(\w{1,16}): (.+)$").captures(&message)
109                {
110                    return (Some(m[1].to_string()), m[2].to_string());
111                }
112
113                (None, message)
114            }
115            ChatPacket::Player(p) => (
116                // If it's a player chat packet, then the sender and content
117                // are already split for us.
118                Some(p.chat_type.name.to_string()),
119                p.body.content.clone(),
120            ),
121            ChatPacket::Disguised(p) => (
122                // disguised chat packets are basically the same as player chat
123                // packets but without the chat signing things
124                Some(p.chat_type.name.to_string()),
125                p.message.to_string(),
126            ),
127        }
128    }
129
130    /// Get the username of the sender of the message.
131    ///
132    /// If it's not a player-sent chat message or the sender couldn't be
133    /// determined, this will be None.
134    ///
135    /// See [`Self::split_sender_and_content`] for more details about how this
136    /// works.
137    pub fn sender(&self) -> Option<String> {
138        self.split_sender_and_content().0
139    }
140
141    /// Get the UUID of the sender of the message.
142    ///
143    /// If it's not a player-sent chat message, this will be None (this is
144    /// sometimes the case when a server uses a plugin to modify chat
145    /// messages).
146    pub fn sender_uuid(&self) -> Option<Uuid> {
147        match self {
148            ChatPacket::System(_) => None,
149            ChatPacket::Player(m) => Some(m.sender),
150            ChatPacket::Disguised(_) => None,
151        }
152    }
153
154    /// Get the content part of the message as a string.
155    ///
156    /// This does not preserve formatting codes. If it's not a player-sent chat
157    /// message or the sender couldn't be determined, this will contain the
158    /// entire message.
159    pub fn content(&self) -> String {
160        self.split_sender_and_content().1
161    }
162
163    /// Create a new `ChatPacket` from a string. This is meant to be used as a
164    /// convenience function for testing.
165    pub fn new(message: &str) -> Self {
166        ChatPacket::System(Arc::new(ClientboundSystemChat {
167            content: FormattedText::from(message),
168            overlay: false,
169        }))
170    }
171
172    /// Whether this message is an incoming whisper message (i.e. someone else
173    /// messaged the bot with /msg).
174    ///
175    /// This is not guaranteed to work correctly on custom servers.
176    pub fn is_whisper(&self) -> bool {
177        match self {
178            ChatPacket::System(p) => {
179                let message = p.content.to_string();
180                if p.overlay {
181                    return false;
182                }
183                if regex!(r"^(-> me|\w{1,16} whispers: )").is_match(&message) {
184                    return true;
185                }
186                // hypixel
187                if regex!(r"^From (?:\[[^\]]+\] )?\w{1,16}: ").is_match(&message) {
188                    return true;
189                }
190
191                false
192            }
193            _ => match self.message() {
194                FormattedText::Translatable(t) => t.key == "commands.message.display.incoming",
195                _ => false,
196            },
197        }
198    }
199}
200
201/// A client received a chat message packet.
202#[derive(Clone, Debug, Message)]
203pub struct ChatReceivedEvent {
204    pub entity: Entity,
205    pub packet: ChatPacket,
206}
207
208/// Send a chat message (or command, if it starts with a slash) to the server.
209#[derive(Message)]
210pub struct SendChatEvent {
211    pub entity: Entity,
212    pub content: String,
213}
214
215pub fn handle_send_chat_event(
216    mut events: MessageReader<SendChatEvent>,
217    mut send_chat_kind_events: MessageWriter<SendChatKindEvent>,
218) {
219    for event in events.read() {
220        if event.content.starts_with('/') {
221            send_chat_kind_events.write(SendChatKindEvent {
222                entity: event.entity,
223                content: event.content[1..].to_string(),
224                kind: ChatKind::Command,
225            });
226        } else {
227            send_chat_kind_events.write(SendChatKindEvent {
228                entity: event.entity,
229                content: event.content.clone(),
230                kind: ChatKind::Message,
231            });
232        }
233    }
234}
235
236/// A kind of chat packet, either a chat message or a command.
237pub enum ChatKind {
238    Message,
239    Command,
240}
241
242// TODO
243// MessageSigner, ChatMessageContent, LastSeenMessages
244// fn sign_message() -> MessageSignature {
245//     MessageSignature::default()
246// }