tenebrous-dicebot/src/commands.rs

95 lines
2.3 KiB
Rust
Raw Normal View History

use crate::context::Context;
2020-10-17 15:47:17 +00:00
use async_trait::async_trait;
use thiserror::Error;
2020-04-21 06:09:43 +00:00
2020-10-31 12:40:44 +00:00
pub mod basic_rolling;
pub mod cofd;
pub mod cthulhu;
pub mod management;
2020-10-31 12:40:44 +00:00
pub mod misc;
pub mod parser;
2020-10-31 12:40:44 +00:00
pub mod variables;
#[derive(Error, Debug)]
pub enum CommandError {
#[error("invalid command: {0}")]
InvalidCommand(String),
#[error("ignored command")]
IgnoredCommand,
}
2020-04-21 06:07:03 +00:00
pub struct Execution {
plain: String,
html: String,
}
2020-04-21 06:07:03 +00:00
impl Execution {
pub fn plain(&self) -> &str {
&self.plain
}
2020-04-21 06:07:03 +00:00
pub fn html(&self) -> &str {
&self.html
}
}
2020-10-17 15:47:17 +00:00
#[async_trait]
pub trait Command: Send + Sync {
async fn execute(&self, ctx: &Context<'_>) -> Execution;
fn name(&self) -> &'static str;
2020-04-21 06:07:03 +00:00
}
#[derive(Debug)]
pub struct CommandResult {
pub plain: String,
pub html: String,
}
/// Attempt to execute a command, and return the content that should
/// go back to Matrix, if the command was executed (successfully or
/// not). If a command is determined to be ignored, this function will
/// return None, signifying that we should not send a response.
2020-11-12 21:05:14 +00:00
pub async fn execute_command(ctx: &Context<'_>) -> CommandResult {
let res = parser::parse_command(&ctx.message_body);
let (plain, html) = match res {
2020-10-17 15:47:17 +00:00
Ok(cmd) => {
let execution = cmd.execute(ctx).await;
(execution.plain().into(), execution.html().into())
}
Err(e) => {
let message = format!("Error parsing command: {}", e);
let html_message = format!("<p><strong>{}</strong></p>", message);
(message, html_message)
}
};
let plain = format!("{}\n{}", ctx.username, plain);
let html = format!("<p>{}</p>\n{}", ctx.username, html);
2020-11-12 21:05:14 +00:00
CommandResult {
plain: plain,
html: html,
2020-11-12 21:05:14 +00:00
}
}
#[cfg(test)]
mod tests {
use super::*;
2020-11-12 21:05:14 +00:00
#[tokio::test]
async fn unrecognized_command() {
let db = crate::db::Database::new_temp().unwrap();
2020-11-22 20:52:44 +00:00
let ctx = Context {
db: db,
matrix_client: &matrix_sdk::Client::new("http://example.com").unwrap(),
room_id: "myroomid",
username: "myusername",
message_body: "!notacommand",
};
2020-11-12 21:05:14 +00:00
let result = execute_command(&ctx).await;
assert!(result.plain.contains("Error"));
}
}