Skip to content
This repository has been archived by the owner on Aug 7, 2024. It is now read-only.

Commit

Permalink
feat: update logger and other small changes
Browse files Browse the repository at this point in the history
  • Loading branch information
M3DZIK authored Jul 9, 2022
1 parent 3a6d81b commit cee17a1
Show file tree
Hide file tree
Showing 8 changed files with 157 additions and 53 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/target
configuration.json
.env
.env
*.log
85 changes: 85 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 6 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,13 @@ panic = "abort"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
dotenv = "0.15"
serde_json = "1.0"
serde_json = "1.0"
tokio = { version = "1.0", features = ["rt-multi-thread"] }
log = "0.4"
log = { version = "0.4", features = ["max_level_debug", "release_max_level_warn"] }
regex = "1.0"
serde_regex = "1.1"
chrono = "0.4"
serenity = { git = "https://github.com/serenity-rs/serenity.git", default_features = false, features = ["client", "gateway", "rustls_backend", "model"] }
serenity = { git = "https://github.com/serenity-rs/serenity.git", default_features = false, features = ["client", "gateway", "rustls_backend", "model"] }
simplelog = "0.12.0"
anyhow = "1.0.58"
dirs = "4.0.0"
18 changes: 18 additions & 0 deletions src/logger.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use std::fs::File;

use log::LevelFilter;
use simplelog::{ColorChoice, CombinedLogger, Config, TermLogger, TerminalMode, WriteLogger};

pub fn init() -> anyhow::Result<()> {
CombinedLogger::init(vec![
TermLogger::new(
LevelFilter::Debug,
Config::default(),
TerminalMode::Mixed,
ColorChoice::Auto,
),
WriteLogger::new(LevelFilter::Info, Config::default(), File::create("logs.log")?),
])?;

Ok(())
}
17 changes: 0 additions & 17 deletions src/logger/logging.rs

This file was deleted.

1 change: 0 additions & 1 deletion src/logger/mod.rs

This file was deleted.

24 changes: 9 additions & 15 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use std::env;
use std::sync::Arc;
use std::{env, process};

use chrono::{DateTime, Duration, NaiveDateTime, Utc};
use log::{error, info, trace, LevelFilter};
use logger::logging::SimpleLogger;
use log::{error, info, trace};
use model::application::Configuration;
use regex::Regex;
use serenity::client::{Context, EventHandler};
Expand All @@ -13,11 +12,10 @@ use serenity::model::prelude::command::Command;
use serenity::model::prelude::interaction::{Interaction, InteractionResponseType, MessageFlags};
use serenity::prelude::{GatewayIntents, RwLock, TypeMapKey};
use serenity::{async_trait, Client};

mod logger;
mod model;

static LOGGER: SimpleLogger = SimpleLogger;

struct BotConfiguration;

impl TypeMapKey for BotConfiguration {
Expand Down Expand Up @@ -111,7 +109,7 @@ impl EventHandler for Handler {
}

if stop_command {
std::process::exit(0);
process::exit(0);
}
}
}
Expand Down Expand Up @@ -225,9 +223,7 @@ impl EventHandler for Handler {
#[tokio::main]
async fn main() {
// Initialize the logging framework.
log::set_logger(&LOGGER)
.map(|()| log::set_max_level(LevelFilter::Warn))
.expect("Could not set logger.");
logger::init().expect("failed to init logger");

// Set up the configuration.
let configuration = load_configuration();
Expand All @@ -238,7 +234,7 @@ async fn main() {
Some((_, value)) => value,
None => {
error!("Environment variable DISCORD_AUTHORIZATION_TOKEN unset.");
std::process::exit(1);
process::exit(1);
},
};

Expand All @@ -255,9 +251,7 @@ async fn main() {
client.data.write().await.insert::<BotConfiguration>(Arc::new(RwLock::new(configuration)));

// Start the Discord bot.
if let Err(why) = client.start().await {
error!("{:?}", why);
} else {
info!("Client started.");
}
client.start().await.expect("failed to start discord bot");

info!("Client started.");
}
53 changes: 37 additions & 16 deletions src/model/application.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use std::fs::File;
use std::io::{Error, Read, Write};
use std::{
fs::{self, File},
io::{Read, Result, Write},
path::Path,
};

use dirs::config_dir;
use regex::Regex;
use serde::{Deserialize, Serialize};

Expand All @@ -11,26 +15,45 @@ pub struct Configuration {
pub message_responses: Vec<MessageResponse>,
}

const CONFIG_PATH: &str = "configuration.json";

impl Configuration {
fn save(&self) -> Result<(), Error> {
let mut file = File::create("configuration.json")?;
fn save(&self) -> Result<()> {
let sys_config_dir = config_dir().expect("find config dir");

fs::create_dir_all(format!("{}/revanced-discord-bot", sys_config_dir.to_string_lossy()))
.expect("create config dir");

let mut file = File::create(CONFIG_PATH)?;
let json = serde_json::to_string_pretty(&self)?;
file.write_all(json.as_bytes())?;
Ok(())
}

pub fn load() -> Result<Configuration, Error> {
let mut file = match File::open("configuration.json") {
Ok(file) => file,
Err(_) => {
let configuration = Configuration::default();
configuration.save()?;
return Ok(configuration);
},
pub fn load() -> Result<Configuration> {
let sys_config_dir = config_dir().expect("Can not find the configuration directory.");
let sys_config =
format!("{}/revanced-discord-bot/{CONFIG_PATH}", sys_config_dir.to_string_lossy());

// config file in current dir
let mut file = if Path::new(CONFIG_PATH).exists() {
File::open(CONFIG_PATH)?
}
// config file in system dir (on *nix: `~/.config/revanced-discord-bot/`)
else if Path::new(&sys_config).exists() {
File::open(sys_config)?
}
// create defalt config
else {
let default_config = Configuration::default();
default_config.save()?;

File::open(sys_config)?
};

let mut buf = String::new();
file.read_to_string(&mut buf)?;

Ok(serde_json::from_str(&buf)?)
}
}
Expand Down Expand Up @@ -106,16 +129,14 @@ pub struct Author {
#[derive(Serialize, Deserialize)]
pub struct Includes {
pub channels: Vec<u64>,
#[serde(rename = "match")]
#[serde(with = "serde_regex")]
#[serde(rename = "match", with = "serde_regex")]
pub match_field: Vec<Regex>,
}

#[derive(Serialize, Deserialize)]
pub struct Excludes {
pub roles: Vec<u64>,
#[serde(rename = "match")]
#[serde(with = "serde_regex")]
#[serde(rename = "match", with = "serde_regex")]
pub match_field: Vec<Regex>,
}

Expand Down

0 comments on commit cee17a1

Please sign in to comment.