Skip to content

Commit

Permalink
rebase to serenity@next
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesbt365 committed Jun 20, 2024
1 parent e218a01 commit ddafdc9
Show file tree
Hide file tree
Showing 11 changed files with 797 additions and 454 deletions.
766 changes: 539 additions & 227 deletions Cargo.lock

Large diffs are not rendered by default.

14 changes: 8 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0" }

# Discord API
poise = "0.6"
serenity = "0.12"
serenity = { git = "https://github.com/serenity-rs/serenity", branch = "next" }
poise = { git = "https://github.com/serenity-rs/poise", branch = "serenity-next" }
tokio = { version = "1.29.1", features = ["macros", "signal", "rt-multi-thread"] }

# Misc
regex = "1.10.2"
octocrab = "0.19.0"
reqwest = "0.11.22"
regex = "1.10"
hex = "0.4.3"
to-arraystring = "0.1.3"
octocrab = "0.38"
reqwest = "0.12"
to-arraystring = "0.2"
arrayvec = "0.7.4"
futures = "0.3.30"
aformat = "0.1.3"
25 changes: 10 additions & 15 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ pub(crate) const ACCENT_COLOUR: Colour = Colour(0x8957e5);
pub(crate) const OK_COLOUR: Colour = Colour(0x2ecc71);
pub(crate) const ERROR_COLOUR: Colour = Colour(0xe74c3c);

use arrayvec::ArrayString;
use to_arraystring::ToArrayString;

use crate::{Context, Error};
Expand All @@ -24,7 +23,7 @@ pub async fn register(ctx: Context<'_>) -> Result<(), Error> {
Ok(())
}

pub async fn respond_embed(ctx: &Context<'_>, embed: CreateEmbed, ephemeral: bool) {
pub async fn respond_embed(ctx: &Context<'_>, embed: CreateEmbed<'_>, ephemeral: bool) {
let builder = poise::CreateReply::default()
.embed(embed)
.ephemeral(ephemeral);
Expand Down Expand Up @@ -64,7 +63,7 @@ pub async fn interaction_err(ctx: &serenity::Context, press: &ComponentInteracti
)
.ephemeral(true),
);
let _ = press.create_response(ctx, builder).await;
let _ = press.create_response(&ctx.http, builder).await;
}

