REFACTORED: mute and ban action

This commit is contained in:
doryan 2024-06-02 03:34:56 +04:00
parent 8f43d91f5c
commit 561d2deb70
10 changed files with 131 additions and 105 deletions

View File

@ -1,62 +1,65 @@
use telers::{ use telers::{
event::{telegram::HandlerResult, EventReturn}, event::{telegram::HandlerResult, EventReturn},
types::{Message, User},
Bot, Bot,
}; };
use tokio::time::{sleep, Duration as DurationSleep}; use tokio::time::{sleep, Duration as DurationSleep};
use crate::{ use crate::{
types::structs::{ types::{
handler_entity::HandlerEntity, enums::target_user::TargetUser,
message_sender::{MessageSender, MessageSenderBuilder}, structs::handler_entity::{ExtractedEntityData, HandlerEntity},
}, },
utils::telegram::try_do::try_restrict, utils::telegram::try_do::try_restrict,
}; };
use crate::utils::telegram::ban_member::ban_chat_member; use crate::utils::telegram::ban_member::ban_chat_member;
pub async fn ban(handler_entity: HandlerEntity, chat_id: i64, delay: u64) -> HandlerResult { pub async fn ban(
let (bot, message, sender): (Bot, Message, MessageSenderBuilder) = ( handler_entity: HandlerEntity,
handler_entity.bot_instance, chat_id: i64,
handler_entity.message_reciever, user: TargetUser,
handler_entity.message_sender_builder, delay: u64,
); ) -> HandlerResult {
let (bot, message, mut sender_builder): ExtractedEntityData = handler_entity.extract();
let reply_to: Message; let user_id: i64 = match user.get_id() {
Some(id) => id,
if let Some(msg) = message.reply_to_message() { None => {
reply_to = msg.clone(); sender_builder
} else { .text("Ответьте на сообщение, чтобы забанить участника чата.")
sender .reply_to(message.id())
.reply_to(message.id()) .build()
.text("Ответьте на сообщение, чтобы забанить.") .send(&bot)
.build() .await
.send(&bot) .unwrap();
.await?; return Ok(EventReturn::Cancel);
return Ok(EventReturn::Cancel); }
} };
let user: &User = reply_to.from().unwrap();
sleep(DurationSleep::from_millis(delay)).await; sleep(DurationSleep::from_millis(delay)).await;
let future = || async { ban_chat_member(&bot, user.id, chat_id).await }; let future = || async { ban_chat_member(&bot, user_id, chat_id).await };
let demote_args: (&Bot, i64, i64) = (&bot, user.id, chat_id); let demote_args: (&Bot, i64, i64) = (&bot, user_id, chat_id);
let failure_sender: MessageSender = sender sender_builder
.clone() .set_text("Невозможно забанить участника чата, демотните своими силами и попробуйте снова");
.text("Невозможно забанить участника чата, демотните и попробуйте снова")
.build();
if try_restrict(future, demote_args, failure_sender) if try_restrict(future, demote_args, sender_builder.clone().build())
.await .await
.is_err() .is_err()
{ {
Ok(EventReturn::Cancel) Ok(EventReturn::Cancel)
} else { } else {
let banned_user_name: String = reply_to.from().unwrap().clone().username.unwrap(); let banned_user_name: String = message
.reply_to_message()
.unwrap()
.from()
.unwrap()
.clone()
.username
.unwrap();
sender sender_builder
.reply_to(message.id()) .reply_to(message.id())
.text(format!("Пользователь {} забанен.", banned_user_name)) .text(format!("Пользователь {} забанен.", banned_user_name))
.build() .build()

View File

@ -1,6 +1,5 @@
use telers::{ use telers::{
event::{telegram::HandlerResult, EventReturn}, event::{telegram::HandlerResult, EventReturn},
types::{Message, User},
Bot, Bot,
}; };
@ -8,79 +7,59 @@ use tokio::time::{sleep, Duration};
use crate::{ use crate::{
types::{ types::{
enums::time_metrics::TimeMetrics, enums::target_user::TargetUser,
structs::{ structs::handler_entity::{ExtractedEntityData, HandlerEntity},
countable_time::CountableTime, handler_entity::HandlerEntity, TimeValues,
message_sender::MessageSenderBuilder,
},
traits::countable_interface::ICountable,
}, },
utils::{ utils::{
general::unrestrict_date::unrestrict_date, general::get_duration::{get_duration, ExtractedDuration},
telegram::{restrict::restrict, try_do::try_restrict}, telegram::{restrict::restrict, try_do::try_restrict},
}, },
}; };
type HandlerEntityExtract = (Bot, Message, MessageSenderBuilder);
type TimeValues = (TimeMetrics, u64);
pub async fn mute( pub async fn mute(
handler_entity: HandlerEntity, handler_entity: HandlerEntity,
chat_id: i64, chat_id: i64,
values: TimeValues, user: TargetUser,
time: TimeValues,
) -> HandlerResult { ) -> HandlerResult {
let (bot, message, sender_builder): HandlerEntityExtract = ( let (bot, message, mut sender_builder): ExtractedEntityData = handler_entity.extract();
handler_entity.bot_instance,
handler_entity.message_reciever,
handler_entity.message_sender_builder,
);
let (metric, delay): TimeValues = values;
let reply_to: Message; let user_id: i64 = match user.get_id() {
Some(id) => id,
None => {
sender_builder
.text("Ответьте на сообщение, чтобы замьютить участника чата.")
.reply_to(message.id())
.build()
.send(&bot)
.await
.unwrap();
return Ok(EventReturn::Cancel);
}
};
if let Some(msg) = message.reply_to_message() { sleep(Duration::from_millis(time.1)).await;
reply_to = msg.clone();
} else {
sender_builder
.reply_to(message.id())
.text("Ответьте на сообщение, чтобы забанить.")
.build()
.send(&bot)
.await?;
return Ok(EventReturn::Cancel);
}
sleep(Duration::from_millis(delay)).await; let (unmute_date, postfix, mute_duration): ExtractedDuration = get_duration(time);
let demote_args: (&Bot, i64, i64) = (&bot, user_id, chat_id);
let callback = || async { restrict(&bot, user_id, unmute_date, chat_id).await };
let user: &User = reply_to.from().unwrap(); sender_builder.set_text("Невозможно замьютить участника чата, демотните и попробуйте снова");
let time_duration = metric.extract(); if try_restrict(callback, demote_args, sender_builder.clone().build())
let postfix = CountableTime::from_value(time_duration)
.get_postfix(metric)
.unwrap();
let unmute_date = unrestrict_date(time_duration);
let future = || async { restrict(&bot, user.id, unmute_date, chat_id).await };
let demote_args: (&Bot, i64, i64) = (&bot, user.id, chat_id);
let failure = sender_builder
.clone()
.text("Невозможно замьютить участника чата, демотните и попробуйте снова");
if try_restrict(future, demote_args, failure.build())
.await .await
.is_err() .is_err()
{ {
Ok(EventReturn::Cancel) Ok(EventReturn::Cancel)
} else { } else {
let muted_user_name = reply_to.from().unwrap().clone().username.unwrap(); let muted_user_name = message.from().unwrap().clone().username.unwrap();
sender_builder sender_builder
.reply_to(message.id()) .reply_to(message.id())
.text(format!( .text(format!(
"Пользователь {} замьючен на {:?} {}.", "Пользователь {} замьючен на {:?} {}.",
muted_user_name, time_duration, postfix muted_user_name, mute_duration, postfix
)) ))
.build() .build()
.send(&bot) .send(&bot)

View File

@ -1,13 +1,12 @@
use telers::{ use telers::{
event::{telegram::HandlerResult, EventReturn}, event::{telegram::HandlerResult, EventReturn},
methods::RestrictChatMember, methods::RestrictChatMember,
types::{ChatPermissions, Message}, types::ChatPermissions,
Bot,
}; };
use crate::types::{ use crate::types::{
enums::target_user::TargetUser, enums::target_user::TargetUser,
structs::{handler_entity::HandlerEntity, message_sender::MessageSenderBuilder}, structs::handler_entity::{ExtractedEntityData, HandlerEntity},
}; };
pub async fn unmute( pub async fn unmute(
@ -15,19 +14,9 @@ pub async fn unmute(
chat_id: i64, chat_id: i64,
user: TargetUser, user: TargetUser,
) -> HandlerResult { ) -> HandlerResult {
let (bot, message, sender_builder): (Bot, Message, MessageSenderBuilder) = ( let (bot, message, sender_builder): ExtractedEntityData = handler_entity.extract();
handler_entity.bot_instance,
handler_entity.message_reciever,
handler_entity.message_sender_builder,
);
let user_id: i64 = match user { let user_id: i64 = user.get_id().unwrap();
TargetUser::Id(id) => id,
TargetUser::Reply => message.reply_to_message().unwrap().from().unwrap().id,
_ => {
return Ok(EventReturn::Cancel);
}
};
let default_member_permissions = ChatPermissions::all() let default_member_permissions = ChatPermissions::all()
.can_change_info(false) .can_change_info(false)

View File

@ -62,7 +62,7 @@ pub async fn unmute_command(bot: Bot, message: Message, command: CommandObject)
) )
.await; .await;
} else { } else {
let on_reply = TargetUser::Reply; let on_reply = TargetUser::Reply(handler_entity.message_reciever.clone());
unmute(handler_entity, chat_id, on_reply).await?; unmute(handler_entity, chat_id, on_reply).await?;
} }
} }

View File

@ -7,7 +7,7 @@ use telers::{
use crate::{ use crate::{
handlers::actions::{ban::ban, mute::mute}, handlers::actions::{ban::ban, mute::mute},
types::{ types::{
enums::time_metrics::TimeMetrics, enums::{target_user::TargetUser, time_metrics::TimeMetrics},
structs::{handler_entity::HandlerEntity, message_sender::MessageSender}, structs::{handler_entity::HandlerEntity, message_sender::MessageSender},
}, },
}; };
@ -25,16 +25,23 @@ pub async fn dice_handler(bot: Bot, message: Message) -> HandlerResult {
}; };
let (mute_time, emoji): (TimeMetrics, &str) = (TimeMetrics::Days(dice.value), &dice.emoji); let (mute_time, emoji): (TimeMetrics, &str) = (TimeMetrics::Days(dice.value), &dice.emoji);
let target: TargetUser = TargetUser::Reply(handler_entity.message_reciever.clone());
match emoji { match emoji {
"🎲" => { "🎲" => {
mute(handler_entity, chat_id, (mute_time, DICE_DELAY_MS)).await?; mute(handler_entity, chat_id, target, (mute_time, DICE_DELAY_MS)).await?;
} }
"🎰" => { "🎰" => {
if dice.value == 64 { if dice.value == 64 {
ban(handler_entity, chat_id, CASINO_DELAY_MS).await?; ban(handler_entity, chat_id, target, CASINO_DELAY_MS).await?;
} else { } else {
mute(handler_entity, chat_id, (mute_time, CASINO_DELAY_MS)).await?; mute(
handler_entity,
chat_id,
target,
(mute_time, CASINO_DELAY_MS),
)
.await?;
} }
} }
_ => { _ => {

View File

@ -1,7 +1,19 @@
use telers::types::Message;
#[derive(Clone, Default, Debug)] #[derive(Clone, Default, Debug)]
pub enum TargetUser { pub enum TargetUser {
Id(i64), Id(i64),
Reply, Reply(Message),
#[default] #[default]
None, None,
} }
impl TargetUser {
pub fn get_id(&self) -> Option<i64> {
match self {
Self::Id(id) => Some(*id),
Self::Reply(msg) => Some(msg.reply_to_message().unwrap().from().unwrap().id),
Self::None => None,
}
}
}

View File

@ -1,5 +1,7 @@
use enums::time_metrics::TimeMetrics;
pub mod enums; pub mod enums;
pub mod structs; pub mod structs;
pub mod traits; pub mod traits;
pub type DynError = Box<dyn std::error::Error>; pub type TimeValues = (TimeMetrics, u64);

View File

@ -1,8 +1,21 @@
use crate::types::structs::message_sender::MessageSenderBuilder; use crate::types::structs::message_sender::MessageSenderBuilder;
use telers::{types::Message, Bot}; use telers::{types::Message, Bot};
pub type ExtractedEntityData = (Bot, Message, MessageSenderBuilder);
pub struct HandlerEntity { pub struct HandlerEntity {
pub bot_instance: Bot, pub bot_instance: Bot,
pub message_reciever: Message, pub message_reciever: Message,
pub message_sender_builder: MessageSenderBuilder, pub message_sender_builder: MessageSenderBuilder,
} }
impl HandlerEntity {
#[inline]
pub fn extract(self) -> ExtractedEntityData {
(
self.bot_instance,
self.message_reciever,
self.message_sender_builder,
)
}
}

View File

@ -0,0 +1,20 @@
use chrono::NaiveDateTime;
use crate::types::{
enums::time_metrics::TimeMetrics, structs::countable_time::CountableTime,
traits::countable_interface::ICountable, TimeValues,
};
use super::unrestrict_date::unrestrict_date;
pub type ExtractedDuration = (NaiveDateTime, String, i64);
pub fn get_duration(time: TimeValues) -> ExtractedDuration {
let time_duration = time.0.extract();
let unmute_date = unrestrict_date(time_duration);
let postfix = CountableTime::from_value(time_duration)
.get_postfix(time.0)
.unwrap();
(unmute_date, postfix, time_duration)
}

View File

@ -1 +1,2 @@
pub mod get_duration;
pub mod unrestrict_date; pub mod unrestrict_date;