Moved insults and compliments into the db
+ Fmt
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
use crate::error::Error;
|
||||
use j_db::database::Database;
|
||||
use j_db::model::JdbModel;
|
||||
use rand::seq::SliceRandom;
|
||||
use rand::thread_rng;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use tera::{Context, Tera};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone, Eq, PartialEq)]
|
||||
pub enum ResponseType {
|
||||
Insult,
|
||||
Compliment,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct RandomResponseTemplate {
|
||||
id: Option<u64>,
|
||||
pub response_type: ResponseType,
|
||||
pub template: String,
|
||||
pub word_bank: HashMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
impl RandomResponseTemplate {
|
||||
pub fn render(&self, target: &str) -> Result<String, Error> {
|
||||
let mut context = Context::new();
|
||||
context.insert("target", target);
|
||||
|
||||
for (key, words) in &self.word_bank {
|
||||
context.insert(key, &words.choose(&mut thread_rng()).unwrap());
|
||||
}
|
||||
|
||||
Ok(Tera::one_off(&self.template, &context, false)?)
|
||||
}
|
||||
|
||||
pub fn get_all_responses_for_type(
|
||||
db: &Database,
|
||||
resp_type: ResponseType,
|
||||
) -> Result<Vec<Self>, Error> {
|
||||
Ok(db
|
||||
.filter(|_, random_response: &RandomResponseTemplate| {
|
||||
random_response.response_type == resp_type
|
||||
})?
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn get_random_response(
|
||||
db: &Database,
|
||||
resp_type: ResponseType,
|
||||
target: &str,
|
||||
) -> Result<Option<String>, Error> {
|
||||
let templates = Self::get_all_responses_for_type(db, resp_type)?;
|
||||
let template = templates.choose(&mut thread_rng());
|
||||
|
||||
if let Some(template) = template {
|
||||
Ok(Some(template.render(target)?))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JdbModel for RandomResponseTemplate {
|
||||
fn id(&self) -> Option<u64> {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn set_id(&mut self, id: u64) {
|
||||
self.id = Some(id)
|
||||
}
|
||||
|
||||
fn tree() -> String {
|
||||
"RandomResponseTemplate".to_string()
|
||||
}
|
||||
}
|
||||
@@ -1 +1,2 @@
|
||||
pub mod insult_compliment;
|
||||
pub mod random;
|
||||
|
||||
Reference in New Issue
Block a user