Skip to content

Commit

Permalink
Decent logging. Configurable log level.
Browse files Browse the repository at this point in the history
  • Loading branch information
keuin committed Mar 27, 2022
1 parent ab4b890 commit b611e39
Show file tree
Hide file tree
Showing 8 changed files with 199 additions and 131 deletions.
152 changes: 68 additions & 84 deletions Cargo.lock

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

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ tokio = { version = "1.17.0", features = ["full"] }
futures = "0.3.21"
warp = "0.3.2"
teloxide = { version = "0.7.2", features = ["macros", "auto-send"] }
log = "0.4.16"
pretty_env_logger = "0.4.0"
serde = "1.0.136"
serde_derive = "1.0.136"
serde_json = "1.0.79"
sqlx = { version = "0.5", features = [ "runtime-tokio-rustls", "sqlite" ] }
urandom = "0.1.0"
bs58 = "0.4.0"
bs58 = "0.4.0"
tracing = "0.1.32"
tracing-subscriber = "0.3.9"
45 changes: 32 additions & 13 deletions src/bot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::ops::Deref;
use std::sync::Arc;

use teloxide::{prelude2::*, types::MessageKind, utils::command::BotCommand};
use tracing::{debug, error, info};

use crate::{database, DbPool, token};
use crate::user::User;
Expand All @@ -18,36 +19,54 @@ enum Command {

async fn answer(bot: AutoSend<Bot>, message: Message, command: Command, db: Arc<DbPool>)
-> Result<(), Box<dyn Error + Send + Sync>> {
debug!("Answering telegram message: {:?}", message);
match command {
Command::Help => {
bot.send_message(message.chat.id, Command::descriptions()).await?;
debug!("Command /help.");
if let Err(why) =
bot.send_message(message.chat.id, Command::descriptions()).await {
error!("Failed to send telegram message: {:?}.", why);
}
}
Command::Start => {
debug!("Command /start.");
if let MessageKind::Common(msg) = message.kind {
if msg.from.is_none() {
debug!("Ignore message from channel.");
return Ok(()); // ignore messages from channel
}
let from = msg.from.unwrap();
let db = db.deref();
let chat_id = message.chat.id;
match database::create_user(db, User {
let user = User {
id: from.id as u64,
name: from.username.unwrap_or_else(|| String::from("")),
token: token::generate(),
chat_id: chat_id as u64,
}).await {
Ok(_) => {}
Err(why) => println!("cannot create user: {:?}", why),
};
if let Err(why) = database::create_user(db, &user).await {
if format!("{:?}", why).contains("UNIQUE constraint failed") {
info!("User exists: {}", user);
} else {
error!("Failed to create user {}: {:?}. Skip creating.", user, why);
}
} else {
info!("Created user {}.", user);
}
bot.send_message(
chat_id,
match database::get_user_by_chat_id(db, chat_id as u64).await? {
Some(user) =>
format!("Your token is `{}`. Treat it as a secret!", user.token),
_ =>
let message =
match database::get_user_by_chat_id(db, chat_id as u64).await {
Ok(u) => match u {
Some(user) => format!("Your token is `{}`. Treat it as a secret!", user.token),
_ => String::from("Error: cannot fetch token.")
},
Err(why) => {
error!("Cannot get user: {:?}.", why);
String::from("Error: cannot fetch token.")
},
).await?;
}
};
if let Err(why) = bot.send_message(chat_id, message).await {
error!("Failed to send telegram message: {:?}.", why);
}
}
}
};
Expand Down
18 changes: 14 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,34 @@ use std::fs::File;
use std::io::Read;

use serde_derive::Deserialize;
use tracing::error;

#[derive(Deserialize)]
pub struct Config {
pub bot_token: String,
pub log_file: String,
pub db_file: String,
pub listen: String,
pub log_level: String,
}

impl Config {
// Read config file. Panic if any error occurs.
pub fn from_file(file_path: &str) -> Config {
let mut file = File::open(file_path)
.unwrap_or_else(|_| panic!("cannot open file {}", file_path));
.unwrap_or_else(|err| {
error!("Cannot open config file {}: {:?}", file_path, err);
panic!();
});
let mut config = String::new();
file.read_to_string(&mut config)
.unwrap_or_else(|_| panic!("cannot read config file {}", file_path));
return serde_json::from_str(config.as_str())
.expect("cannot decode config file in JSON");
.unwrap_or_else(|err| {
error!("Cannot read config file {}: {:?}.", file_path, err);
panic!();
});
return serde_json::from_str(config.as_str()).unwrap_or_else(|err| {
error!("Cannot decode config file: {:?}.", err);
panic!();
});
}
}

0 comments on commit b611e39

Please sign in to comment.