From 90ac6d77aa3fd4ba34c36abed01ec2fde23b8a4e Mon Sep 17 00:00:00 2001 From: Pavel Kirilin <win10@list.ru> Date: Thu, 4 Apr 2024 03:02:57 +0200 Subject: [PATCH] Added new handle. Signed-off-by: Pavel Kirilin <win10@list.ru> --- src/bot/handlers/basic/currency_converter.rs | 43 +++++++++++--------- src/bot/handlers/basic/get_user_id.rs | 24 +++++++++++ src/bot/handlers/basic/help.rs | 4 +- src/bot/handlers/basic/mod.rs | 1 + src/bot/handlers/basic/notify_all.rs | 4 +- src/bot/handlers/basic/time_converter.rs | 12 +++--- src/bot/handlers/fun/greeter.rs | 4 +- src/bot/handlers/fun/repeator.rs | 4 +- src/bot/handlers/fun/rotator.rs | 2 +- src/bot/main.rs | 11 +++-- 10 files changed, 77 insertions(+), 32 deletions(-) create mode 100644 src/bot/handlers/basic/get_user_id.rs diff --git a/src/bot/handlers/basic/currency_converter.rs b/src/bot/handlers/basic/currency_converter.rs index 5acfc21..1b54c2f 100644 --- a/src/bot/handlers/basic/currency_converter.rs +++ b/src/bot/handlers/basic/currency_converter.rs @@ -74,7 +74,7 @@ lazy_static::lazy_static! { ); static ref CUR_REGEX: Regex = { - #[allow(clippy::clone_double_ref)] + #[allow(suspicious_double_ref_op)] let a = CONVERTION_ALIASES.keys() .copied() .chain(SUPPORTED_CURS.iter().copied()) @@ -115,7 +115,9 @@ impl Filter for CurrencyTextFilter { #[async_trait::async_trait] impl Handler for CurrencyConverter { async fn react(&self, _: &Client, update: &Update) -> anyhow::Result<()> { - let Some(message) = get_message(update) else{ return Ok(())}; + let Some(message) = get_message(update) else { + return Ok(()); + }; let response = self .client .get("https://www.cbr-xml-daily.ru/daily_json.js") @@ -127,10 +129,11 @@ impl Handler for CurrencyConverter { let Some(valutes) = response .get("Valute") - .and_then(serde_json::Value::as_object) else{ - log::warn!("Can't get valutes fom response."); - return Ok(()); - }; + .and_then(serde_json::Value::as_object) + else { + log::warn!("Can't get valutes fom response."); + return Ok(()); + }; let mut calucates = Vec::new(); @@ -142,17 +145,19 @@ impl Handler for CurrencyConverter { // Convert match to string. .map(|mtch| mtch.as_str()) // Parse it. - .and_then(|val| val.parse::<f64>().ok()) else{ - continue; - }; + .and_then(|val| val.parse::<f64>().ok()) + else { + continue; + }; let cur_name = capture.name("cur_name").map(|mtch| mtch.as_str()); let Some(cur_name) = cur_name // We check if the value is an alias. .and_then(|val| CONVERTION_ALIASES.get(val).copied()) // get previous value if not. - .or(cur_name) else{ - continue; - }; + .or(cur_name) + else { + continue; + }; let fingerprint = format!("{num_value:.5} {cur_name}"); // Check if we already processed this value. if mapped.contains(&fingerprint) { @@ -167,19 +172,19 @@ impl Handler for CurrencyConverter { .and_then(|info| info.get("Nominal")) .map(ToString::to_string) .and_then(|value| value.as_str().parse::<f64>().ok()) - // If the name cannot be found, we continue. - else{ - continue; - }; + // If the name cannot be found, we continue. + else { + continue; + }; // Now we want to know multiplier. let Some(multiplier) = valutes .get(cur_name) .and_then(|info| info.get("Value")) .map(ToString::to_string) .and_then(|value| value.as_str().parse::<f64>().ok()) - else{ - continue; - }; + else { + continue; + }; calucates.push(format!( "<pre>{num_value} {cur_name} = {value:.2} RUB</pre><br>", diff --git a/src/bot/handlers/basic/get_user_id.rs b/src/bot/handlers/basic/get_user_id.rs new file mode 100644 index 0000000..9a13998 --- /dev/null +++ b/src/bot/handlers/basic/get_user_id.rs @@ -0,0 +1,24 @@ +use grammers_client::{types::Chat, Client, InputMessage, Update}; + +use crate::{bot::handlers::Handler, utils::messages::get_message}; + +#[derive(Clone)] +pub struct GetUserId; + +#[async_trait::async_trait] +impl Handler for GetUserId { + async fn react(&self, _: &Client, update: &Update) -> anyhow::Result<()> { + let message = get_message(update); + let Some(msg) = message else { + return Ok(()); + }; + let Chat::User(user) = msg.chat() else { + return Ok(()); + }; + let username = user.username().unwrap_or("Unknown username"); + let user_id = user.id(); + msg.reply(InputMessage::text(format!("{username}: {user_id}")).silent(true)) + .await?; + Ok(()) + } +} diff --git a/src/bot/handlers/basic/help.rs b/src/bot/handlers/basic/help.rs index 00a96ca..38b519b 100644 --- a/src/bot/handlers/basic/help.rs +++ b/src/bot/handlers/basic/help.rs @@ -8,7 +8,9 @@ pub struct Help; #[async_trait::async_trait] impl Handler for Help { async fn react(&self, _: &Client, update: &Update) -> anyhow::Result<()> { - let Update::NewMessage(message) = update else {return Ok(())}; + let Update::NewMessage(message) = update else { + return Ok(()); + }; message.reply("Я больше не раÑÑказываю что Ñ ÑƒÐ¼ÐµÑŽ.").await?; diff --git a/src/bot/handlers/basic/mod.rs b/src/bot/handlers/basic/mod.rs index c8780e1..c1e40c3 100644 --- a/src/bot/handlers/basic/mod.rs +++ b/src/bot/handlers/basic/mod.rs @@ -1,5 +1,6 @@ pub mod currency_converter; pub mod get_chat_id; +pub mod get_user_id; pub mod help; pub mod notify_all; pub mod time_converter; diff --git a/src/bot/handlers/basic/notify_all.rs b/src/bot/handlers/basic/notify_all.rs index 1155591..7b42364 100644 --- a/src/bot/handlers/basic/notify_all.rs +++ b/src/bot/handlers/basic/notify_all.rs @@ -8,7 +8,9 @@ pub struct NotifyAll; #[async_trait::async_trait] impl Handler for NotifyAll { async fn react(&self, client: &Client, update: &Update) -> anyhow::Result<()> { - let Some(message) = get_message(update) else {return Ok(());}; + let Some(message) = get_message(update) else { + return Ok(()); + }; let Chat::Group(group) = message.chat() else { return Ok(()); }; diff --git a/src/bot/handlers/basic/time_converter.rs b/src/bot/handlers/basic/time_converter.rs index 55e3e80..b56f3b4 100644 --- a/src/bot/handlers/basic/time_converter.rs +++ b/src/bot/handlers/basic/time_converter.rs @@ -24,15 +24,15 @@ pub fn convert_time(offsets: &[FixedOffset], times: &[NaiveTime]) -> Vec<String> let mut replies = Vec::new(); let now = Utc::now(); - let Some(main_offset) = offsets.get(0) else { + let Some(main_offset) = offsets.first() else { return vec![]; }; for time in times { let dt = NaiveDateTime::new(now.date_naive(), *time); let Some(start_time) = main_offset.from_local_datetime(&dt).latest() else { - continue; - }; + continue; + }; for offset in offsets { if offset == main_offset && offsets.len() > 1 { @@ -56,7 +56,9 @@ pub fn convert_time(offsets: &[FixedOffset], times: &[NaiveTime]) -> Vec<String> #[async_trait::async_trait] impl Handler for TimeConverter { async fn react(&self, _: &Client, update: &Update) -> anyhow::Result<()> { - let Some(message) = get_message(update) else{return Ok(());}; + let Some(message) = get_message(update) else { + return Ok(()); + }; let mut offsets = Vec::new(); let mut times = Vec::new(); @@ -97,7 +99,7 @@ impl Handler for TimeConverter { if times.is_empty() { offsets = [FixedOffset::east_opt(0).unwrap()] .into_iter() - .chain(offsets.into_iter()) + .chain(offsets) .collect::<Vec<_>>(); times.push(Utc::now().time()); } diff --git a/src/bot/handlers/fun/greeter.rs b/src/bot/handlers/fun/greeter.rs index f5ae4c8..b61754b 100644 --- a/src/bot/handlers/fun/greeter.rs +++ b/src/bot/handlers/fun/greeter.rs @@ -21,7 +21,9 @@ pub struct Greeter; #[async_trait] impl Handler for Greeter { async fn react(&self, _: &Client, update: &Update) -> anyhow::Result<()> { - let Update::NewMessage(message) = update else {return Ok(())}; + let Update::NewMessage(message) = update else { + return Ok(()); + }; // Choose random greeting from the list of greetings. let reply_text = GREETINGS.iter().choose(&mut rand::rngs::OsRng).copied(); diff --git a/src/bot/handlers/fun/repeator.rs b/src/bot/handlers/fun/repeator.rs index 5b41018..7e61b64 100644 --- a/src/bot/handlers/fun/repeator.rs +++ b/src/bot/handlers/fun/repeator.rs @@ -8,7 +8,9 @@ pub struct Repeator; #[async_trait::async_trait] impl Handler for Repeator { async fn react(&self, _: &Client, update: &Update) -> anyhow::Result<()> { - let Some(message) = get_message(update) else { return Ok(()) }; + let Some(message) = get_message(update) else { + return Ok(()); + }; message .respond(InputMessage::from(message.text()).silent(true)) .await?; diff --git a/src/bot/handlers/fun/rotator.rs b/src/bot/handlers/fun/rotator.rs index 4bfbf79..f3ca8fc 100644 --- a/src/bot/handlers/fun/rotator.rs +++ b/src/bot/handlers/fun/rotator.rs @@ -37,7 +37,7 @@ async fn rotator(replied_message: Message, text: String) { #[async_trait::async_trait] impl Handler for Rotator { async fn react(&self, _: &Client, update: &Update) -> anyhow::Result<()> { - let Some(message) = get_message(update) else{ + let Some(message) = get_message(update) else { return Ok(()); }; if let Some(text) = message.text().strip_prefix(".rl").map(str::trim) { diff --git a/src/bot/main.rs b/src/bot/main.rs index fa85274..6d106b5 100644 --- a/src/bot/main.rs +++ b/src/bot/main.rs @@ -19,6 +19,7 @@ use super::{ basic::{ currency_converter::{CurrencyConverter, CurrencyTextFilter}, get_chat_id::GetChatId, + get_user_id::GetUserId, help::Help, notify_all::NotifyAll, time_converter::TimeConverter, @@ -97,6 +98,7 @@ async fn handle_with_log(handler: Box<dyn Handler>, client: Client, update_data: /// and spawns correcsponding handlers. /// /// Also, every available handler is defined here. +#[allow(clippy::too_many_lines)] async fn run(args: BotConfig, client: Client) -> anyhow::Result<()> { let me = client.get_me().await?; let handlers: Vec<FilteredHandler> = vec![ @@ -118,6 +120,11 @@ async fn run(args: BotConfig, client: Client) -> anyhow::Result<()> { .add_filter(ExcludedChatsFilter(args.excluded_chats.clone())) .add_filter(TextFilter(&[".cid"], TextMatchMethod::Matches)) .add_filter(OnlyFromId(me.id())), + // Get user id. + FilteredHandler::new(GetUserId) + .add_filter(SilentFilter) + .add_filter(MessageDirectionFilter(MessageDirection::Outgoing)) + .add_filter(TextFilter(&[".uid"], TextMatchMethod::Matches)), // Make Ð±Ð»Ñ fun again. FilteredHandler::new(Blyaficator) .add_filter(ExcludedChatsFilter(args.excluded_chats.clone())) @@ -168,8 +175,6 @@ async fn run(args: BotConfig, client: Client) -> anyhow::Result<()> { &[".cid"], TextMatchMethod::StartsWith, ))), - // .add_filter(TextFilter(&[".cid"], TextMatchMethod::)), - // Notify all. FilteredHandler::new(NotifyAll) .add_filter(ExcludedChatsFilter(args.excluded_chats.clone())) .add_filter(UpdateTypeFilter(&[UpdateType::New])) @@ -265,7 +270,7 @@ pub async fn start(args: BotConfig, web_code: Arc<RwLock<Option<String>>>) -> an Err(err) => { log::error!("{err}"); } - Ok(_) => { + Ok(()) => { log::info!("Lol, messages are ended."); } } -- GitLab