Skip to content

Commit

Permalink
option passthrough and edits on insights
Browse files Browse the repository at this point in the history
  • Loading branch information
ThomasByr committed Nov 27, 2023
1 parent 52fa3fd commit 4303503
Show file tree
Hide file tree
Showing 7 changed files with 127 additions and 70 deletions.
24 changes: 15 additions & 9 deletions src/commands/asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,19 +85,25 @@ pub async fn handle_request(
let (code, ext) = parser::get_message_attachment(&msg.attachments).await?;
if !code.is_empty() {
// content.push_str(&format!("\n```{}\n{}\n```\n", ext, code));
writeln!(content, "\n```{}\n{}\n```", ext, code).unwrap();
writeln!(content, "\n```{}\n{}\n```\n", ext, code).unwrap();
}

// parse user input
let comp_mngr = data_read.get::<CompilerCache>().unwrap();
let result =
match parser::get_components(&content, &author, Some(comp_mngr), &msg.referenced_message).await
{
Ok(r) => r,
Err(e) => {
return Err(CommandError::from(format!("{}", e)));
}
};
let result = match parser::get_components(
&content,
&author,
Some(comp_mngr),
&msg.referenced_message,
false,
)
.await
{
Ok(r) => r,
Err(e) => {
return Err(CommandError::from(format!("{}", e)));
}
};

// send out loading emote
if msg.react(&ctx.http, loading_reaction.clone()).await.is_err() {
Expand Down
11 changes: 8 additions & 3 deletions src/commands/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,14 @@ pub async fn handle_request(

// parse user input
let compilation_manager = data_read.get::<CompilerCache>().unwrap();
let parse_result =
parser::get_components(&content, &author, Some(compilation_manager), &msg.referenced_message)
.await?;
let parse_result = parser::get_components(
&content,
&author,
Some(compilation_manager),
&msg.referenced_message,
false,
)
.await?;

// send out loading emote
if msg.react(&ctx.http, loading_reaction.clone()).await.is_err() {
Expand Down
70 changes: 35 additions & 35 deletions src/commands/insights.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,36 @@
use serenity::builder::CreateEmbed;
use serenity::framework::standard::{macros::command, Args, CommandError, CommandResult};
use serenity::model::prelude::*;
use serenity::prelude::*;

use crate::apis::insights::InsightsRequest;

use crate::cache::{ConfigCache, InsightsAPICache};
use crate::utls::constants::{COLOR_FAIL, COLOR_OKAY};
use crate::utls::parser::ParserResult;
use crate::cache::{ConfigCache, InsightsAPICache, MessageCache, MessageCacheEntry};
use crate::utls::discordhelpers::embeds::build_insights_response_embed;
use crate::utls::{discordhelpers, parser};

#[command]
pub async fn insights(ctx: &Context, msg: &Message, _args: Args) -> CommandResult {
let embed = handle_request(ctx.clone(), msg.content.clone(), msg.author.clone(), msg).await?;
if let Ok(sent_msg) =
discordhelpers::embeds::dispatch_embed(&ctx.http, msg.channel_id, embed).await
{
// add delete cache
let data_read = ctx.data.read().await;
let mut delete_cache = data_read.get::<MessageCache>().unwrap().lock().await;
delete_cache.insert(msg.id.0, MessageCacheEntry::new(sent_msg, msg.clone()));
}

debug!("Command executed");
Ok(())
}

pub async fn handle_request(
ctx: Context,
content: String,
author: User,
msg: &Message,
) -> std::result::Result<CreateEmbed, CommandError> {
let data_read = ctx.data.read().await;
let insights_lock = data_read.get::<InsightsAPICache>().unwrap();
let botinfo_lock = data_read.get::<ConfigCache>().unwrap();
Expand All @@ -26,13 +46,16 @@ pub async fn insights(ctx: &Context, msg: &Message, _args: Args) -> CommandResul
}
};

let mut parse_result = ParserResult::default();
if !parser::find_code_block(&mut parse_result, &msg.content, &msg.author).await? {
return Err(CommandError::from("Unable to find a codeblock to format!"));
}
let parse_result =
parser::get_components(&content, &author, None, &msg.referenced_message, true).await?;

let req = InsightsRequest {
code: parse_result.code,
insights_options: vec![String::from("cpp2c")], // hard coded version for now
insights_options: if parse_result.options.is_empty() {
vec![String::from("cpp20"), String::from("use-libcpp")]
} else {
parse_result.options
},
};

if msg.react(&ctx.http, loading_reaction.clone()).await.is_err() {
Expand All @@ -45,35 +68,12 @@ pub async fn insights(ctx: &Context, msg: &Message, _args: Args) -> CommandResul
let insights = insights_lock.lock().await;
insights.get_insights(req).await
};

discordhelpers::delete_bot_reacts(ctx, msg, loading_reaction).await?;
discordhelpers::delete_bot_reacts(&ctx, msg, loading_reaction).await?;

if let Some(resp_obj) = resp {
let error = resp_obj.return_code != 0;
let sent = msg
.channel_id
.send_message(&ctx.http, |m| {
m.embed(|emb| {
emb
.color(if error { COLOR_FAIL } else { COLOR_OKAY })
.title("cppinsights.io")
.description(format!(
"```cpp\n{}\n```",
if error { resp_obj.stderr } else { resp_obj.stdout }
))
})
})
.await;

if let Ok(sent_msg) = sent {
discordhelpers::send_completion_react(ctx, &sent_msg, !error).await?;
}
info!("Insights response retval: {}", resp_obj.return_code);
Ok(build_insights_response_embed(&author, resp_obj))
} else {
return Err(CommandError::from(
"Unable to retrieve insights at this time! Please try again later.",
));
Err(CommandError::from("Unable to retrieve insights at this time! Please try again later."))
}

debug!("Command executed");
Ok(())
}
26 changes: 13 additions & 13 deletions src/tests/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ async fn standard_parse() {
);

let reply = None;
let result = get_components(input, &dummy_user, None, &reply).await;
let result = get_components(input, &dummy_user, None, &reply, false).await;
if result.is_err() {
panic!("Parser failed.");
}
Expand All @@ -41,7 +41,7 @@ async fn standard_parse_args() {
);

let reply = None;
let result = get_components(input, &dummy_user, None, &reply).await;
let result = get_components(input, &dummy_user, None, &reply, false).await;
if result.is_err() {
panic!("Parser failed.");
}
Expand All @@ -61,7 +61,7 @@ async fn standard_parse_url() {
let input = indoc::indoc!(";compile c++ < https://pastebin.com/raw/ERqDRZva");

let reply = None;
let result = get_components(input, &dummy_user, None, &reply).await;
let result = get_components(input, &dummy_user, None, &reply, false).await;
if result.is_err() {
panic!("Parser failed.");
}
Expand All @@ -81,7 +81,7 @@ async fn standard_parse_url_args() {
let input = indoc::indoc!(";compile c++ < https://pastebin.com/raw/ERqDRZva\ntest1 test2");

let reply = None;
let result = get_components(input, &dummy_user, None, &reply).await;
let result = get_components(input, &dummy_user, None, &reply, false).await;
if result.is_err() {
panic!("Parser failed.");
}
Expand All @@ -107,7 +107,7 @@ async fn standard_parse_stdin() {
);

let reply = None;
let result = get_components(input, &dummy_user, None, &reply).await;
let result = get_components(input, &dummy_user, None, &reply, false).await;
if result.is_err() {
panic!("Parser failed.");
}
Expand Down Expand Up @@ -135,7 +135,7 @@ async fn standard_parse_block_stdin() {
);

let reply = None;
let result = get_components(input, &dummy_user, None, &reply).await;
let result = get_components(input, &dummy_user, None, &reply, false).await;
if result.is_err() {
panic!("Parser failed.");
}
Expand All @@ -161,7 +161,7 @@ async fn standard_parse_deduce_compiler() {

let reply = None;
let cm = Arc::new(RwLock::new(CompilationManager::new().await.unwrap()));
let result = get_components(input, &dummy_user, Some(&cm), &reply).await;
let result = get_components(input, &dummy_user, Some(&cm), &reply, false).await;
if result.is_err() {
panic!("Parser failed.");
}
Expand All @@ -187,7 +187,7 @@ async fn standard_parse_deduce_compiler_upper_case() {

let reply = None;
let cm = Arc::new(RwLock::new(CompilationManager::new().await.unwrap()));
let result = get_components(input, &dummy_user, Some(&cm), &reply).await;
let result = get_components(input, &dummy_user, Some(&cm), &reply, false).await;
if result.is_err() {
panic!("Parser failed.");
}
Expand All @@ -213,7 +213,7 @@ async fn standard_parse_late_deduce_compiler() {

let reply = None;
let cm = Arc::new(RwLock::new(CompilationManager::new().await.unwrap()));
let result = get_components(input, &dummy_user, Some(&cm), &reply).await;
let result = get_components(input, &dummy_user, Some(&cm), &reply, false).await;
if result.is_err() {
panic!("Parser failed.");
}
Expand Down Expand Up @@ -242,7 +242,7 @@ async fn standard_parse_late_deduce_compiler_block_stdin() {

let reply = None;
let cm = Arc::new(RwLock::new(CompilationManager::new().await.unwrap()));
let result = get_components(input, &dummy_user, Some(&cm), &reply).await;
let result = get_components(input, &dummy_user, Some(&cm), &reply, false).await;
if result.is_err() {
panic!("Parser failed.");
}
Expand All @@ -263,7 +263,7 @@ async fn standard_parse_one_line() {

let reply = None;
let cm = Arc::new(RwLock::new(CompilationManager::new().await.unwrap()));
let result = get_components(input, &dummy_user, Some(&cm), &reply).await;
let result = get_components(input, &dummy_user, Some(&cm), &reply, false).await;
if result.is_err() {
panic!("Parser failed.");
}
Expand All @@ -283,7 +283,7 @@ async fn standard_parse_args_one_line() {
let input = indoc::indoc!(";compile c -O3```int main() {return 232;}```");

let reply = None;
let result = get_components(input, &dummy_user, None, &reply).await;
let result = get_components(input, &dummy_user, None, &reply, false).await;
if result.is_err() {
panic!("Parser failed.");
}
Expand All @@ -308,7 +308,7 @@ async fn parse_url_with_block_stdin() {
);

let reply = None;
let result = get_components(input, &dummy_user, None, &reply).await;
let result = get_components(input, &dummy_user, None, &reply, false).await;
if result.is_err() {
panic!("Parser failed.");
}
Expand Down
24 changes: 21 additions & 3 deletions src/utls/discordhelpers/embeds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use serenity::{
model::prelude::*,
};

use crate::apis::insights::InsightsResponse;
use crate::cache::LinkAPICache;
use crate::managers::compilation::CompilationDetails;
use wandbox::*;
Expand Down Expand Up @@ -264,6 +265,23 @@ pub fn build_small_compilation_embed(author: &User, res: &mut CompilationResult)
embed
}

pub fn build_insights_response_embed(author: &User, res: InsightsResponse) -> CreateEmbed {
let mut embed = CreateEmbed::default();

let error = res.return_code != 0;
if !error {
embed.color(COLOR_OKAY);
} else {
embed.color(COLOR_FAIL);
}

embed.description(format!("```cpp\n{}```", if error { res.stderr } else { res.stdout }));

embed.footer(|f| f.text(format!("Requested by: {} | Powered by cppinsights.io", author.tag())));

embed
}

pub fn embed_message(emb: CreateEmbed) -> CreateMessage<'static> {
let mut msg = CreateMessage::default();
msg.embed(|e| {
Expand Down Expand Up @@ -319,10 +337,10 @@ pub fn build_welcome_embed() -> CreateEmbed {
format!("{}compile python\n```py\nprint('hello world')\n```", prefix),
true,
);
embed.field("Learning Time!", "If you like reading the manuals of things, read our [wiki](https://github.com/ThomasByr/discord-compiler-bot/wiki/) wiki or if you are confident type `;help` to view all commands.", false);
embed.field("Support", "If you ever run into any issues please stop by our [github](https://github.com/ThomasByr/discord-compiler-bot) and we'll give you a hand.", true);
embed.field("Learning Time!", "If you like reading the manuals of things, read our [getting started](https://github.com/Headline/discord-compiler-bot/wiki/Getting-Started) wiki or if you are confident type `;help` to view all commands.", false);
embed.field("Support", "If you ever run into any issues please stop by our [support server](https://discord.com/invite/nNNEZ6s) and we'll give you a hand.", true);
embed.footer(|f| {
f.text("powered by godbolt.org & wandbox.org // created by Thomas Bouyer (blcklight#0)")
f.text("powered by godbolt.org & wandbox.org // created by Michael Flaherty (Headline#9999)")
});
embed
}
Expand Down
29 changes: 27 additions & 2 deletions src/utls/discordhelpers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,37 @@ pub async fn handle_edit(
let err = embeds::build_fail_embed(&author, &e.to_string());
embeds::edit_message_embed(ctx, &mut old, err, None).await;
}
} else if content.starts_with(&format!("{}insights", prefix)) {
if let Err(e) =
handle_edit_insights(ctx, content, author.clone(), old.clone(), original_message.clone())
.await
{
let err = embeds::build_fail_embed(&author, &e.to_string());
embeds::edit_message_embed(ctx, &mut old, err, None).await;
}
} else {
let err = embeds::build_fail_embed(&author, "Invalid command for edit functionality!");
embeds::edit_message_embed(ctx, &mut old, err, None).await;
}
}

pub async fn handle_edit_insights(
ctx: &Context,
content: String,
author: User,
mut old: Message,
original_msg: Message,
) -> CommandResult {
let embed =
crate::commands::insights::handle_request(ctx.clone(), content, author, &original_msg).await?;

let compilation_successful = embed.0.get("color").unwrap() == COLOR_OKAY;
discordhelpers::send_completion_react(ctx, &old, compilation_successful).await?;

embeds::edit_message_embed(ctx, &mut old, embed, None).await;
Ok(())
}

pub async fn handle_edit_cpp(
ctx: &Context,
content: String,
Expand Down Expand Up @@ -266,11 +291,11 @@ pub async fn send_global_presence(shard_manager: &MutexGuard<'_, ShardManager>,
};

// update shard guild count & presence
let presence_str = format!("{} guilds | ;help ({})", server_count, env!("CARGO_PKG_VERSION"));
let presence_str = format!("in {} servers | ;invite", server_count);

let runners = shard_manager.runners.lock().await;
for (_, v) in runners.iter() {
v.runner_tx.set_presence(Some(Activity::watching(&presence_str)), OnlineStatus::Online);
v.runner_tx.set_presence(Some(Activity::playing(&presence_str)), OnlineStatus::Online);
}
}

Expand Down
13 changes: 8 additions & 5 deletions src/utls/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ pub async fn get_components(
author: &User,
compilation_manager: Option<&Arc<RwLock<CompilationManager>>>,
reply: &Option<Box<Message>>,
ignore_lang: bool,
) -> Result<ParserResult, CommandError> {
let mut result = ParserResult::default();

Expand Down Expand Up @@ -81,11 +82,13 @@ pub async fn get_components(
}
} else {
// no compilation manager, just assume target is supplied
if let Some(param) = args.first() {
let lower_param = param.trim().to_lowercase();
let language = shortname_to_qualified(&lower_param);
args.remove(0);
result.target = language.to_owned();
if !ignore_lang {
if let Some(param) = args.first() {
let lower_param = param.trim().to_lowercase();
let language = shortname_to_qualified(&lower_param);
args.remove(0);
result.target = language.to_owned();
}
}
}

Expand Down

0 comments on commit 4303503

Please sign in to comment.