tenebrous-dicebot/src/commands/basic_rolling.rs

55 lines
1.6 KiB
Rust
Raw Normal View History

use super::{Command, Execution, ExecutionResult};
use crate::basic::dice::ElementExpression;
use crate::basic::parser::parse_element_expression;
use crate::basic::roll::Roll;
2020-10-31 12:40:44 +00:00
use crate::context::Context;
use crate::error::BotError;
2020-10-31 12:40:44 +00:00
use async_trait::async_trait;
use nom::Err as NomErr;
use std::convert::TryFrom;
2020-10-31 12:40:44 +00:00
pub struct RollCommand(pub ElementExpression);
impl From<RollCommand> for Box<dyn Command> {
fn from(cmd: RollCommand) -> Self {
Box::new(cmd)
}
}
impl TryFrom<&str> for RollCommand {
type Error = BotError;
fn try_from(input: &str) -> Result<Self, Self::Error> {
let result = parse_element_expression(input);
match result {
Ok((rest, expression)) if rest.len() == 0 => Ok(RollCommand(expression)),
//"Legacy code boundary": translates Nom errors into BotErrors.
Ok(_) => Err(BotError::NomParserIncomplete),
Err(NomErr::Error(e)) => Err(BotError::NomParserError(e.1)),
Err(NomErr::Failure(e)) => Err(BotError::NomParserError(e.1)),
Err(NomErr::Incomplete(_)) => Err(BotError::NomParserIncomplete),
}
}
}
2020-10-31 12:40:44 +00:00
#[async_trait]
impl Command for RollCommand {
fn name(&self) -> &'static str {
"roll regular dice"
}
fn is_secure(&self) -> bool {
false
}
async fn execute(&self, _ctx: &Context<'_>) -> ExecutionResult {
2020-10-31 12:40:44 +00:00
let roll = self.0.roll();
let html = format!(
"<strong>Dice:</strong> {}</p><p><strong>Result</strong>: {}",
2020-10-31 12:40:44 +00:00
self.0, roll
);
Execution::success(html)
2020-10-31 12:40:44 +00:00
}
}