From b611e395a2d002c0696c2c10e2f43b3f9013c6d9 Mon Sep 17 00:00:00 2001 From: Keuin Date: Mon, 28 Mar 2022 00:06:58 +0800 Subject: Decent logging. Configurable log level. --- src/bot.rs | 45 ++++++++++++++++++++++++++++++++------------- 1 file changed, 32 insertions(+), 13 deletions(-) (limited to 'src/bot.rs') diff --git a/src/bot.rs b/src/bot.rs index 9ea2c3a..e46ed85 100644 --- a/src/bot.rs +++ b/src/bot.rs @@ -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; @@ -18,36 +19,54 @@ enum Command { async fn answer(bot: AutoSend, message: Message, command: Command, db: Arc) -> Result<(), Box> { + 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); + } } } }; -- cgit v1.2.3