tenebrous-dicebot/src/bot/mod.rs

249 lines
7.9 KiB
Rust

use crate::commands::{execute_command, ExecutionError, ExecutionResult, ResponseExtractor};
use crate::config::*;
use crate::context::{Context, RoomContext};
use crate::db::sqlite::Database;
use crate::db::DbState;
use crate::error::BotError;
use crate::matrix;
use crate::state::DiceBotState;
use dirs;
use futures::stream::{self, StreamExt};
use log::{error, info};
use matrix_sdk::{self, identifiers::EventId, room::Joined, Client, ClientConfig, SyncSettings};
use std::clone::Clone;
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use url::Url;
pub mod event_handlers;
/// How many commands can be in one message. If the amount is higher
/// than this, we reject execution.
const MAX_COMMANDS_PER_MESSAGE: usize = 50;
/// The DiceBot struct represents an active dice bot. The bot is not
/// connected to Matrix until its run() function is called.
pub struct DiceBot {
/// A reference to the configuration read in on application start.
config: Arc<Config>,
/// The matrix client.
client: Client,
/// State of the dicebot
state: Arc<RwLock<DiceBotState>>,
/// Active database layer
db: Database,
}
fn cache_dir() -> Result<PathBuf, BotError> {
let mut dir = dirs::cache_dir().ok_or(BotError::NoCacheDirectoryError)?;
dir.push("matrix-dicebot");
Ok(dir)
}
/// Creates the matrix client.
fn create_client(config: &Config) -> Result<Client, BotError> {
let cache_dir = cache_dir()?;
//let store = JsonStore::open(&cache_dir)?;
let client_config = ClientConfig::new().store_path(cache_dir);
let homeserver_url = Url::parse(&config.matrix_homeserver())?;
Ok(Client::new_with_config(homeserver_url, client_config)?)
}
/// Handle responding to a single command being executed. Wil print
/// out the full result of that command.
async fn handle_single_result(
client: &Client,
cmd_result: &ExecutionResult,
respond_to: &str,
room: &Joined,
event_id: EventId,
) {
if cmd_result.is_err() {
error!(
"Command execution error: {}",
cmd_result.as_ref().err().unwrap()
);
}
let html = cmd_result.message_html(respond_to);
matrix::send_message(client, room.room_id(), &html, Some(event_id)).await;
}
/// Handle responding to multiple commands being executed. Will print
/// out how many commands succeeded and failed (if any failed).
async fn handle_multiple_results(
client: &Client,
results: &[(String, ExecutionResult)],
respond_to: &str,
room: &Joined,
) {
let respond_to = format!(
"<a href=\"https://matrix.to/#/{}\">{}</a>",
respond_to, respond_to
);
let errors: Vec<(&str, &ExecutionError)> = results
.into_iter()
.filter_map(|(cmd, result)| match result {
Err(e) => Some((cmd.as_ref(), e)),
_ => None,
})
.collect();
for result in errors.iter() {
error!("Command execution error: '{}' - {}", result.0, result.1);
}
let message = if errors.len() == 0 {
format!("{}: Executed {} commands", respond_to, results.len())
} else {
let failures: Vec<String> = errors
.iter()
.map(|&(cmd, err)| format!("<strong>{}:</strong> {}", cmd, err))
.collect();
format!(
"{}: Executed {} commands ({} failed)\n\nFailures:\n{}",
respond_to,
results.len(),
errors.len(),
failures.join("\n")
)
.replace("\n", "<br/>")
};
matrix::send_message(client, room.room_id(), &message, None).await;
}
impl DiceBot {
/// Create a new dicebot with the given configuration and state
/// actor. This function returns a Result because it is possible
/// for client creation to fail for some reason (e.g. invalid
/// homeserver URL).
pub fn new(
config: &Arc<Config>,
state: &Arc<RwLock<DiceBotState>>,
db: &Database,
) -> Result<Self, BotError> {
Ok(DiceBot {
client: create_client(&config)?,
config: config.clone(),
state: state.clone(),
db: db.clone(),
})
}
/// Logs in to matrix and potentially records a new device ID. If
/// no device ID is found in the database, a new one will be
/// generated by the matrix SDK, and we will store it.
async fn login(&self, client: &Client) -> Result<(), BotError> {
let username = self.config.matrix_username();
let password = self.config.matrix_password();
// Pull device ID from database, if it exists. Then write it
// to DB if the library generated one for us.
let device_id: Option<String> = self.db.get_device_id().await?;
let device_id: Option<&str> = device_id.as_deref();
client
.login(username, password, device_id, Some("matrix dice bot"))
.await?;
if device_id.is_none() {
let device_id = client.device_id().await.ok_or(BotError::NoDeviceIdFound)?;
self.db.set_device_id(device_id.as_str()).await?;
info!("Recorded new device ID: {}", device_id.as_str());
} else {
info!("Using existing device ID: {}", device_id.unwrap());
}
info!("Logged in as {}", username);
Ok(())
}
/// Logs the bot in to Matrix and listens for events until program
/// terminated, or a panic occurs. Originally adapted from the
/// matrix-rust-sdk command bot example.
pub async fn run(self) -> Result<(), BotError> {
let client = self.client.clone();
self.login(&client).await?;
client.set_event_handler(Box::new(self)).await;
info!("Listening for commands");
// TODO replace with sync_with_callback for cleaner shutdown
// process.
client.sync(SyncSettings::default()).await;
Ok(())
}
async fn execute_commands(
&self,
room: &Joined,
sender_username: &str,
msg_body: &str,
) -> Vec<(String, ExecutionResult)> {
let room_name: &str = &room.display_name().await.ok().unwrap_or_default();
let commands: Vec<&str> = msg_body
.lines()
.filter(|line| line.starts_with("!"))
.take(MAX_COMMANDS_PER_MESSAGE + 1)
.collect();
//Up to 50 commands allowed, otherwise we send back an error.
let results: Vec<(String, ExecutionResult)> = if commands.len() < MAX_COMMANDS_PER_MESSAGE {
stream::iter(commands)
.then(|command| async move {
let ctx = Context {
db: self.db.clone(),
matrix_client: &self.client,
room: RoomContext::new_with_name(&room, room_name),
username: &sender_username,
message_body: &command,
};
let cmd_result = execute_command(&ctx).await;
info!("[{}] {} executed: {}", room_name, sender_username, command);
(command.to_owned(), cmd_result)
})
.collect()
.await
} else {
vec![(
"".to_owned(),
Err(ExecutionError(BotError::MessageTooLarge)),
)]
};
results
}
pub async fn handle_results(
&self,
room: &Joined,
sender_username: &str,
event_id: EventId,
results: Vec<(String, ExecutionResult)>,
) {
if results.len() >= 1 {
if results.len() == 1 {
handle_single_result(
&self.client,
&results[0].1,
sender_username,
&room,
event_id,
)
.await;
} else if results.len() > 1 {
handle_multiple_results(&self.client, &results, sender_username, &room).await;
}
}
}
}