From 960a509385fd8ee42c97b256843bdeb24f0e489e Mon Sep 17 00:00:00 2001 From: nefrace Date: Sun, 6 Nov 2022 02:24:06 +0300 Subject: [PATCH] Small refactoring, added Diesel --- Cargo.lock | 4 +-- Cargo.toml | 2 +- src/godette.rs | 9 +++++++ src/godette/dispatchers.rs | 33 ++++++++++++------------ src/godette/handlers.rs | 53 ++++++++++++++++++-------------------- 5 files changed, 54 insertions(+), 47 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 93deade..a071afb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1618,9 +1618,9 @@ checksum = "20f34339676cdcab560c9a82300c4c2581f68b9369aedf0fae86f2ff9565ff3e" [[package]] name = "teloxide" -version = "0.11.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dc299b132028bb40adb2eb6151e94dec6dff28e5c6bdd498f5964ef96aec442" +checksum = "94734a391eb4f3b6172b285fc10593192f9bdb4c8a377075cff063d967f0e43b" dependencies = [ "aquamarine", "bytes", diff --git a/Cargo.toml b/Cargo.toml index 3e24616..da80976 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ authors = ["Vladislav Rud "] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -teloxide = { version = "0.11", features = ["macros", "auto-send"] } +teloxide = { version = "0.11.1", features = ["macros", "auto-send"] } log = "0.4" pretty_env_logger = "0.4" tokio = { version = "1.8", features = ["rt-multi-thread", "macros"] } diff --git a/src/godette.rs b/src/godette.rs index fed2fe1..2a81c40 100644 --- a/src/godette.rs +++ b/src/godette.rs @@ -1,6 +1,10 @@ +use std::env; + +use diesel::{Connection, PgConnection}; use teloxide::{dispatching::DpHandlerDescription, prelude::*, RequestError}; pub mod commands; + mod dispatchers; mod handlers; mod utils; @@ -8,6 +12,7 @@ mod utils; pub struct Godette { pub bot: Bot, pub triggers: Vec, + db: PgConnection, } pub struct Trigger { @@ -30,9 +35,12 @@ impl KarmaTrigger { impl Godette { pub fn new() -> Godette { + let database_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set"); Godette { bot: Bot::from_env(), triggers: vec![], + db: PgConnection::establish(&database_url) + .unwrap_or_else(|_| panic!("Error connecting to {}", database_url)), } } @@ -40,6 +48,7 @@ impl Godette { &self, ) -> Handler<'static, DependencyMap, Result<(), RequestError>, DpHandlerDescription> { dptree::entry() + .branch(Update::filter_chat_member().endpoint(Godette::chat_member)) .branch(Update::filter_callback_query().endpoint(Godette::callback_dispatcher)) .branch( Update::filter_message() diff --git a/src/godette/dispatchers.rs b/src/godette/dispatchers.rs index 0680ddf..cf81cea 100644 --- a/src/godette/dispatchers.rs +++ b/src/godette/dispatchers.rs @@ -1,4 +1,4 @@ -use teloxide::prelude::*; +use teloxide::{prelude::*, types::ChatMemberKind}; use super::{handlers, utils, Godette}; use crate::commands::{AdminCommand, Command}; @@ -35,17 +35,12 @@ impl Godette { pub async fn message_dispatcher(bot: Bot, msg: Message) -> ResponseResult<()> { // Checking if it's a reply and send it to Reply dispatcher - let reply = msg.reply_to_message(); - match reply { - Some(reply) => { - Godette::reply_dispatcher(bot.clone(), msg.clone(), reply.to_owned()).await? - } - None => (), - }; + if let Some(reply) = msg.reply_to_message() { + Godette::reply_dispatcher(bot.clone(), msg.clone(), reply.to_owned()).await?; + } let text = utils::get_text_or_empty(&msg); - match text.to_lowercase().find("оффтоп") { - Some(_) => handlers::offtop(&bot, &msg).await?, - None => (), + if !text.to_lowercase().contains("оффтоп") { + handlers::offtop(&bot, &msg).await?; } lazy_static! { @@ -55,11 +50,8 @@ impl Godette { } if let Some(caps) = DOC_RE.captures(&text) { - match caps.name("topic") { - Some(topic) => { - handlers::documentation(&bot, &msg, String::from(topic.as_str())).await? - } - None => (), + if let Some(topic) = caps.name("topic") { + handlers::documentation(&bot, &msg, String::from(topic.as_str())).await? } } @@ -85,4 +77,13 @@ impl Godette { } Ok(()) } + + pub async fn chat_member(bot: Bot, member: ChatMemberUpdated) -> ResponseResult<()> { + if member.new_chat_member.kind == ChatMemberKind::Member { + bot.send_message(member.chat.id, member.from.first_name) + .await?; + } + + Ok(()) + } } diff --git a/src/godette/handlers.rs b/src/godette/handlers.rs index cddd285..772f9b1 100644 --- a/src/godette/handlers.rs +++ b/src/godette/handlers.rs @@ -3,7 +3,7 @@ use teloxide::{ prelude::*, types::ParseMode::MarkdownV2, utils::command::BotCommands, - utils::markdown::{self, bold, escape, italic}, + utils::markdown::{bold, escape, italic}, }; use url::Url; @@ -22,8 +22,8 @@ pub async fn show_adminhelp(bot: Bot, msg: Message) -> ResponseResult { pub async fn me(bot: Bot, msg: Message, quote: String) -> ResponseResult { let name = msg.from().unwrap().to_owned().full_name(); - let esc_username = markdown::escape(&name); - let esc_quote = markdown::escape("e); + let esc_username = escape(&name); + let esc_quote = escape("e); let text = format!("*_{esc_username}_* {esc_quote}").to_string(); bot.delete_message(msg.chat.id, msg.id).await?; @@ -46,8 +46,8 @@ pub async fn warn(bot: Bot, msg: Message, reason: String) -> ResponseResult { let username = guilty.from().unwrap().to_owned().full_name(); - let username_formatted = markdown::bold(&markdown::escape(&username)); - let reason_formatted = markdown::italic(&markdown::escape(&reason)); + let username_formatted = bold(&escape(&username)); + let reason_formatted = italic(&escape(&reason)); let text = format!( "{username_formatted} получил предупреждение по причине:\n\"{reason_formatted}\"" ); @@ -70,7 +70,7 @@ pub async fn unwarn(bot: Bot, msg: Message) -> ResponseResult { .await } -pub async fn karma(bot: &Bot, msg: &Message, reply: &Message, text: &String) -> ResponseResult<()> { +pub async fn karma(bot: &Bot, msg: &Message, reply: &Message, text: &str) -> ResponseResult<()> { let triggers = vec![ KarmaTrigger::new("спс", 1), KarmaTrigger::new("спасибо", 1), @@ -82,27 +82,24 @@ pub async fn karma(bot: &Bot, msg: &Message, reply: &Message, text: &String) -> KarmaTrigger::new("👎", -1), ]; for trigger in triggers { - match text.to_lowercase().find(&trigger.text) { - Some(_id) => { - let giver = msg.from().unwrap(); - let reciever = reply.from().unwrap(); - let change_text = match trigger.value { - 1 => "повысил", - -1 => "понизил", - _ => "изменил", - }; - let text = format!( - "*{}* {} карму *{}*", - escape(&giver.first_name), - change_text, - escape(&reciever.first_name) - ); - bot.send_message(msg.chat.id, text) - .parse_mode(MarkdownV2) - .await?; - return Ok(()); - } - None => (), + if text.to_lowercase().contains(&trigger.text) { + let giver = msg.from().unwrap(); + let reciever = reply.from().unwrap(); + let change_text = match trigger.value { + 1 => "повысил", + -1 => "понизил", + _ => "изменил", + }; + let text = format!( + "*{}* {} карму *{}*", + escape(&giver.first_name), + change_text, + escape(&reciever.first_name) + ); + bot.send_message(msg.chat.id, text) + .parse_mode(MarkdownV2) + .await?; + return Ok(()); } } Ok(()) @@ -129,7 +126,7 @@ pub async fn documentation(bot: &Bot, msg: &Message, topic: String) -> ResponseR .unwrap(); let results = utils::request_docs(&topic).await; - if results.len() > 0 { + if results.is_empty() { let mut links = results .iter() .take(10)