clemsbot/src/main.rs

71 lines
1.8 KiB
Rust
Raw Permalink Normal View History

2021-08-20 07:49:24 +00:00
#![feature(try_blocks, drain_filter)]
2021-08-18 05:45:44 +00:00
mod app;
2021-08-20 07:49:24 +00:00
use futures::FutureExt;
use tokio::{
fs::OpenOptions,
io::{AsyncReadExt, AsyncWriteExt},
runtime::{Builder, Handle},
};
2021-08-18 05:45:44 +00:00
use crate::app::{
State,
config::Config,
user_config::UserConfig,
};
2021-09-01 17:39:16 +00:00
use std::path::Path;
2021-08-18 05:45:44 +00:00
fn main() -> anyhow::Result<()> {
let runtime = Builder::new_multi_thread()
.enable_all()
.build()?;
let handle = runtime.handle().clone();
runtime.block_on(inner(handle))
}
async fn inner(runtime: Handle) -> anyhow::Result<()> {
2021-09-01 17:39:16 +00:00
println!("reading config");
2021-08-18 05:45:44 +00:00
let mut uc_toml = String::new();
tokio::fs::File::open("config.toml").await?.read_to_string(&mut uc_toml).await?;
let user_config: UserConfig = toml::from_str(&uc_toml)?;
2021-09-01 17:39:16 +00:00
println!("reading data");
2021-08-18 05:45:44 +00:00
let c_path = Path::new("data.json");
let config: Config = if c_path.exists() {
let mut c_json = String::new();
tokio::fs::File::open(c_path).await?.read_to_string(&mut c_json).await?;
serde_json::from_str(&c_json)?
} else {
Config::default()
};
2021-09-01 17:39:16 +00:00
println!("starting bot");
2021-08-18 05:45:44 +00:00
let state = State::new(runtime, user_config, config).await?;
2021-09-01 17:39:16 +00:00
save_config(c_path, &*state.config.read().await).await?;
2021-08-18 05:45:44 +00:00
tokio::signal::ctrl_c()
2021-09-01 17:39:16 +00:00
.then(|_| async {
println!("received ctrl-c");
println!("saving config");
save_config(c_path, &*state.config.read().await).await?;
Result::<(), anyhow::Error>::Ok(())
})
2021-08-18 05:45:44 +00:00
.await?;
2021-09-01 17:39:16 +00:00
println!("exiting");
2021-08-18 05:45:44 +00:00
Ok(())
}
2021-09-01 17:39:16 +00:00
pub async fn save_config(path: &Path, config: &Config) -> anyhow::Result<()> {
2021-08-18 05:45:44 +00:00
let mut config_file = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(path)
.await?;
2021-09-01 17:39:16 +00:00
config_file.write_all(&serde_json::to_vec(config)?).await?;
2021-08-18 05:45:44 +00:00
Ok(())
}