From 2f7954632d0d1c7257bb0016f4b95c33ddb5a00c Mon Sep 17 00:00:00 2001 From: Joey Hines Date: Sat, 13 Apr 2024 14:54:23 -0600 Subject: [PATCH] Updated motivations to use new randoms + Handle task failures more gracefully --- Cargo.lock | 2 +- Cargo.toml | 2 +- src/discord/birthday.rs | 4 +- src/discord/motivate.rs | 37 +----------------- .../migration_5_update_motivation.rs | 38 +++++++++++++++++++ src/migrations/mod.rs | 10 ++++- src/models/motivation.rs | 34 +++++------------ src/models/random.rs | 2 +- src/models/task.rs | 15 +++++++- src/user/mod.rs | 2 +- 10 files changed, 76 insertions(+), 70 deletions(-) create mode 100644 src/migrations/migration_5_update_motivation.rs diff --git a/Cargo.lock b/Cargo.lock index a0a95f0..65bf328 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -787,7 +787,7 @@ dependencies = [ [[package]] name = "fren" -version = "0.6.0" +version = "0.7.0" dependencies = [ "axum", "axum-macros", diff --git a/Cargo.toml b/Cargo.toml index 4c2ba95..15d357d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fren" -version = "0.6.0" +version = "0.7.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/src/discord/birthday.rs b/src/discord/birthday.rs index 3261189..874826f 100644 --- a/src/discord/birthday.rs +++ b/src/discord/birthday.rs @@ -79,9 +79,9 @@ pub async fn list_birthdays(ctx: &Context, msg: &Message) -> CommandResult { msg_builder.push_bold_line("All the birthdays I know:"); for birthday in birthdays { let user_id = UserId::from(birthday.discord_id); - + let user = user_id.to_user(&ctx.http).await?; - + msg_builder.push_line(format!( "* {} {}", user.name, diff --git a/src/discord/motivate.rs b/src/discord/motivate.rs index 1ee9fe5..7834331 100644 --- a/src/discord/motivate.rs +++ b/src/discord/motivate.rs @@ -10,12 +10,7 @@ use serenity::model::channel::Message; use std::borrow::Cow; #[group] -#[commands( - motivation, - motivation_add_album, - motivation_add_action, - motivation_add_goal -)] +#[commands(motivation, motivation_add_album)] pub struct Motivate; pub async fn create_motivation_image(motivation: Motivation) -> Result, CommandError> { @@ -132,33 +127,3 @@ async fn motivation_add_album(ctx: &Context, msg: &Message, args: Args) -> Comma Ok(()) } - -#[command] -#[description("Add an action to the motivation generator")] -async fn motivation_add_action(ctx: &Context, msg: &Message, args: Args) -> CommandResult { - let data = ctx.data.read().await; - let global_data = data.get::().unwrap(); - - let action = args.rest(); - - MotivationConfig::add_action(&global_data.db, action)?; - - msg.reply(&ctx.http, "Done ;)").await?; - - Ok(()) -} - -#[command] -#[description("Add goal to the motivation generator")] -async fn motivation_add_goal(ctx: &Context, msg: &Message, args: Args) -> CommandResult { - let data = ctx.data.read().await; - let global_data = data.get::().unwrap(); - - let goal = args.rest(); - - MotivationConfig::add_goal(&global_data.db, goal)?; - - msg.reply(&ctx.http, "Done ;)").await?; - - Ok(()) -} diff --git a/src/migrations/migration_5_update_motivation.rs b/src/migrations/migration_5_update_motivation.rs new file mode 100644 index 0000000..c5c63e8 --- /dev/null +++ b/src/migrations/migration_5_update_motivation.rs @@ -0,0 +1,38 @@ +use crate::models::motivation::{ACTION_RANDOM_GROUP, GOAL_RANDOM_GROUP}; +use crate::models::random::RandomConfig; +use j_db::database::Database; +use j_db::migration::Migration; + +pub struct Migration5UpdateMotivation {} + +impl Migration for Migration5UpdateMotivation { + fn up(&self, db: &Database) -> j_db::error::Result<()> { + let tree = db.db.open_tree("Motivation")?; + let (id, config_bytes) = tree.first()?.unwrap(); + + let mut config = json::parse(std::str::from_utf8(&config_bytes).unwrap()).unwrap(); + + for action in config["action"].members() { + RandomConfig::add_random(db, ACTION_RANDOM_GROUP, &action.to_string()).ok(); + } + + for goal in config["goal"].members() { + RandomConfig::add_random(db, GOAL_RANDOM_GROUP, &goal.to_string()).ok(); + } + + config.remove("action"); + config.remove("goal"); + + tree.insert(id, config.to_string().into_bytes()).unwrap(); + + Ok(()) + } + + fn down(&self, _db: &Database) -> j_db::error::Result<()> { + Ok(()) + } + + fn version(&self) -> u64 { + 5 + } +} diff --git a/src/migrations/mod.rs b/src/migrations/mod.rs index 1288253..6fb86ac 100644 --- a/src/migrations/mod.rs +++ b/src/migrations/mod.rs @@ -1,6 +1,7 @@ use crate::migrations::migration2_remove_imgur::Migration2RemoveImgur; use crate::migrations::migration3_remove_img::Migration3RemoveImage; use crate::migrations::migration_4_update_random::Migration4UpdateRandoms; +use crate::migrations::migration_5_update_motivation::Migration5UpdateMotivation; use j_db::database::Database; use j_db::migration; use j_db::migration::Direction; @@ -8,8 +9,9 @@ use j_db::migration::Direction; mod migration2_remove_imgur; mod migration3_remove_img; mod migration_4_update_random; +mod migration_5_update_motivation; -const CURRENT_DB_VERSION: u64 = 4; +const CURRENT_DB_VERSION: u64 = 5; #[allow(clippy::single_match)] pub fn do_migration(db: &Database) { @@ -40,6 +42,12 @@ pub fn do_migration(db: &Database) { ) .unwrap(); } + 5 => migration::do_migration::( + db, + Migration5UpdateMotivation {}, + Direction::Up, + ) + .unwrap(), _ => {} } } diff --git a/src/models/motivation.rs b/src/models/motivation.rs index 2efa29d..29b3b5c 100644 --- a/src/models/motivation.rs +++ b/src/models/motivation.rs @@ -1,19 +1,21 @@ use crate::album_manager::{AlbumManager, AlbumQuery, Image}; use crate::error::Error; +use crate::models::random::RandomConfig; use j_db::database::Database; use j_db::error::JDbError; use j_db::model::JdbModel; -use rand::prelude::{IteratorRandom, SliceRandom}; +use rand::prelude::SliceRandom; use rand::thread_rng; use serde::{Deserialize, Serialize}; use std::fmt::Debug; +pub const GOAL_RANDOM_GROUP: &str = "Goal"; +pub const ACTION_RANDOM_GROUP: &str = "Action"; + #[derive(Debug, Deserialize, Serialize, Clone)] pub struct MotivationConfig { id: Option, pub album: Vec, - pub action: Vec, - pub goal: Vec, } impl JdbModel for MotivationConfig { @@ -42,8 +44,6 @@ impl MotivationConfig { .unwrap_or(Self { id: None, album: vec![], - action: vec![], - goal: vec![], })) } @@ -56,24 +56,6 @@ impl MotivationConfig { Ok(()) } - pub fn add_action(db: &Database, action: &str) -> Result<(), Error> { - let mut motivation = Self::get_motivation_config(db)?; - motivation.action.push(action.to_string()); - - db.insert(motivation)?; - - Ok(()) - } - - pub fn add_goal(db: &Database, goal: &str) -> Result<(), Error> { - let mut motivation = Self::get_motivation_config(db)?; - motivation.goal.push(goal.to_string()); - - db.insert(motivation)?; - - Ok(()) - } - pub async fn generate_motivation( db: &Database, picox: &AlbumManager, @@ -112,9 +94,11 @@ impl MotivationConfig { .choose(&mut thread_rng()) .ok_or(Error::NoAlbumFound)?; - let action = motivation.action.iter().choose(&mut thread_rng()).unwrap(); + let actions = RandomConfig::get_random(db, ACTION_RANDOM_GROUP)?.unwrap_or_default(); + let goals = RandomConfig::get_random(db, GOAL_RANDOM_GROUP)?.unwrap_or_default(); - let goal = motivation.goal.iter().choose(&mut thread_rng()).unwrap(); + let action = actions.get_response(db)?.unwrap_or_default(); + let goal = goals.get_response(db)?.unwrap_or_default(); let image = picox.get_image_by_id(*image).await.unwrap(); diff --git a/src/models/random.rs b/src/models/random.rs index 4b59f19..ec83d48 100644 --- a/src/models/random.rs +++ b/src/models/random.rs @@ -43,7 +43,7 @@ impl JdbModel for Random { !self.response.eq_ignore_ascii_case(&other.response) } } -#[derive(Debug, Deserialize, Serialize, Clone)] +#[derive(Debug, Deserialize, Serialize, Clone, Default)] pub struct RandomConfig { id: Option, pub name: String, diff --git a/src/models/task.rs b/src/models/task.rs index 4b74748..d67dc2f 100644 --- a/src/models/task.rs +++ b/src/models/task.rs @@ -173,7 +173,12 @@ impl Task { } TaskType::HandleReload => { println!("Reloading config..."); - global_data.reload().await.unwrap(); + let res = global_data.reload().await; + + match res { + Ok(_) => println!("Finished reloading config!"), + Err(err) => println!("Error reloading config: {:?}", err), + } Task::add_task( &global_data.db, @@ -183,7 +188,13 @@ impl Task { } TaskType::RestockShop => { println!("Restocking Shop..."); - restock_shop(ctx, global_data).await.unwrap(); + let res = restock_shop(ctx, global_data).await; + + match res { + Ok(_) => println!("Finished restocking shop!"), + Err(err) => println!("Error restocking shop: {:?}", err), + } + Task::add_task( &global_data.db, TaskType::RestockShop, diff --git a/src/user/mod.rs b/src/user/mod.rs index d393c32..e7d0ea7 100644 --- a/src/user/mod.rs +++ b/src/user/mod.rs @@ -45,7 +45,7 @@ impl User { Self { id: None, user_id, - coin_count: -100_000_00, + coin_count: 0, inventory: Default::default(), } }