Minor config manager refactor

This commit is contained in:
August 2024-10-01 09:58:58 -04:00
parent 244dfac270
commit 398f2d8b2a
Signed by: shibedrill
GPG Key ID: 5FE0CB25945EFAA2
7 changed files with 37 additions and 27 deletions

2
Cargo.lock generated
View File

@ -1514,7 +1514,7 @@ dependencies = [
[[package]] [[package]]
name = "shibe-bot" name = "shibe-bot"
version = "0.3.1" version = "0.3.2"
dependencies = [ dependencies = [
"build-time", "build-time",
"dotenvy", "dotenvy",

View File

@ -3,7 +3,7 @@ name = "shibe-bot"
description = "A Discord bot written in Rust, using Poise." description = "A Discord bot written in Rust, using Poise."
license = "MIT" license = "MIT"
readme = "README.md" readme = "README.md"
version = "0.3.1" version = "0.3.2"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -1,4 +1,4 @@
# Shibe Bot 0.3.1 # Shibe Bot 0.3.2
[![Rust](https://github.com/shibedrill/shibe-bot/actions/workflows/rust.yml/badge.svg)](https://github.com/shibedrill/shibe-bot/actions/workflows/rust.yml) [![Rust](https://github.com/shibedrill/shibe-bot/actions/workflows/rust.yml/badge.svg)](https://github.com/shibedrill/shibe-bot/actions/workflows/rust.yml)
[![GitHub License](https://img.shields.io/github/license/shibedrill/shibe-bot)](LICENSE.txt) [![GitHub License](https://img.shields.io/github/license/shibedrill/shibe-bot)](LICENSE.txt)

View File

@ -155,8 +155,11 @@ pub async fn deer(ctx: Context<'_>) -> Result<(), Error> {
error!("Executing command `deer` failed: {}", e); error!("Executing command `deer` failed: {}", e);
})? })?
}; };
ctx.say(format!("https://vxreddit.com{}", &chosen_post.data.permalink)) ctx.say(format!(
.await?; "https://vxreddit.com{}",
&chosen_post.data.permalink
))
.await?;
info!("Executed command `deer` successfully"); info!("Executed command `deer` successfully");
Ok(()) Ok(())
} }

View File

@ -68,7 +68,9 @@ pub async fn add_channel(
match config.channels.iter().find(|item| **item == channel_id) { match config.channels.iter().find(|item| **item == channel_id) {
None => { None => {
config.channels.push(channel_id); config.channels.push(channel_id);
ctx.say(format!("Successfully added <#{channel_id}> to the channel registry.")) ctx.say(format!(
"Successfully added <#{channel_id}> to the channel registry."
))
.await?; .await?;
} }
Some(_) => { Some(_) => {
@ -92,12 +94,16 @@ pub async fn remove_channel(
let channel_id = { u64::from(channel.id()) }; let channel_id = { u64::from(channel.id()) };
match config.channels.iter().position(|item| *item == channel_id) { match config.channels.iter().position(|item| *item == channel_id) {
None => { None => {
ctx.say(format!("Channel <#{channel_id}> was not in the channel registry.")) ctx.say(format!(
"Channel <#{channel_id}> was not in the channel registry."
))
.await?; .await?;
} }
Some(found) => { Some(found) => {
config.channels.remove(found); config.channels.remove(found);
ctx.say(format!("Successfully removed <#{channel_id}> from the channel registry.")) ctx.say(format!(
"Successfully removed <#{channel_id}> from the channel registry."
))
.await?; .await?;
} }
} }
@ -145,7 +151,7 @@ pub async fn dice(
} }
) )
} }
_ => format!("Rolled a random number from 1 to {sides}, got: {answer}") _ => format!("Rolled a random number from 1 to {sides}, got: {answer}"),
}; };
ctx.say(response).await?; ctx.say(response).await?;
info!("Executed command `dice` successfully"); info!("Executed command `dice` successfully");

View File

@ -88,10 +88,11 @@ async fn main() {
// Configure persistent options // Configure persistent options
let config_manager: Arc<Mutex<Manager<Settings>>> = Arc::new(Mutex::new( let config_manager: Arc<Mutex<Manager<Settings>>> = Arc::new(Mutex::new(
Manager::load(SETTINGS_PATH) Manager::load(SETTINGS_PATH).unwrap_or(Manager::manage(SETTINGS_PATH, Settings::default())),
.unwrap_or(Manager::manage(SETTINGS_PATH, Settings::default())),
)); ));
config_manager.lock().await.store(); let _ = config_manager.lock().await.store().inspect_err(|e| {
error!("Failed to store config: {}", e);
});
// Set up framework // Set up framework
let framework = poise::Framework::builder() let framework = poise::Framework::builder()

View File

@ -13,12 +13,12 @@ pub struct Manager<T: Default + Serialize + for<'a> Deserialize<'a>> {
impl<T: Default + Serialize + for<'a> Deserialize<'a>> Manager<T> { impl<T: Default + Serialize + for<'a> Deserialize<'a>> Manager<T> {
/// Instantiate new self if the path contains a valid serialization of /// Instantiate new self if the path contains a valid serialization of
/// the settings structure. /// the settings structure.
pub fn load(path: &str) -> Option<Self> { pub fn load(path: &str) -> Result<Self, std::io::Error> {
let mut file = std::fs::File::open(path).ok()?; let mut file = std::fs::File::open(path)?;
let mut data = String::new(); let mut data = String::new();
file.read_to_string(&mut data).ok()?; file.read_to_string(&mut data)?;
let settings = serde_json::from_str(&data).ok()?; let settings = serde_json::from_str(&data)?;
Some(Self { Ok(Self {
internal: settings, internal: settings,
path: String::from(path), path: String::from(path),
}) })
@ -27,20 +27,20 @@ impl<T: Default + Serialize + for<'a> Deserialize<'a>> Manager<T> {
/// disk but not in memory. Because this is a stupid method, it will most /// disk but not in memory. Because this is a stupid method, it will most
/// likely go unused by most. /// likely go unused by most.
#[allow(dead_code)] #[allow(dead_code)]
pub fn update(&mut self) -> Option<()> { pub fn update(&mut self) -> Result<(), std::io::Error> {
let mut file = std::fs::File::open(self.path.clone()).ok()?; let mut file = std::fs::File::open(self.path.clone())?;
let mut data = String::new(); let mut data = String::new();
file.read_to_string(&mut data).ok()?; file.read_to_string(&mut data)?;
self.internal = serde_json::from_str(&data).ok()?; self.internal = serde_json::from_str(&data)?;
Some(()) Ok(())
} }
/// Serialize settings structure to the stored path. Returns None if /// Serialize settings structure to the stored path. Returns None if
/// unsuccessful. /// unsuccessful.
pub fn store(&self) -> Option<()> { pub fn store(&self) -> Result<(), std::io::Error> {
let data = serde_json::to_string_pretty(&self.internal).ok()?; let data = serde_json::to_string_pretty(&self.internal)?;
let mut file = std::fs::File::create(&self.path).ok()?; let mut file = std::fs::File::create(&self.path)?;
let _ = file.write(data.as_bytes()); let _ = file.write(data.as_bytes());
Some(()) Ok(())
} }
/// Create a new manager, passing in the path, and a structure to manage. /// Create a new manager, passing in the path, and a structure to manage.
/// We cannot initialize a settings manager without fully initialized settings. /// We cannot initialize a settings manager without fully initialized settings.