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

View File

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

View File

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

View File

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

View File

@ -7,7 +7,7 @@ use telers::{
use crate::{
handlers::actions::{ban::ban, mute::mute},
types::{
enums::time_metrics::TimeMetrics,
enums::{target_user::TargetUser, time_metrics::TimeMetrics},
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 target: TargetUser = TargetUser::Reply(handler_entity.message_reciever.clone());
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 {
ban(handler_entity, chat_id, CASINO_DELAY_MS).await?;
ban(handler_entity, chat_id, target, CASINO_DELAY_MS).await?;
} 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)]
pub enum TargetUser {
Id(i64),
Reply,
Reply(Message),
#[default]
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 structs;
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 telers::{types::Message, Bot};
pub type ExtractedEntityData = (Bot, Message, MessageSenderBuilder);
pub struct HandlerEntity {
pub bot_instance: Bot,
pub message_reciever: Message,
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;