diff --git a/src/ban.rs b/src/bot_functions/ban.rs similarity index 98% rename from src/ban.rs rename to src/bot_functions/ban.rs index 242ee62..ea66801 100644 --- a/src/ban.rs +++ b/src/bot_functions/ban.rs @@ -46,7 +46,7 @@ pub mod ban{ bot.send_sticker( chat_id, InputFile::file_id("CAACAgIAAxkBAAEpgPdlzmgotYp4CID3H4LjT7yLpboESQAC-UcAAt-sWUnzukc95MLxuTQE") - ).await; + ).await.unwrap(); Ok("Демократия была совершена".to_string()) } Err(error) => { diff --git a/src/bot_functions/mute.rs b/src/bot_functions/mute.rs new file mode 100644 index 0000000..c2280a3 --- /dev/null +++ b/src/bot_functions/mute.rs @@ -0,0 +1,104 @@ +pub mod mute { + use teloxide::Bot; + use teloxide::requests::Requester; + use tokio::time::{sleep, Duration}; + use chrono::{Duration as ChronoDuration, Local, TimeDelta}; + use teloxide::payloads::RestrictChatMemberSetters; + use teloxide::types::{ChatId, ChatPermissions, InputFile, Message, MessageKind}; + + pub async fn mute_user( + replied_message: Option<&Message>, + multiplier: i32, + time: String, + bot: &Bot, + chat_id: ChatId) -> Result + { + if let None = replied_message { + bot.send_message( + chat_id, + "Ответьте на сообщение человека, которого вы хотите замьютить".to_string() + ).await.unwrap(); + Err("Ответьте на сообщение человека, которого вы хотите замьютить".to_string()) + } else { + match &replied_message.unwrap().kind { + MessageKind::Common(message) => { + if let None = message.from { + bot.send_message(chat_id, "Сообщение не найдено").await.unwrap(); + Err("Сообщение не найдено".to_string()) + } else if let Some(user) = &message.from { + match time.as_str() { + "w" | "d" | "h" | "m" => { + let dice_value = bot.send_dice(chat_id) + .await + .unwrap() + .dice() + .unwrap() + .value; + + let time_value = (multiplier * dice_value) as i64; + + let mute_duration : (TimeDelta, &str) = match time.as_str() { + "w" => (ChronoDuration::weeks(time_value), "недель"), + "d" => (ChronoDuration::days(time_value), "дней"), + "h" => (ChronoDuration::hours(time_value), "часов"), + "m" => (ChronoDuration::minutes(time_value), "минут"), + _ => (ChronoDuration::weeks(time_value), "недель"), + }; + + let duration = Local::now().naive_utc() + mute_duration.0; + + sleep(Duration::from_secs(4)).await ; + + match bot.restrict_chat_member( + chat_id, + user.id, + ChatPermissions::from_bits(0).unwrap() + ).until_date(duration.and_utc()) + .await + { + Ok(_) => { + bot.send_message( + chat_id, + format!("На пользователя {} повесили железный зановес на {} {}", + user.first_name, + multiplier * dice_value, mute_duration.1 + ) + ).await + .unwrap(); + bot.send_sticker( + chat_id, + InputFile::file_id("CAACAgIAAxkBAAEpgP1lzmlmReALF20lHlRRGRvQ_SSCDAACqjwAAiIpSUkOv2XNIRmlYTQE") + ).await.unwrap(); + Ok("Демократия была совершена".to_string()) + } + Err(error) => { + bot.send_message( + chat_id, + error.to_string().to_string() + ).await + .unwrap(); + Err(error.to_string()) + } + } + }, + _ => { + bot.send_message(chat_id, "Напишите меру времени") + .await + .unwrap(); + Err("Напишите меру времени".to_string()) + } + } + } else { + bot.send_message(chat_id, "Ошибка номер хуй") + .await + .unwrap(); + Err("Ошибка номер хуй".to_string()) + } + } + _ => { + Err("тест".to_string()) + } + } + } + } +} \ No newline at end of file diff --git a/src/unmute.rs b/src/bot_functions/unmute.rs similarity index 100% rename from src/unmute.rs rename to src/bot_functions/unmute.rs diff --git a/src/enums/commands.rs b/src/enums/commands.rs new file mode 100644 index 0000000..43f2492 --- /dev/null +++ b/src/enums/commands.rs @@ -0,0 +1,23 @@ +pub mod enum_commands { + use teloxide::utils::command::BotCommands; + + #[derive(BotCommands, Clone, Debug)] + #[command(rename_rule = "lowercase", description = "Поддерживаемые команды:")] + pub enum Commands { + #[command(description = "Команда для отображения инструкции")] + Facker, + #[command(description = "Снимается мьют.")] + DemocracyUnmute, + #[command(description = "Банит человека. Для этого необходимо: \ + 1. Сделать реплай на сообщение человека, которого вы хотите забанить; \ + 2. Указать причину бана." + )] + Tribunal(String), + #[command(description = "Мьют человека. Для этого необходимо: \ + 1. Сделать реплай на сообщение человека, которого вы хотите замьютить; \ + 2. Указать множитель мьюта; \ + 3. Указать единицу времени.", + parse_with = "split")] + DemocracyMute(i32, String), + } +} diff --git a/src/handlers/main_handler.rs b/src/handlers/main_handler.rs new file mode 100644 index 0000000..9f69550 --- /dev/null +++ b/src/handlers/main_handler.rs @@ -0,0 +1,73 @@ +pub mod main_handler { + use std::future::Future; + use teloxide::Bot; + use teloxide::types::Message; + use crate::ban::ban::ban_user; + use crate::mute::mute::mute_user; + use crate::unmute::unmute::unmute; + use teloxide::requests::Requester; + use teloxide::prelude::ResponseResult; + use teloxide::utils::command::BotCommands; + use crate::commands::enum_commands::Commands; + use crate::is_admin::is_admin::is_admin_check; + + async fn admin_command(bot: Bot, msg: Message, callback: impl Future){ + if is_admin_check(&msg, &bot).await { + callback.await; + } + } + + pub async fn handler(bot: Bot, msg: Message, commands: Commands) -> ResponseResult<()> { + let chat_id = msg.chat.id; + + match commands { + Commands::Facker => { + bot.send_message(msg.chat.id, Commands::descriptions().to_string()).await?; + }, + Commands::Tribunal(reason) => { + let reason_result = if reason.is_empty() { None } else { Some(reason) }; + admin_command(bot.clone(), msg.clone(), ban_user( + msg.reply_to_message(), + reason_result, + &bot, + chat_id, + )).await; + }, + Commands::DemocracyMute(multiplier, time) => { + if let 1i32..=10i32 = multiplier{ + admin_command(bot.clone(), msg.clone(), mute_user( + msg.clone().reply_to_message(), + multiplier, + time.to_string(), + &bot, + chat_id, + )).await; + } else if let 10i32..=i32::MAX = multiplier{ + bot.send_message( + msg.chat.id, + "Вы ввели слишком большой множитель, пожалуйста, \ + выберите множитель из промежутка [1; 10]" + ).await + .expect("Вы ввели слишком большой множитель, пожалуйста, \ + выберите множитель из промежутка [1; 10]"); + } else { + bot.send_message( + msg.chat.id, + "Вы ввели нулевой или отрицательный множитель, пожалуйста, \ + выберите множитель из промежутка [1; 10]" + ).await + .expect("Вы ввели нулевой или отрицательный множитель, пожалуйста, \ + выберите множитель из промежутка [1; 10]"); + } + } + Commands::DemocracyUnmute => { + admin_command(bot.clone(), msg.clone(), unmute( + msg.clone().reply_to_message(), + &bot, + chat_id, + )).await; + } + }; + Ok(()) + } +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index c9910cc..1744260 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,15 +1,19 @@ -mod ban; -mod mute; -mod unmute; -mod is_admin; - -use std::ops::Deref; use teloxide::prelude::*; -use crate::ban::ban::ban_user; -use crate::mute::mute::mute_user; -use crate::unmute::unmute::unmute; -use teloxide::utils::command::BotCommands; -use crate::is_admin::is_admin::is_admin_check; +use crate::commands::enum_commands::Commands; +use crate::main_handler::main_handler::handler; + +#[path="bot_functions/ban.rs"] +mod ban; +#[path="bot_functions/mute.rs"] +mod mute; +#[path="bot_functions/unmute.rs"] +mod unmute; +#[path="utils/is_admin.rs"] +mod is_admin; +#[path="enums/commands.rs"] +mod commands; +#[path="handlers/main_handler.rs"] +mod main_handler; #[tokio::main] async fn main() { @@ -18,83 +22,5 @@ async fn main() { let bot = Bot::new("6941223962:AAG4SVKKlUOPlgJTINLfxtD09duB_YSkHOw".to_string()); - Commands::repl(bot, callback).await; + Commands::repl(bot, handler).await; } - -#[derive(BotCommands, Clone, Debug)] -#[command(rename_rule = "lowercase", description = "Поддерживаемые команды:")] -enum Commands { - #[command(description = "Команда для отображения инструкции")] - Help, - #[command(description = "Снимается мьют.")] - DemocracyUnmute, - #[command(description = "Банит человека. Для этого необходимо \ - 1. Сделать реплай на сообщение человека, которого вы хотите забанить; \ - 2. Указать причину бана." - )] - Nuremberg(String), - #[command(description = "Мьют человека. Для этого необходимо \ - 1. Сделать реплай на сообщение человека, которого вы хотите замьютить; \ - 2. Указатножитель мьюта.", - parse_with = "split")] - DemocracyMute(i64, String), -} - -async fn callback(bot: Bot, msg: Message, commands: Commands) -> ResponseResult<()> { - - match commands { - Commands::Help => { - bot.send_message(msg.chat.id, Commands::descriptions().to_string()).await?; - }, - Commands::Nuremberg(reason) => { - if is_admin_check(&msg, &bot).await { - let reason_result = if reason.is_empty() { None } else { Some(reason) }; - let _ = ban_user( - msg.reply_to_message(), - reason_result, - &bot, - msg.chat.id, - ).await; - } - }, - Commands::DemocracyMute(multiplier, reason) => { - if let 1i64..=10i64 = multiplier{ - if is_admin_check(&msg, &bot).await { - let _ = mute_user( - msg.reply_to_message(), - multiplier, - reason.to_string(), - &bot, - msg.chat.id, - ).await; - } - } else if let 10i64..=i64::MAX = multiplier{ - bot.send_message( - msg.chat.id, - "Вы ввели слишком большой множитель, пожалуйста, \ - выберите множитель из промежутка [1; 10]" - ).await - .expect("Вы ввели слишком большой множитель, пожалуйста, \ - выберите множитель из промежутка [1; 10]"); - } else { - bot.send_message( - msg.chat.id, - "Вы ввели нулевой или отрицательный множитель, пожалуйста, \ - выберите множитель из промежутка [1; 10]" - ).await - .expect("Вы ввели нулевой или отрицательный множитель, пожалуйста, \ - выберите множитель из промежутка [1; 10]"); - } - } - Commands::DemocracyUnmute => { - if is_admin_check(&msg, &bot).await { - let _ = unmute( - msg.reply_to_message(), - &bot, - msg.chat.id, - ).await; - } - } - }; - Ok(()) -} \ No newline at end of file diff --git a/src/mute.rs b/src/mute.rs deleted file mode 100644 index d671614..0000000 --- a/src/mute.rs +++ /dev/null @@ -1,88 +0,0 @@ -pub mod mute { - use teloxide::Bot; - use teloxide::requests::Requester; - use tokio::time::{sleep, Duration}; - use chrono::{Duration as ChronoDuration, Local}; - use teloxide::payloads::RestrictChatMemberSetters; - use teloxide::types::{ChatId, ChatPermissions, InputFile, Message, MessageKind}; - - pub async fn mute_user( - replied_message: Option<&Message>, - multiplier: i64, - reason: String, - bot: &Bot, - chat_id: ChatId) -> Result - { - if let None = replied_message { - bot.send_message( - chat_id, - "Ответьте на сообщение человека, которого вы хотите замьютить".to_string() - ).await.unwrap(); - Err("Ответьте на сообщение человека, которого вы хотите замьютить".to_string()) - } else { - match &replied_message.unwrap().kind { - MessageKind::Common(message) => { - if let None = message.from { - bot.send_message(chat_id, "Сообщение не найдено").await.unwrap(); - Err("Сообщение не найдено".to_string()) - } else if let Some(user) = &message.from { - let dice_value = bot.send_dice(chat_id) - .await - .unwrap() - .dice() - .unwrap() - .value as i64; - - let duration = Local::now().naive_utc() + ChronoDuration::hours(multiplier * dice_value); - - sleep(Duration::from_secs(4)).await ; - - match bot.restrict_chat_member( - chat_id, - user.id, - ChatPermissions::from_bits(0).unwrap() - ).until_date(duration.and_utc()) - .await - { - Ok(_) => { - bot.send_message( - chat_id, - format!("На пользователя {} повесили железный зановес на {} часов по причине \"{}\" ", - user.first_name, - multiplier * dice_value, - reason - ) - ).await - .unwrap(); - bot.send_sticker( - chat_id, - InputFile::file_id("CAACAgIAAxkBAAEpgP1lzmlmReALF20lHlRRGRvQ_SSCDAACqjwAAiIpSUkOv2XNIRmlYTQE") - ).await; - Ok("Демократия была совершена".to_string()) - } - Err(error) => { - bot.send_message( - chat_id, - error.to_string() + &*format!( - ". Результат в часах: {}", - multiplier * dice_value - ).to_string() - ).await - .unwrap(); - Err(error.to_string()) - } - } - } else { - bot.send_message(chat_id, "Ошибка номер хуй") - .await - .unwrap(); - Err("Ошибка номер хуй".to_string()) - } - } - _ => { - Err("тест".to_string()) - } - } - } - } -} \ No newline at end of file diff --git a/src/is_admin.rs b/src/utils/is_admin.rs similarity index 100% rename from src/is_admin.rs rename to src/utils/is_admin.rs