Added docker building.
This commit is contained in:
15
src/args.rs
15
src/args.rs
@ -77,8 +77,21 @@ pub struct BotConfig {
|
||||
)]
|
||||
pub session_file: String,
|
||||
|
||||
#[arg(name = "bot-excluded-chats", long, env = "BOT_EXCLUDED_CHATS")]
|
||||
#[arg(
|
||||
name = "bot-excluded-chats",
|
||||
long,
|
||||
env = "BOT_EXCLUDED_CHATS",
|
||||
value_delimiter = ','
|
||||
)]
|
||||
pub excluded_chats: Vec<i64>,
|
||||
|
||||
#[arg(
|
||||
name = "bot-currency-excluded-chats",
|
||||
long,
|
||||
env = "BOT_CURRENCY_EXCLUDED_CHATS",
|
||||
value_delimiter = ','
|
||||
)]
|
||||
pub currency_excluded_chats: Vec<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Parser, Debug)]
|
||||
|
@ -4,6 +4,11 @@ use crate::bot::handlers::Handler;
|
||||
|
||||
use super::base::Filter;
|
||||
|
||||
/// This is a structure to match
|
||||
/// handlers with corresponding filters.
|
||||
///
|
||||
/// It's handy, because for different messages
|
||||
/// we have different set of rules.
|
||||
#[derive(Clone)]
|
||||
pub struct FilteredHandler {
|
||||
filters: Vec<Box<dyn Filter>>,
|
||||
@ -23,6 +28,8 @@ impl FilteredHandler {
|
||||
self
|
||||
}
|
||||
|
||||
/// This method performs checks for all filters we have.
|
||||
/// We run it not in parralel for fast fail strategy.
|
||||
pub fn check(&self, update: &Update) -> bool {
|
||||
for filter in &self.filters {
|
||||
match filter.filter(update) {
|
@ -1 +0,0 @@
|
||||
|
@ -1,5 +1,7 @@
|
||||
use grammers_client::Update;
|
||||
|
||||
use crate::utils::messages::get_message;
|
||||
|
||||
use super::base::Filter;
|
||||
|
||||
#[allow(dead_code)]
|
||||
@ -15,9 +17,17 @@ pub enum TextMatchMethod {
|
||||
IMatches,
|
||||
}
|
||||
|
||||
/// This filter is used to filter out
|
||||
/// that marked as silent.
|
||||
#[derive(Clone)]
|
||||
pub struct SilentFilter;
|
||||
|
||||
/// This filter checks that current
|
||||
/// chat is not one of excluded chats.
|
||||
#[derive(Clone)]
|
||||
pub struct ExcludedChatsFilter(pub Vec<i64>);
|
||||
|
||||
/// This filter checks for message directions.
|
||||
#[derive(Clone)]
|
||||
pub struct MessageDirectionFilter(pub MessageDirection);
|
||||
|
||||
@ -31,10 +41,8 @@ impl Filter for ExcludedChatsFilter {
|
||||
Update::CallbackQuery(query) => query.chat().clone(),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
if self.0.contains(&a.id()) {
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(true)
|
||||
// Check that list of excluded chats doesn't contain our chat.
|
||||
Ok(!self.0.contains(&a.id()))
|
||||
}
|
||||
}
|
||||
|
||||
@ -44,6 +52,7 @@ impl Filter for MessageDirectionFilter {
|
||||
|
||||
let res = matches!(
|
||||
(self.0, message.outgoing()),
|
||||
// Here we check that message's direction matches the direction we want.
|
||||
(MessageDirection::Outgoing, true) | (MessageDirection::Incoming, false)
|
||||
);
|
||||
Ok(res)
|
||||
@ -72,3 +81,11 @@ impl<'a> Filter for TextFilter<'a> {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
impl Filter for SilentFilter {
|
||||
fn filter(&self, update: &Update) -> anyhow::Result<bool> {
|
||||
let Some(message) = get_message(update) else {return Ok(false)};
|
||||
// Check that message is not silent.
|
||||
Ok(!message.silent())
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,3 @@
|
||||
mod base;
|
||||
pub mod chain;
|
||||
pub mod base;
|
||||
pub mod filtered_handler;
|
||||
pub mod message_fitlers;
|
||||
|
176
src/bot/handlers/basic/currency_converter.rs
Normal file
176
src/bot/handlers/basic/currency_converter.rs
Normal file
@ -0,0 +1,176 @@
|
||||
use std::{collections::HashMap, time::Duration};
|
||||
|
||||
use grammers_client::{Client, InputMessage, Update};
|
||||
use regex::Regex;
|
||||
|
||||
use crate::{
|
||||
bot::{filters::base::Filter, handlers::Handler},
|
||||
utils::messages::get_message,
|
||||
};
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref SUPPORTED_CURS: Vec<&'static str> = vec![
|
||||
"GBP",
|
||||
"HUF",
|
||||
"USD",
|
||||
"EUR",
|
||||
"CNY",
|
||||
"NOK",
|
||||
"UAH",
|
||||
"SEK",
|
||||
"CHF",
|
||||
"KRW",
|
||||
"JPY",
|
||||
"KZT",
|
||||
"PLN",
|
||||
"TRY",
|
||||
"AMD",
|
||||
"RSD",
|
||||
];
|
||||
|
||||
static ref CONVERTION_ALIASES: HashMap<&'static str, &'static str> = HashMap::from(
|
||||
[
|
||||
// GBP
|
||||
("фунт", "GBP"),
|
||||
// USD
|
||||
("бакс", "USD"),
|
||||
("доллар", "USD"),
|
||||
// EUR
|
||||
("евро", "EUR"),
|
||||
// JPY
|
||||
("иен", "JPY"),
|
||||
("йен", "JPY"),
|
||||
// KRW
|
||||
("вон", "KRW"),
|
||||
// CHF
|
||||
("франк", "CHF"),
|
||||
// SEK
|
||||
("крон", "CHF"),
|
||||
// CNY
|
||||
("юан", "CNY"),
|
||||
// UAH
|
||||
("гривна", "UAH"),
|
||||
("гривны", "UAH"),
|
||||
("гривен", "UAH"),
|
||||
("грiвен", "UAH"),
|
||||
// KZT
|
||||
("тенге", "KZT"),
|
||||
("тэнге", "KZT"),
|
||||
// PLN
|
||||
("злот", "PLN"),
|
||||
// TRY
|
||||
("лир", "TRY"),
|
||||
// AMD
|
||||
("драм", "AMD"),
|
||||
// RSD
|
||||
("динар", "RSD"),
|
||||
]
|
||||
);
|
||||
|
||||
static ref CUR_REGEX: Regex = {
|
||||
#[allow(clippy::clone_double_ref)]
|
||||
let a = CONVERTION_ALIASES.keys()
|
||||
.copied()
|
||||
.chain(SUPPORTED_CURS.iter().copied())
|
||||
.collect::<Vec<_>>()
|
||||
.join("|");
|
||||
Regex::new(format!(r"\s*(?P<cur_value>\d+([\.,]\d+)?)\s+(?P<cur_name>{a})").as_str()).unwrap()
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CurrencyTextFilter;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CurrencyConverter {
|
||||
client: reqwest::Client,
|
||||
}
|
||||
|
||||
impl CurrencyConverter {
|
||||
pub fn new() -> anyhow::Result<Self> {
|
||||
let client = reqwest::ClientBuilder::new()
|
||||
.timeout(Duration::from_secs(2))
|
||||
.gzip(true)
|
||||
.build()?;
|
||||
Ok(Self { client })
|
||||
}
|
||||
}
|
||||
|
||||
/// This filter check if the message matches regex for currencies.
|
||||
impl Filter for CurrencyTextFilter {
|
||||
fn filter(&self, update: &Update) -> anyhow::Result<bool> {
|
||||
let Some(message) = get_message(update) else {
|
||||
return Ok(false);
|
||||
};
|
||||
Ok(CUR_REGEX.is_match(message.text()))
|
||||
}
|
||||
}
|
||||
|
||||
#[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 response = self
|
||||
.client
|
||||
.get("https://www.cbr-xml-daily.ru/daily_json.js")
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.json::<serde_json::Value>()
|
||||
.await?;
|
||||
|
||||
let Some(valutes) = response
|
||||
.get("Valute")
|
||||
.and_then(serde_json::Value::as_object) else{
|
||||
log::warn!("Can't get valutes fom response.");
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let mut calucates = Vec::new();
|
||||
|
||||
for capture in CUR_REGEX.captures_iter(message.text()) {
|
||||
// We parse supplied value from message
|
||||
let Some(num_value) = capture
|
||||
.name("cur_value")
|
||||
// Convert match to string.
|
||||
.map(|mtch| mtch.as_str())
|
||||
// Parse it.
|
||||
.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;
|
||||
};
|
||||
let calculated = valutes
|
||||
.get(cur_name)
|
||||
.and_then(|info| info.get("Value"))
|
||||
.map(ToString::to_string)
|
||||
.and_then(|value| value.as_str().parse::<f64>().ok())
|
||||
.map(|multiplier| multiplier * num_value);
|
||||
if let Some(value) = calculated {
|
||||
calucates.push(format!(
|
||||
"<pre>{num_value} {cur_name} = {value:.2} RUB</pre><br>"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if !calucates.is_empty() {
|
||||
let mut bot_response =
|
||||
String::from("<b>Полагаясь на текущий курс валют могу сказать следующее:</b>\n\n");
|
||||
for calc in calucates {
|
||||
bot_response.push_str(calc.as_str());
|
||||
}
|
||||
message
|
||||
// We send it as silent, so we can filter this message later.
|
||||
.reply(InputMessage::html(bot_response).silent(true))
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
@ -10,7 +10,7 @@ impl Handler for Help {
|
||||
async fn react(&self, _: &Client, update: &Update) -> anyhow::Result<()> {
|
||||
let Update::NewMessage(message) = update else {return Ok(())};
|
||||
|
||||
message.reply("Хелпа").await?;
|
||||
message.reply("Я больше не рассказываю что я умею.").await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
@ -1,2 +1,3 @@
|
||||
pub mod currency_converter;
|
||||
pub mod get_chat_id;
|
||||
pub mod help;
|
||||
|
@ -6,6 +6,7 @@ use grammers_client::{Client, Update};
|
||||
|
||||
const BLYA_WORDS: &[&str] = &[", бля,", ", сука,", ", ёбаный рот,", ", охуеть конечно,"];
|
||||
|
||||
/// It's time to add some бляs.
|
||||
#[derive(Clone)]
|
||||
pub struct Blyaficator;
|
||||
|
||||
|
@ -4,6 +4,17 @@ use rand::seq::IteratorRandom;
|
||||
|
||||
use crate::bot::handlers::base::Handler;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref GREETINGS: &'static [&'static str] = &[
|
||||
"Привет!",
|
||||
"Добрый день!",
|
||||
"Здравствуйте.",
|
||||
"Приетствую.",
|
||||
"Доброго времени суток.",
|
||||
];
|
||||
}
|
||||
|
||||
/// Greeter just replies to greeting messages.
|
||||
#[derive(Clone)]
|
||||
pub struct Greeter;
|
||||
|
||||
@ -18,9 +29,8 @@ impl Handler for Greeter {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let reply_text = ["Привет!", "Добрый день!", "Здравствуйте.", "Приетствую"]
|
||||
.into_iter()
|
||||
.choose(&mut rand::thread_rng());
|
||||
// Choose random greeting from the list of greetings.
|
||||
let reply_text = GREETINGS.iter().choose(&mut rand::thread_rng()).copied();
|
||||
|
||||
if let Some(text) = reply_text {
|
||||
message.reply(text).await?;
|
||||
|
@ -8,19 +8,30 @@ use tokio::sync::RwLock;
|
||||
|
||||
use super::{
|
||||
filters::{
|
||||
chain::FilteredHandler,
|
||||
filtered_handler::FilteredHandler,
|
||||
message_fitlers::{
|
||||
ExcludedChatsFilter, MessageDirection, MessageDirectionFilter, TextFilter,
|
||||
TextMatchMethod,
|
||||
ExcludedChatsFilter, MessageDirection, MessageDirectionFilter, SilentFilter,
|
||||
TextFilter, TextMatchMethod,
|
||||
},
|
||||
},
|
||||
handlers::{
|
||||
basic::{get_chat_id::GetChatId, help::Help},
|
||||
basic::{
|
||||
currency_converter::{CurrencyConverter, CurrencyTextFilter},
|
||||
get_chat_id::GetChatId,
|
||||
help::Help,
|
||||
},
|
||||
fun::{blyaficator::Blyaficator, greeter::Greeter},
|
||||
Handler,
|
||||
},
|
||||
};
|
||||
|
||||
/// Authorization function.
|
||||
///
|
||||
/// This function asks for login code and
|
||||
/// waits for it to become available.
|
||||
///
|
||||
/// Also it validates two-factor authentication
|
||||
/// password if it was supplied.
|
||||
async fn authorize(
|
||||
args: &BotConfig,
|
||||
client: &Client,
|
||||
@ -32,18 +43,19 @@ async fn authorize(
|
||||
.await?;
|
||||
let mut code = None;
|
||||
|
||||
// Check for code to becom available every second.
|
||||
while code.is_none() {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
{
|
||||
code = web_code.read().await.clone();
|
||||
}
|
||||
}
|
||||
|
||||
// Acutal signing in.
|
||||
let signed_in = client.sign_in(&token, &code.unwrap()).await;
|
||||
match signed_in {
|
||||
// If signing i
|
||||
Err(SignInError::PasswordRequired(password_token)) => {
|
||||
// Note: this `prompt` method will echo the password in the console.
|
||||
// Real code might want to use a better way to handle this.
|
||||
// If the password was not supplied, we use the hint in panic.
|
||||
let hint = password_token.hint().unwrap_or("None");
|
||||
let password = args
|
||||
.tfa_password
|
||||
@ -60,48 +72,82 @@ async fn authorize(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// This little function is used to execute handlers on updates and print errors
|
||||
/// if something bad happens.
|
||||
///
|
||||
/// The reason, I created a separate function is simple. I spawn every handler as a
|
||||
/// separate task and I don't care if fails.
|
||||
async fn handle_with_log(handler: Box<dyn Handler>, client: Client, update_data: Update) {
|
||||
if let Err(err) = handler.react(&client, &update_data).await {
|
||||
log::error!("{err}");
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(args: BotConfig, client: Client) {
|
||||
/// Acutal logic on handling updates.
|
||||
///
|
||||
/// This function handles every update we get from telegram
|
||||
/// and spawns correcsponding handlers.
|
||||
///
|
||||
/// Also, every available handler is defined here.
|
||||
async fn run(args: BotConfig, client: Client) -> anyhow::Result<()> {
|
||||
let handlers: Vec<FilteredHandler> = vec![
|
||||
// Printing help.
|
||||
FilteredHandler::new(Help).add_filter(TextFilter(&[".h"], TextMatchMethod::IMatches)),
|
||||
// Greeting my fellow humans.
|
||||
FilteredHandler::new(Greeter)
|
||||
.add_filter(SilentFilter)
|
||||
.add_filter(MessageDirectionFilter(MessageDirection::Incoming))
|
||||
.add_filter(TextFilter(&["привет"], TextMatchMethod::IStartsWith))
|
||||
.add_filter(ExcludedChatsFilter(args.excluded_chats)),
|
||||
FilteredHandler::new(Help).add_filter(TextFilter(&[".h"], TextMatchMethod::IMatches)),
|
||||
// Getting chat id.
|
||||
FilteredHandler::new(GetChatId)
|
||||
.add_filter(TextFilter(&[".cid"], TextMatchMethod::IMatches)),
|
||||
// Make бля fun again.
|
||||
FilteredHandler::new(Blyaficator)
|
||||
.add_filter(TextFilter(&[".bl"], TextMatchMethod::IStartsWith)),
|
||||
// Handler for converting currecies.
|
||||
FilteredHandler::new(CurrencyConverter::new()?)
|
||||
.add_filter(SilentFilter)
|
||||
.add_filter(ExcludedChatsFilter(args.currency_excluded_chats))
|
||||
.add_filter(CurrencyTextFilter),
|
||||
];
|
||||
|
||||
loop {
|
||||
// Get new update
|
||||
let update = client.next_update().await;
|
||||
if update.is_err() {
|
||||
log::error!("{}", update.unwrap_err());
|
||||
break;
|
||||
}
|
||||
if let Some(update_data) = update.unwrap() {
|
||||
let update_ref = &update_data;
|
||||
let matched_handlers = handlers
|
||||
.par_iter()
|
||||
.filter(move |val| val.check(update_ref))
|
||||
.collect::<Vec<_>>();
|
||||
for handler in matched_handlers {
|
||||
tokio::spawn(handle_with_log(
|
||||
handler.handler.clone(),
|
||||
client.clone(),
|
||||
update_data.clone(),
|
||||
));
|
||||
}
|
||||
// We get update if there's no error
|
||||
let Some(update_data) = update.ok().and_then(|inner|inner) else{
|
||||
log::warn!("Empty update is found.");
|
||||
continue;
|
||||
};
|
||||
// A reference to update, so we can easily move it.
|
||||
let update_ref = &update_data;
|
||||
let filtered = handlers
|
||||
// A parralel iterator over matchers.
|
||||
.par_iter()
|
||||
// Here we get all handlers that match filters.
|
||||
.filter(move |val| val.check(update_ref))
|
||||
// For each matched handler we spawn a new task.
|
||||
.collect::<Vec<_>>();
|
||||
for handler in filtered {
|
||||
tokio::spawn(handle_with_log(
|
||||
handler.handler.clone(),
|
||||
client.clone(),
|
||||
update_data.clone(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The main entrypoint for bot.
|
||||
///
|
||||
/// This function starts bot, performs login and
|
||||
/// starts endless loop.
|
||||
pub async fn start(args: BotConfig, web_code: Arc<RwLock<Option<String>>>) -> anyhow::Result<()> {
|
||||
log::info!("Connecting to Telegram...");
|
||||
let client = Client::connect(Config {
|
||||
@ -115,17 +161,20 @@ pub async fn start(args: BotConfig, web_code: Arc<RwLock<Option<String>>>) -> an
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
|
||||
log::info!("Connected!");
|
||||
|
||||
if client.is_authorized().await? {
|
||||
// If we already authrized, we write random token, so web won't update it.
|
||||
let mut code_writer = web_code.write().await;
|
||||
*code_writer = Some(String::new());
|
||||
} else {
|
||||
// If we don't have token, wait for it.
|
||||
authorize(&args, &client, web_code).await?;
|
||||
client.session().save_to_file(args.session_file.as_str())?;
|
||||
}
|
||||
|
||||
run(args.clone(), client).await;
|
||||
run(args.clone(), client).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
44
src/main.rs
44
src/main.rs
@ -25,27 +25,27 @@ async fn main() -> anyhow::Result<()> {
|
||||
|
||||
let token_lock = Arc::new(RwLock::new(None));
|
||||
|
||||
let bot_token = token_lock.clone();
|
||||
let server_token = token_lock.clone();
|
||||
[
|
||||
// Spawining bot task
|
||||
tokio::task::spawn(bot::start(args.bot.clone(), token_lock.clone())),
|
||||
// Spawning server task.
|
||||
tokio::task::spawn(error_wrap(server::create(
|
||||
args.server.clone(),
|
||||
token_lock.clone(),
|
||||
)?)),
|
||||
]
|
||||
.into_iter()
|
||||
// Turning all tasks in unirdered futures set.
|
||||
.collect::<FuturesUnordered<_>>()
|
||||
// Grab first completed future
|
||||
.take(1)
|
||||
// Take the value
|
||||
.next()
|
||||
// Await for it to complete
|
||||
.await
|
||||
// Unwrap (since we can guarantee that it's not empty).
|
||||
// Throw all errors by using ??. First for joining task, second from the task itself.
|
||||
.unwrap()??;
|
||||
|
||||
let web_server = server::create(args.server.clone(), server_token)?;
|
||||
let bot_future = bot::start(args.bot.clone(), bot_token);
|
||||
|
||||
let tasks = [
|
||||
tokio::task::spawn(bot_future),
|
||||
tokio::task::spawn(error_wrap(web_server)),
|
||||
];
|
||||
|
||||
let completed = tasks
|
||||
.into_iter()
|
||||
.collect::<FuturesUnordered<_>>()
|
||||
.take(1)
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
|
||||
if let Some(fut) = completed.into_iter().next() {
|
||||
fut?
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
@ -11,9 +11,10 @@ pub fn create(args: ServerConfig, token: Arc<RwLock<Option<String>>>) -> anyhow:
|
||||
let addr = (args.host.clone(), args.port);
|
||||
let server = HttpServer::new(move || {
|
||||
App::new()
|
||||
.wrap(actix_web::middleware::Logger::new(
|
||||
"\"%r\" \"-\" \"%s\" \"%a\" \"%D\"",
|
||||
))
|
||||
.wrap(
|
||||
actix_web::middleware::Logger::new("\"%r\" \"-\" \"%s\" \"%a\" \"%D\"")
|
||||
.exclude("/health"),
|
||||
)
|
||||
.app_data(Data::new(token.clone()))
|
||||
.app_data(Data::new(args.clone()))
|
||||
.service(login)
|
||||
|
@ -1,5 +1,16 @@
|
||||
use askama::Template;
|
||||
|
||||
/// Index pages.
|
||||
///
|
||||
/// This page is used to authenticate users.
|
||||
/// It has two states: activated or not.
|
||||
///
|
||||
/// It the activated is false, we
|
||||
/// render two input fields, with telegram code
|
||||
/// and server's password.
|
||||
///
|
||||
/// If the user is authenticated, we just render
|
||||
/// some random information.
|
||||
#[derive(Template)]
|
||||
#[template(path = "index.html")]
|
||||
pub struct Index {
|
||||
|
Reference in New Issue
Block a user