Skip to content

Commit

Permalink
Merge branch 'arthomnix-master'
Browse files Browse the repository at this point in the history
  • Loading branch information
peterix committed Dec 22, 2024
2 parents af21626 + f8cf41f commit b87c036
Show file tree
Hide file tree
Showing 7 changed files with 178 additions and 27 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
RUST_LOG=error

DISCORD_TOKEN=
PASTE_EE_TOKEN=
BACKGROUND_CAT_PREFIX=-
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,27 @@ I made this bot because it was brought to my attention that other discords also

- Build the code: `cargo build --bin discord-cat`
- Copy `.env.example` to `target/debug/`
- Customize `target/debug/.env` and include your Discord token in it, like this:
- Customize `target/debug/.env` and include your Discord and paste.ee tokens in it, like this:
```
# See https://docs.rs/env_logger
RUST_LOG=error
DISCORD_TOKEN=AAa0AAa0AAAaAaa...
PASTE_EE_TOKEN=aaAAaAa0AaAA0...
BACKGROUND_CAT_PREFIX=-
```
- Run the bot: `cargo run -p discord-cat`

## Running in production

- Copy `.env.example` to `.env`
- Customize `.env` and include your Discord token in it, like this:
- Customize `.env` and include your Discord and paste.ee tokens in it, like this:
```
# See https://docs.rs/env_logger
RUST_LOG=error
DISCORD_TOKEN=AAa0AAa0AAAaAaa...
PASTE_EE_TOKEN=aaAAaAa0AaAA0...
BACKGROUND_CAT_PREFIX=-
```

Expand Down
3 changes: 2 additions & 1 deletion apps/discord-cat/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ kankyo = "0.3.0"
tokio = { version = "1.17.0", features = ["macros", "rt-multi-thread"] }
futures = "0.3.21"
serde = { version = "1.0.136", features = ["derive"] }
json = "0.12.4"

[dependencies.serenity]
version = "0.11.2"
default-features = false
features = ["client", "model", "gateway", "native_tls_backend", "cache", "utils", "framework", "standard_framework"]
features = ["client", "model", "collector", "gateway", "native_tls_backend", "cache", "utils", "framework", "standard_framework"]
165 changes: 144 additions & 21 deletions apps/discord-cat/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use lazy_static::lazy_static;
use log::{debug, error, info};
use regex::Regex;
use reqwest::get;
use std::{collections::HashSet, env};
use std::{collections::HashSet, env, time::Duration};
use futures::StreamExt;

use serenity::{
async_trait,
Expand All @@ -14,9 +15,12 @@ use serenity::{
channel::Message,
gateway::Ready,
id::{ChannelId, UserId},
user::User,
interactions::InteractionResponseType,
},
prelude::*,
utils::Colour,
builder::CreateButton,
};

