Initial commit.

Signed-off-by: Pavel Kirilin <win10@list.ru>
This commit is contained in:
2023-02-20 01:20:41 +04:00
parent 9a04acd753
commit faae5e4898
39 changed files with 3420 additions and 2 deletions

131
src/bot/main.rs Normal file
View File

@ -0,0 +1,131 @@
use std::{sync::Arc, time::Duration};
use crate::args::BotConfig;
use grammers_client::{Client, Config, SignInError, Update};
use grammers_session::Session;
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
use tokio::sync::RwLock;
use super::{
filters::{
chain::FilteredHandler,
message_fitlers::{
ExcludedChatsFilter, MessageDirection, MessageDirectionFilter, TextFilter,
TextMatchMethod,
},
},
handlers::{
basic::{get_chat_id::GetChatId, help::Help},
fun::{blyaficator::Blyaficator, greeter::Greeter},
Handler,
},
};
async fn authorize(
args: &BotConfig,
client: &Client,
web_code: Arc<RwLock<Option<String>>>,
) -> anyhow::Result<()> {
log::info!("Requesting login code.");
let token = client
.request_login_code(&args.phone, args.app_id, &args.api_hash)
.await?;
let mut code = None;
while code.is_none() {
tokio::time::sleep(Duration::from_secs(1)).await;
{
code = web_code.read().await.clone();
}
}
let signed_in = client.sign_in(&token, &code.unwrap()).await;
match signed_in {
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.
let hint = password_token.hint().unwrap_or("None");
let password = args
.tfa_password
.as_ref()
.unwrap_or_else(|| panic!("2FA password is required. Hint for password: `{hint}`"));
log::info!("Checking client's password.");
client
.check_password(password_token, password.trim())
.await?;
}
Ok(_) => (),
Err(e) => panic!("{}", e),
}
Ok(())
}
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) {
let handlers: Vec<FilteredHandler> = vec![
FilteredHandler::new(Greeter)
.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)),
FilteredHandler::new(GetChatId)
.add_filter(TextFilter(&[".cid"], TextMatchMethod::IMatches)),
FilteredHandler::new(Blyaficator)
.add_filter(TextFilter(&[".bl"], TextMatchMethod::IStartsWith)),
];
loop {
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(),
));
}
}
}
}
pub async fn start(args: BotConfig, web_code: Arc<RwLock<Option<String>>>) -> anyhow::Result<()> {
log::info!("Connecting to Telegram...");
let client = Client::connect(Config {
session: Session::load_file_or_create(args.session_file.as_str())?,
api_id: args.app_id,
api_hash: args.api_hash.clone(),
params: grammers_client::InitParams {
device_model: String::from("MEME_MACHINE"),
catch_up: false,
..Default::default()
},
})
.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 {
authorize(&args, &client, web_code).await?;
client.session().save_to_file(args.session_file.as_str())?;
}
run(args.clone(), client).await;
Ok(())
}