diff --git a/dicebot/src/bot/event_handlers.rs b/dicebot/src/bot/event_handlers.rs index 03b0b5a..4b4f4ca 100644 --- a/dicebot/src/bot/event_handlers.rs +++ b/dicebot/src/bot/event_handlers.rs @@ -5,11 +5,11 @@ use crate::error::BotError; use log::{debug, error, info, warn}; use matrix_sdk::ruma::events::room::member::RoomMemberEventContent; use matrix_sdk::ruma::events::{StrippedStateEvent, SyncMessageLikeEvent}; -use matrix_sdk::{Client, DisplayName}; use matrix_sdk::{self, room::Room, ruma::events::room::message::RoomMessageEventContent}; +use matrix_sdk::{Client, DisplayName}; use std::ops::Sub; -use std::time::{Duration, SystemTime}; use std::time::UNIX_EPOCH; +use std::time::{Duration, SystemTime}; /// Check if a message is recent enough to actually process. If the /// message is within "oldest_message_age" seconds, this function @@ -67,7 +67,23 @@ async fn should_process_message<'a>( .map(str::to_string) .unwrap_or_else(|| String::new()); - let sender_username: String = format!("@{}:{}", event.sender().localpart(), event.sender().server_name()); + let sender_username: String = format!( + "@{}:{}", + event.sender().localpart(), + event.sender().server_name() + ); + + // Do not process messages from the bot itself. Otherwise it might + // try to execute its own commands. + let bot_username = bot + .client + .user_id() + .map(|u| format!("@{}:{}", u.localpart(), u.server_name())) + .unwrap_or_default(); + + if sender_username == bot_username { + return Err(BotError::ShouldNotProcessError); + } Ok((msg_body, sender_username)) } @@ -100,7 +116,10 @@ pub(super) async fn on_stripped_state_member( info!( "Autojoining room {}", - room.display_name().await.ok().unwrap_or_else(|| DisplayName::Named("[error]".to_string())) + room.display_name() + .await + .ok() + .unwrap_or_else(|| DisplayName::Named("[error]".to_string())) ); if let Err(e) = client.join_room_by_id(&room.room_id()).await { @@ -134,6 +153,11 @@ pub(super) async fn on_room_message( .execute_commands(&room, &sender_username, &msg_body) .await; - bot.handle_results(&room, &sender_username, event.event_id().to_owned(), results) - .await; + bot.handle_results( + &room, + &sender_username, + event.event_id().to_owned(), + results, + ) + .await; }