use background_cat::common_mistakes;
Expand Down Expand Up @@ -120,14 +124,14 @@ impl EventHandler for Handler {
if origins.is_empty() {
let mistakes = common_mistakes(&log);
if ! mistakes.is_empty() {
send_help_reply(msg.channel_id, mistakes, ctx).await;
send_help_reply(msg.channel_id, mistakes, &ctx).await;
return;
} else {
info!("Didn't find any mistakes in log ({})", link.as_str());
}
} else {
info!("Detected pirated, custom or forked launcher ({})", link.as_str());
send_origins_reply(msg.channel_id, origins, ctx).await;
send_origins_reply(msg.channel_id, origins, &ctx).await;
return;
}

Expand All @@ -142,29 +146,35 @@ impl EventHandler for Handler {
if content_type.is_some() && str::starts_with(&content_type.unwrap(), "text/plain") {
let log = String::from_utf8_lossy(&content).into_owned();

let origins = common_origins(&log);
let paste_ee_future = upload_paste_ee(msg.channel_id, &log, &ctx, &msg.author);

if origins.is_empty() {
let mistakes = common_mistakes(&log);
let log_parse_future = async {
let origins = common_origins(&log);

if !mistakes.is_empty() {
debug!("Mistakes found: {:?}", mistakes);
send_help_reply(msg.channel_id, mistakes, ctx).await;
return;
if origins.is_empty() {
let mistakes = common_mistakes(&log);

if !mistakes.is_empty() {
debug!("Mistakes found: {:?}", mistakes);
send_help_reply(msg.channel_id, mistakes, &ctx).await;
return;
} else {
info!(
"Didn't find any mistakes in attachment ({})",
attachment.filename
);
}
} else {
info!(
"Didn't find any mistakes in attachment ({})",
"Detected pirated, custom or forked launcher ({})",
attachment.filename
);
send_origins_reply(msg.channel_id, origins, &ctx).await;
return;
}
} else {
info!(
"Detected pirated, custom or forked launcher ({})",
attachment.filename
);
send_origins_reply(msg.channel_id, origins, ctx).await;
return;
}
};

futures::join!(paste_ee_future, log_parse_future);
}
}
return;
Expand All @@ -184,8 +194,121 @@ impl EventHandler for Handler {
}
}

async fn upload_paste_ee(channel_id: ChannelId, log: &String, ctx: &Context, user: &User) {
let mut button = CreateButton::default();
button.custom_id("upload-log");
button.label("Upload Log");

match channel_id.send_message(&ctx, |m| {
m.embed(|e| {
e.title("Upload log to paste.ee?");
e.colour(Colour::DARK_TEAL);
e.description("This will make it easier for people to read your log.\nThis button only works for the user who sent the log.");
debug!("Embed: {:?}", e);
e
});
m.components(|c| {
c.create_action_row(|r| {
r.add_button(button);
r
});
debug!("Components: {:?}", c);
c
});
debug!("Embed: {:?}", m);
m
}).await {
Err(why) => error!("Couldn't send message: {}", why),
Ok(mut msg) => {
let mut interaction_stream = msg.await_component_interactions(&ctx).timeout(Duration::from_secs(180)).build();
let mut uploaded = false;

while let Some(interaction) = interaction_stream.next().await {
if interaction.user.id == user.id {
let paste_ee_token = env::var("PASTE_EE_TOKEN").expect("Expected paste.ee API token in $PASTE_EE_TOKEN");
let client = reqwest::Client::new();

let request_body = json::object! {
description: "MultiMC Background Cat Log Upload",
sections: [{ contents: log.as_str() }]
}.dump();

let response = json::parse(
client.post("https://api.paste.ee/v1/pastes")
.header("Content-Type", "application/json")
.header("X-Auth-Token", paste_ee_token)
.body(request_body)
.send()
.await.unwrap()
.text()
.await.unwrap()
.as_str()
).unwrap();

if !&response["success"].as_bool().unwrap_or_default() {
error!("paste.ee upload failed");
} else {
let link = &response["link"];

interaction.create_interaction_response(&ctx, |r| {
r.kind(InteractionResponseType::UpdateMessage).interaction_response_data(|d| {
d.embed(|e| {
e.title("Uploaded log");
e.colour(Colour::DARK_TEAL);
e.field("Log uploaded to paste.ee", link, true);
debug!("Embed: {:?}", e);
e
});
d.components(|c| c);
debug!("Interaction response data: {:?}", d);
d
});
debug!("Interaction response: {:?}", r);
r
}).await.unwrap();

uploaded = true;
info!("Uploaded attachment log to paste.ee: {}", link);
}
} else {
interaction.create_interaction_response(&ctx, |r| {
r.kind(InteractionResponseType::ChannelMessageWithSource).interaction_response_data(|d| {
d.ephemeral(true);
d.embed(|e| {
e.title("You are unauthorized to do this!");
e.colour(Colour::DARK_TEAL);
e.description("Only the user who sent the log can upload it to paste.ee.");
debug!("Embed: {:?}", e);
e
});
debug!("Interaction response data: {:?}", d);
d
});
debug!("Interaction response: {:?}", r);
r
}).await.unwrap();
}
}

if !uploaded {
msg.edit(&ctx, |m| {
m.embed(|e| {
e.title("Timed out");
e.colour(Colour::DARK_TEAL);
e.description("Log has not been uploaded");
debug!("Embed: {:?}", e);
e
});
m.components(|c| c);
debug!("Embed: {:?}", m);
m
}).await.unwrap();
}
}
}
}

async fn send_help_reply(channel_id: ChannelId, mistakes: Vec<(&str, String)>, ctx: Context) {
async fn send_help_reply(channel_id: ChannelId, mistakes: Vec<(&str, String)>, ctx: &Context) {
if let Err(why) = channel_id
.send_message(&ctx, |m| {
m.embed(|e| {
Expand All @@ -210,7 +333,7 @@ async fn send_help_reply(channel_id: ChannelId, mistakes: Vec<(&str, String)>, c
return;
}

async fn send_origins_reply(channel_id: ChannelId, origins: Vec<(&str, String)>, ctx: Context) {
async fn send_origins_reply(channel_id: ChannelId, origins: Vec<(&str, String)>, ctx: &Context) {
if let Err(why) = channel_id
.send_message(&ctx, |m| {
m.embed(|e| {
Expand Down
17 changes: 14 additions & 3 deletions libs/background-cat/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub fn common_mistakes(input: &str) -> Vec<(&str, String)> {

pub(crate) type Check = fn(&str) -> Option<(&str, String)>;

pub(crate) const PARSERS: [Check; 17] = [
pub(crate) const PARSERS: [Check; 18] = [
multimc_in_program_files,
macos_too_new_java,
multimc_in_onedrive_managed_folder,
Expand All @@ -30,6 +30,7 @@ pub(crate) const PARSERS: [Check; 17] = [
detect_temp_directories,
using_system_glfw,
using_system_openal,
reboot_required,
];

fn multimc_in_program_files(log: &str) -> Option<(&str, String)> {
Expand Down Expand Up @@ -217,6 +218,15 @@ fn using_system_glfw(log: &str) -> Option<(&str, String)> {
}
}

fn reboot_required(log: &str) -> Option<(&str, String)> {
const TRIGGER: &str = "Couldn't extract native jar";
if log.contains(TRIGGER) {
Some(("‼", RESPONSES.get("reboot-required")?.to_string()))
} else {
None
}
}

pub fn common_origins(input: &str) -> Vec<(&str, String)> {
ORIGINS.iter().flat_map(|m| m(input)).collect()
}
Expand Down Expand Up @@ -258,8 +268,9 @@ fn pirated_build(log: &str) -> Option<(&str, String)> {
fn forked_build(log: &str) -> Option<(&str, String)> {
const POLYMC_BUILD: &str = "PolyMC version: ";
const MANYMC_BUILD: &str = "ManyMC version: ";
const PRISM_BUILD: &str = "Prism Launcher version: ";

if log.contains(POLYMC_BUILD) || log.contains(MANYMC_BUILD) {
if log.contains(POLYMC_BUILD) || log.contains(MANYMC_BUILD) || log.contains(PRISM_BUILD) {
Some(("‼", RESPONSES.get("forked-build")?.to_string()))
} else {
None
Expand All @@ -274,4 +285,4 @@ fn m1_wrapper(log: &str) -> Option<(&str, String)> {
} else {
None
}
}
}
6 changes: 6 additions & 0 deletions libs/background-cat/src/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,12 @@ lazy_static! {
indoc! {
"You seem to be using your systems GLFW installation. This can cause the instance to crash if not properly setup. In case of a crash, make sure this isn't the cause of it."
}
),
(
"reboot-required",
indoc! {
"Another process appears to be locking your native library JARs. To solve this, please reboot your computer."
}
)
]);
}

0 comments on commit b87c036

Please sign in to comment.