Cleanup :)

This commit is contained in:
Djkato 2023-07-14 16:41:16 +02:00
parent 6bd5da9c3a
commit 9f02f55479
4 changed files with 49 additions and 60 deletions

1
Cargo.lock generated
View file

@ -981,6 +981,7 @@ dependencies = [
"serenity", "serenity",
"serenity_utils", "serenity_utils",
"tokio", "tokio",
"url",
] ]
[[package]] [[package]]

View file

@ -16,3 +16,4 @@ serenity_utils = "0.7.0"
tokio = { version = "1.29.1", features = ["macros", "rt-multi-thread"] } tokio = { version = "1.29.1", features = ["macros", "rt-multi-thread"] }
rand = "0.8.4" rand = "0.8.4"
regex = "1.9.0" regex = "1.9.0"
url = "2.4.0"

View file

@ -1,9 +1,10 @@
use moove::moove;
use rand::random;
use serenity::async_trait; use serenity::async_trait;
use serenity::model::channel::Message; use serenity::model::channel::Message;
use serenity::model::gateway::Ready; use serenity::model::gateway::Ready;
use serenity::prelude::*; use serenity::prelude::*;
use util::security::dotenv_var; use util::security::dotenv_var;
use rand::random;
mod moove; mod moove;
mod util; mod util;
@ -13,6 +14,10 @@ struct Handler;
#[async_trait] #[async_trait]
impl EventHandler for Handler { impl EventHandler for Handler {
async fn message(&self, ctx: Context, msg: Message) { async fn message(&self, ctx: Context, msg: Message) {
match moove(ctx.http.clone(), msg.clone()).await {
Ok(_) => (),
Err(e) => println!("ERROR MOVING!{e}"),
}
if msg.content == "!ping" { if msg.content == "!ping" {
if let Err(why) = msg.channel_id.say(&ctx.http, "Pong!").await { if let Err(why) = msg.channel_id.say(&ctx.http, "Pong!").await {
println!("Error sending message: {:?}", why); println!("Error sending message: {:?}", why);
@ -24,7 +29,7 @@ impl EventHandler for Handler {
println!("{} is connected!", ready.user.name); println!("{} is connected!", ready.user.name);
let debug = match dotenv_var("DEBUG") { let debug = match dotenv_var("DEBUG") {
Some(v) => v, Some(v) => v,
None => "OFF".to_string() None => "OFF".to_string(),
}; };
if debug == "ON" { if debug == "ON" {
let messages = [ let messages = [
@ -36,13 +41,13 @@ impl EventHandler for Handler {
"Heyyyyy!", "Heyyyyy!",
"I'm baaaaack!", "I'm baaaaack!",
"Whom'st have summoned the ancient one?", "Whom'st have summoned the ancient one?",
]; ];
let rand_num = random::<usize>() % messages.len(); let rand_num = random::<usize>() % messages.len();
let channel = ctx.http.get_channel(780439236867653635).await.unwrap().id(); let channel = ctx.http.get_channel(780439236867653635).await.unwrap().id();
match channel.say(&ctx.http, messages[rand_num]).await { match channel.say(&ctx.http, messages[rand_num]).await {
Err(e) => println!("Something went wrong: {e}"), Err(e) => println!("Something went wrong: {e}"),
Ok(_) => return Ok(_) => return,
}; };
} }
} }
@ -52,8 +57,7 @@ impl EventHandler for Handler {
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<()> {
use anyhow::Context; use anyhow::Context;
let token = dotenv_var("TOKEN").context("No TOKEN in env")?; let token = dotenv_var("TOKEN").context("No TOKEN in env")?;
let intents = GatewayIntents::GUILD_MESSAGES let intents = GatewayIntents::GUILD_MESSAGES | GatewayIntents::MESSAGE_CONTENT;
| GatewayIntents::MESSAGE_CONTENT;
let mut client = Client::builder(&token, intents) let mut client = Client::builder(&token, intents)
.event_handler(Handler) .event_handler(Handler)

View file

@ -1,73 +1,56 @@
use std::sync::Arc;
use anyhow::{self, Context};
use poise::serenity_prelude::AttachmentType;
use serenity::builder::{CreateEmbed, CreateMessage}; use serenity::builder::{CreateEmbed, CreateMessage};
use serenity::model::channel::Message;
use serenity::http::Http; use serenity::http::Http;
use serenity::model::channel::Attachment; use serenity::model::channel::Attachment;
use anyhow; use serenity::model::channel::Message;
use serenity::model::mention; use serenity::model::mention;
use url::Url;
// use regex::Regex; // use regex::Regex;
// Checks if the message should be mooved, if not returns Ok(0) // Checks if the message should be mooved, if not returns Ok(0)
// If the message should be mooved, try to move it and return Ok(1) if mooved succesfully // If the message should be mooved, try to move it and return Ok(1) if mooved succesfully
// else returns Err() // else returns Err()
pub async fn moove(http: Http, msg: Message) -> Result<u8, String>{
pub async fn moove(http: Arc<Http>, msg: Message) -> anyhow::Result<()> {
let channel_mentions = msg.mention_channels; let channel_mentions = msg.mention_channels;
let words = msg.content.trim().split_whitespace().count(); let words = msg.content.trim().split_whitespace().count();
// let re = Regex::new(r"<#[0-9]*>$").unwrap(); // let re = Regex::new(r"<#[0-9]*>$").unwrap();
// if re.captures(content) // if re.captures(content)
if channel_mentions.len() != 1 || words != 1 { if channel_mentions.len() != 1 || words != 1 || msg.content.is_empty() {
return Ok(0); anyhow::bail!("no message worth processing");
} }
let mut msg_to_moove = match msg.referenced_message { let msg_to_moove = msg.referenced_message.context("no message present")?;
Some(m) => m,
None => return Ok(0)
};
let mentioned_channel = channel_mentions[0].id; let mentioned_channel = channel_mentions[0].id;
let attachments = msg_to_moove.attachments; //steals all attachments, but sets all of them as Image urls, so rip actual docs etc
let embeds = msg_to_moove.embeds; let attachments = msg_to_moove
.attachments
.into_iter()
.map(|att| AttachmentType::Image(Url::parse(att.url.as_str()).unwrap()));
let sent_by = format!("Sent by {}\n mooved {}\n", msg_to_moove.author, msg.author); //steals all the embeds
let embeds: Vec<CreateEmbed> = msg_to_moove
.embeds
.into_iter()
.map(|em| CreateEmbed::from(em))
.collect();
let mut embeds_copy : Vec<CreateEmbed> = Vec::new(); let mut new_content = format!("Sent by {}\n mooved {}\n", msg_to_moove.author, msg.author);
for embed in msg_to_moove.embeds { new_content += format!("Message:\n{}", msg_to_moove.content).as_str();
embeds_copy.push(CreateEmbed::from(embed));
}
// let mut attachment_links : Vec<String> = Vec::new(); mentioned_channel
let attachment_link = msg_to_moove.attachments.pop(); .send_message(http, |m| {
// for attachment in msg_to_moove.attachments { m.content(new_content)
// attachment_links.push(attachment.url); .add_embeds(embeds)
// } .add_files(attachments)
})
// if embeds_copy.len() > 0 || attachment_links.len() > 0 { .await?;
if embeds_copy.len() > 0 { Ok(())
let mut new_content = "".to_string();
if !msg_to_moove.content.is_empty() {
new_content = format!("Message:\n{}", msg_to_moove.content);
}
sent_by.push_str(&new_content);
match mentioned_channel.send_message(http, |m| {
m.content(sent_by).add_embeds(embeds_copy).add_file(attachment_link)
}).await {
Ok(_) => return Ok(0),
Err(e) => return Err(e.to_string())
};
}
else if !msg_to_moove.content.is_empty() {
match mentioned_channel.send_message(http, |m| {
m.add_embed(|e| {
e.title("MOO").field(sent_by, " ", false).field("Message:\n", msg_to_moove.content, false)
})
}).await {
Ok(_) => return Ok(0),
Err(e) => return Err(e.to_string())
};
}
Err("Something went wrong while mooving the message".to_string())
} }