Added Chooser handler.

Signed-off-by: Pavel Kirilin <win10@list.ru>
This commit is contained in:
2023-02-26 05:49:59 +04:00
parent 99c049549f
commit 9dbd32cc5b
3 changed files with 42 additions and 2 deletions

View File

@ -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(())
}
}

View File

@ -1,4 +1,5 @@
pub mod blyaficator;
pub mod chooser;
pub mod greeter;
pub mod magic_ball;
pub mod repeator;

View File

@ -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;