From 9dbd32cc5b851889be187906d1c7299a85b61688 Mon Sep 17 00:00:00 2001 From: Pavel Kirilin <win10@list.ru> Date: Sun, 26 Feb 2023 05:49:59 +0400 Subject: [PATCH] Added Chooser handler. Signed-off-by: Pavel Kirilin <win10@list.ru> --- src/bot/handlers/fun/chooser.rs | 34 +++++++++++++++++++++++++++++++++ src/bot/handlers/fun/mod.rs | 1 + src/bot/main.rs | 9 +++++++-- 3 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 src/bot/handlers/fun/chooser.rs diff --git a/src/bot/handlers/fun/chooser.rs b/src/bot/handlers/fun/chooser.rs new file mode 100644 index 0000000..76a7a1b --- /dev/null +++ b/src/bot/handlers/fun/chooser.rs @@ -0,0 +1,34 @@ +use grammers_client::{Client, Update}; +use rand::seq::SliceRandom; + +use crate::{bot::handlers::Handler, utils::messages::get_message}; + +#[derive(Clone)] +pub struct Chooser; + +#[async_trait::async_trait] +impl Handler for Chooser { + async fn react(&self, _: &Client, update: &Update) -> anyhow::Result<()> { + let Some(input_message) = get_message(update) else { + return Ok(()); + }; + let response = input_message + .text() + .strip_prefix(".c") + // Check if string is not empty. + .filter(|a| !a.is_empty()) + // Split by commas. + .map(|text| text.trim().split(',').collect::<Vec<_>>()) + // Choose random variant. + .and_then(|collected| collected.choose(&mut rand::rngs::OsRng).copied()); + // It the string is chosen, reply to message with it. + if let Some(answer) = response { + input_message.reply(answer).await?; + } else { + input_message + .reply("Я не Ñмог понÑть из чего мне выбирать. Попробуй ещё раз.") + .await?; + } + Ok(()) + } +} diff --git a/src/bot/handlers/fun/mod.rs b/src/bot/handlers/fun/mod.rs index c25fcd8..9cc0c1c 100644 --- a/src/bot/handlers/fun/mod.rs +++ b/src/bot/handlers/fun/mod.rs @@ -1,4 +1,5 @@ pub mod blyaficator; +pub mod chooser; pub mod greeter; pub mod magic_ball; pub mod repeator; diff --git a/src/bot/main.rs b/src/bot/main.rs index e989f12..04649e0 100644 --- a/src/bot/main.rs +++ b/src/bot/main.rs @@ -23,8 +23,8 @@ use super::{ weather_forecaster::WeatherForecaster, }, fun::{ - blyaficator::Blyaficator, greeter::Greeter, magic_ball::MagicBall, repeator::Repeator, - rotator::Rotator, + blyaficator::Blyaficator, chooser::Chooser, greeter::Greeter, magic_ball::MagicBall, + repeator::Repeator, rotator::Rotator, }, Handler, }, @@ -147,6 +147,11 @@ async fn run(args: BotConfig, client: Client) -> anyhow::Result<()> { .add_filter(UpdateTypeFilter(&[UpdateType::New])) .add_filter(SilentFilter) .add_filter(TextFilter(&[".mb"], TextMatchMethod::IStartsWith)), + // Random chooser. + FilteredHandler::new(Chooser) + .add_filter(UpdateTypeFilter(&[UpdateType::New])) + .add_filter(SilentFilter) + .add_filter(TextFilter(&[".c"], TextMatchMethod::IStartsWith)), ]; let mut errors_count = 0; -- GitLab