enum Kind {
Expand All @@ -91,13 +90,8 @@ pub async fn paginate_lists(
) -> Result<(), Error> {
let ctx_id = ctx.id().to_arraystring();

let mut prev_button_id = ArrayString::<24>::new();
prev_button_id.push_str(&ctx_id);
prev_button_id.push_str("prev");

let mut next_button_id = ArrayString::<24>::new();
next_button_id.push_str(&ctx_id);
next_button_id.push_str("next");
let prev_button_id = format!("{ctx_id}prev");
let next_button_id = format!("{ctx_id}next");

let colour = Colour::TEAL;

Expand Down Expand Up @@ -134,10 +128,11 @@ pub async fn paginate_lists(
let msg = ctx.send(reply).await?;

if pages.len() > 1 {
while let Some(press) = ComponentInteractionCollector::new(ctx)
.filter(move |press| press.data.custom_id.starts_with(&ctx_id.to_string()))
.timeout(std::time::Duration::from_secs(180))
.await
while let Some(press) =
ComponentInteractionCollector::new(ctx.serenity_context().shard.clone())
.filter(move |press| press.data.custom_id.starts_with(ctx_id.as_str()))
.timeout(std::time::Duration::from_secs(180))
.await
{
match Kind::from_id(&press.data.custom_id, &ctx_id) {
Some(Kind::Next) => {
Expand All @@ -154,7 +149,7 @@ pub async fn paginate_lists(

press
.create_response(
ctx.serenity_context(),
ctx.http(),
CreateInteractionResponse::UpdateMessage(
CreateInteractionResponseMessage::new().embed(
serenity::CreateEmbed::new()
Expand Down
50 changes: 27 additions & 23 deletions src/commands/snippets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,29 +66,29 @@ pub async fn create_snippet(
#[description = "The snippet's title"] title: String,
#[description = "The snippet's content"] content: String,
) -> Result<(), Error> {
let snippet = Snippet {
id: id.clone(),
title,
content: content.replace(r"\n", "\n"),
};

let mut embed = snippet.embed();
embed = embed.colour(super::OK_COLOUR);

let embed = {
let mut rwlock_guard = ctx.data().state.write().unwrap();
let data = ctx.data();
let mut rwlock_guard = data.state.write().unwrap();

if let Some(position) = rwlock_guard.snippets.iter().position(|s| s.id.eq(&id)) {
rwlock_guard.snippets.remove(position);
}

let snippet = Snippet {
id,
title,
content: content.replace(r"\n", "\n"),
};

println!("New snippet created '{}: {}'", snippet.id, snippet.title);

let mut embed = snippet.embed();

embed = embed.colour(super::OK_COLOUR);

rwlock_guard.snippets.push(snippet);
rwlock_guard.snippets.push(snippet.clone());
rwlock_guard.write();

embed
embed.clone()
};

respond_embed(&ctx, embed, false).await;
Expand Down Expand Up @@ -117,7 +117,8 @@ pub async fn edit_snippet(
}

{
let mut rwlock_guard = ctx.data().state.write().unwrap();
let data = ctx.data();
let mut rwlock_guard = data.state.write().unwrap();
rwlock_guard.snippets.push(snippet.clone());
println!("Snippet edited '{}: {}'", snippet.title, snippet.content);
rwlock_guard.write();
Expand Down Expand Up @@ -206,8 +207,10 @@ pub async fn export_snippet(
) -> Result<(), Error> {
match get_snippet_lazy(&ctx, &id) {
Some(snippet) => {
let attachment =
CreateAttachment::bytes(snippet.content.replace('\n', r"\n"), "snippet.txt");
let attachment = CreateAttachment::bytes(
snippet.content.replace('\n', r"\n").into_bytes(),
"snippet.txt",
);
let message = poise::CreateReply::default()
.attachment(attachment)
.embed(snippet.embed());
Expand All @@ -224,7 +227,7 @@ pub async fn export_snippet(
}

impl Embeddable for Snippet {
fn embed(&self) -> CreateEmbed {
fn embed(&self) -> CreateEmbed<'_> {
CreateEmbed::default()
.title(&self.title)
.description(&self.content)
Expand Down Expand Up @@ -297,10 +300,11 @@ async fn remove_snippet_confirm(ctx: &Context<'_>, snippet: &Snippet) -> Result<

ctx.send(builder).await?;

while let Some(press) = serenity::ComponentInteractionCollector::new(ctx)
.filter(move |press| press.data.custom_id.starts_with(&ctx_id.to_string()))
.timeout(std::time::Duration::from_secs(60))
.await
while let Some(press) =
serenity::ComponentInteractionCollector::new(ctx.serenity_context().shard.clone())
.filter(move |press| press.data.custom_id.starts_with(&ctx_id.to_string()))
.timeout(std::time::Duration::from_secs(60))
.await
{
if press.data.custom_id == delete_id {
handle_delete(ctx, snippet, press).await?;
Expand All @@ -320,7 +324,7 @@ async fn handle_delete(
rm_snippet(ctx, snippet);
interaction
.create_response(
ctx,
ctx.http(),
CreateInteractionResponse::UpdateMessage(
CreateInteractionResponseMessage::new()
.content("Deleted!")
Expand All @@ -343,7 +347,7 @@ async fn handle_cancel(
) -> Result<(), Error> {
interaction
.create_response(
ctx,
ctx.http(),
CreateInteractionResponse::UpdateMessage(
CreateInteractionResponseMessage::new()
.content("Aborted.")
Expand Down
11 changes: 7 additions & 4 deletions src/commands/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,15 +161,15 @@ pub async fn edit_embed(
embedb = embedb.title(title);
}
} else if let Some(t) = &embed.title {
embedb = embedb.title(t);
embedb = embedb.title(t.as_str());
}

if let Some(description) = description {
if description != "_" {
embedb = embedb.description(description);
}
} else if let Some(d) = &embed.description {
embedb = embedb.description(d);
embedb = embedb.description(d.as_str());
}

if let Some(color) = color {
Expand Down Expand Up @@ -198,7 +198,7 @@ pub async fn edit_embed(
embedb = embedb.url(url);
}
} else if let Some(u) = &embed.url {
embedb = embedb.url(u);
embedb = embedb.url(u.as_str());
}

if let Some(image) = image {
Expand Down Expand Up @@ -291,7 +291,9 @@ pub async fn add_repo(
}

{
let mut rwlock_guard = { ctx.data().state.write().unwrap() };
let data = ctx.data();
let mut rwlock_guard = data.state.write().unwrap();

let details = RepositoryDetails {
owner: owner.clone(),
name: repository.clone(),
Expand All @@ -300,6 +302,7 @@ pub async fn add_repo(
rwlock_guard
.issue_prefixes
.insert(key.clone().to_lowercase(), details);

println!(
"Successfully added repository {} for **{}/{}**",
key.to_lowercase(),
Expand Down
46 changes: 30 additions & 16 deletions src/events/code.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,50 @@
use futures::future::join_all;
use regex::{Match, Regex};
use std::path::Path;
use std::str::FromStr;

use poise::serenity_prelude::{self as serenity, Colour, Context, CreateEmbed, Message};
use poise::serenity_prelude::{self as serenity, Colour, CreateEmbed, Http, Message};
use std::sync::Arc;

use crate::formatting::trim_indent;

use crate::FrameworkContext;

// A shade of purple.
const ACCENT_COLOUR: Colour = Colour::new(0x8957e5);

pub async fn message(ctx: &Context, message: &Message) {
if let Some(embeds) = get_embeds(ctx, message).await {
let typing = message.channel_id.start_typing(&ctx.http);
pub async fn message(framework: FrameworkContext<'_>, message: &Message) {
let http = &framework.serenity_context.http.clone();

let content = serenity::CreateMessage::default()
.embeds(embeds)
.reference_message(message);
let _ = message.channel_id.send_message(ctx, content).await;
let Some(file_refs) = get_file_refs(http.clone(), message) else {
return;
};

typing.stop();
}
// This is just cursed. I have no other way to explain this but its the only way I can figure
// out how to satisfy the lifetimes.
let embeds = join_all(file_refs.iter().map(FileReference::create_embed))
.await
.into_iter()
.flatten()
.collect::<Vec<_>>();

let typing = message.channel_id.start_typing(http.clone());

let content = serenity::CreateMessage::default()
.embeds(embeds)
.reference_message(message);
let _ = message.channel_id.send_message(http, content).await;

typing.stop();
}

async fn get_embeds(ctx: &Context, message: &Message) -> Option<Vec<CreateEmbed>> {
let typing = message.channel_id.start_typing(&ctx.http);
let mut embeds: Vec<CreateEmbed> = vec![];
fn get_file_refs(http: Arc<Http>, message: &Message) -> Option<Vec<FileReference<'_>>> {
let typing = message.channel_id.start_typing(http);
let mut embeds = vec![];

if let Some(refs) = FileReference::try_from_str(&message.content) {
for file_ref in refs {
if let Some(embed) = file_ref.create_embed().await {
embeds.push(embed);
}
embeds.push(file_ref);
}
}

Expand Down
Loading

0 comments on commit ddafdc9

Please sign in to comment.