BotDiscord/src/bot/handler.rs
2024-02-07 22:47:37 +00:00

108 lines
3.5 KiB
Rust

use rand::Rng;
use serenity::prelude::*;
use serenity::{
all::{Message, Ready},
async_trait,
builder::{CreateAttachment, CreateMessage},
client::Context,
};
use tokio::fs::File;
use crate::{
config::ConfigGlobal,
img::config_file::{ConfigImgGlobal, KeyWordItem},
};
pub struct Handler;
#[async_trait]
impl EventHandler for Handler {
async fn message(&self, ctx: Context, msg: Message) {
let chan_id: u64 = 675046560219791378;
if msg.author.bot
|| msg.content.starts_with("!")
|| !msg.channel_id.eq(&chan_id)
|| msg.content.len() == 0
{
return;
}
if msg.content == "&ping" {
if let Err(why) = msg.channel_id.say(&ctx.http, "Pong!").await {
println!("Error sending message: {:?}", why);
}
return;
}
let (config_img, config) = {
let data_read = ctx.data.read().await;
let config_img = data_read
.get::<ConfigImgGlobal>()
.expect("Config img not found")
.clone();
let config = data_read
.get::<ConfigGlobal>()
.expect("Main config not found")
.clone();
(config_img, config)
};
if config_img.keyword.len() == 0 || msg.content.len() > 50 {
return;
}
let folder_container = match config_img
.keyword
.iter()
.find(|keyword| keyword.does_value_match(msg.content.clone()))
{
Some(keyword_matching) => {
println!("{} match {:?}", msg.content, keyword_matching);
let keyword_path = match keyword_matching.path.len() {
0 => keyword_matching.path[0].clone(),
_ => {
let id: usize = {
let mut rng = rand::thread_rng();
rng.gen_range(0..keyword_matching.path.len())
};
keyword_matching.path[id].clone()
}
};
keyword_path.clone()
}
None => return,
};
let path = format!("{}/{}", config.image.path.clone(), folder_container);
let file_folder = KeyWordItem::output_folder_content(path.clone());
let id_rand: usize = {
let mut rng = rand::thread_rng();
rng.gen_range(0..file_folder.len())
};
let filename = match file_folder.get(id_rand) {
Some(file) => file.file_name().to_str().unwrap(),
None => return,
};
let file_path = format!("{}/{}", path, filename);
let file = match File::open(file_path).await {
Ok(file) => file,
Err(why) => {
println!("Error opening file: {:?}", why);
return;
}
};
let attachment = match CreateAttachment::file(&file, filename).await {
Ok(attachment) => attachment,
Err(why) => {
println!("Error creating attachment: {:?}", why);
return;
}
};
let builder = CreateMessage::new().add_file(attachment);
if let Err(why) = msg.channel_id.send_message(&ctx.http, builder).await {
println!("Error sending message: {:?}", why);
}
}
async fn ready(&self, _: Context, ready: Ready) {
println!("{} is connected!", ready.user.name);
}
}