feat: Add /nick command usage instruction and broadcast username changes

This commit enhances the chat application by:
- Adding a startup message to inform users about the  command for changing usernames.
- Modifying the  command to broadcast username changes to the chat, using the structured MQTT message format.
This commit is contained in:
2025-07-14 15:26:20 -04:00
parent 549070d3e9
commit c96e6dd408

View File

@@ -27,6 +27,7 @@ impl App {
fn new(username: String) -> App { fn new(username: String) -> App {
let mut messages = Vec::new(); let mut messages = Vec::new();
messages.push(("System".to_string(), format!("Welcome to the chat, {}!", username))); messages.push(("System".to_string(), format!("Welcome to the chat, {}!", username)));
messages.push(("System".to_string(), "To change your username, type /nick <new_username>".to_string()));
App { App {
messages, messages,
input: String::new(), input: String::new(),
@@ -121,9 +122,20 @@ async fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> io::Re
KeyCode::Enter => { KeyCode::Enter => {
let message_text = app.input.drain(..).collect::<String>(); let message_text = app.input.drain(..).collect::<String>();
if message_text.starts_with("/nick ") { if message_text.starts_with("/nick ") {
let old_username = app.username.clone();
let new_username = message_text.split_whitespace().nth(1).unwrap_or(&app.username).to_string(); let new_username = message_text.split_whitespace().nth(1).unwrap_or(&app.username).to_string();
app.username = new_username; app.username = new_username.clone();
app.messages.push(("System".to_string(), format!("Username changed to: {}", app.username))); app.messages.push(("System".to_string(), format!("Username changed to: {}", app.username)));
let chat_message = ChatMessage {
username: old_username,
message: format!("has changed their name to {}", new_username),
};
let payload = serde_json::to_string(&chat_message).unwrap();
client_clone
.publish("chat/msg", QoS::AtMostOnce, false, payload.as_bytes())
.await
.unwrap();
} else { } else {
let chat_message = ChatMessage { let chat_message = ChatMessage {
username: app.username.clone(), username: app.username.clone(),