Skip to content

rebase to serenity@next #42

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,893 changes: 1,152 additions & 741 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"
2 changes: 2 additions & 0 deletions default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,7 @@ rustPlatform.buildRustPackage rec {

cargoLock = {
lockFile = ./Cargo.lock;
allowBuiltinFetchGit = true;

};
}
7 changes: 3 additions & 4 deletions flake.lock

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

31 changes: 14 additions & 17 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ 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 std::borrow::Cow;

use to_arraystring::ToArrayString;

use crate::{Context, Error};
Expand All @@ -25,7 +26,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 @@ -65,7 +66,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 @@ -92,20 +93,15 @@ 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;

let components = CreateActionRow::Buttons(vec![
let components = CreateActionRow::Buttons(Cow::Owned(vec![
CreateButton::new(&*prev_button_id).emoji('◀'),
CreateButton::new(&*next_button_id).emoji('▶'),
]);
]));
let mut current_page = 0;

// Don't paginate if its one page.
Expand Down Expand Up @@ -135,10 +131,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 @@ -155,7 +152,7 @@ pub async fn paginate_lists(

press
.create_response(
ctx.serenity_context(),
ctx.http(),
CreateInteractionResponse::UpdateMessage(
CreateInteractionResponseMessage::new().embed(
serenity::CreateEmbed::new()
Expand Down
88 changes: 46 additions & 42 deletions src/commands/snippets.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
use std::borrow::Cow;

use crate::{
commands::{respond_embed, respond_err, respond_ok},
structures::{Embeddable, Snippet},
Context, Error,
};
use ::serenity::futures::{Stream, StreamExt};
use poise::serenity_prelude::{
self as serenity, futures, CreateAttachment, CreateEmbed, CreateInteractionResponse,
self as serenity, CreateAttachment, CreateEmbed, CreateInteractionResponse,
CreateInteractionResponseMessage,
};

#[allow(clippy::unused_async)]
async fn autocomplete_snippet<'a>(
ctx: Context<'a>,
ctx: Context<'_>,
partial: &'a str,
) -> impl Stream<Item = String> + 'a {
let snippet_list: Vec<String> = {
ctx.data()
.state
.read()
.unwrap()
.snippets
.iter()
.map(Snippet::format_output)
.collect()
};
) -> serenity::CreateAutocompleteResponse<'a> {
let snippet_list: Vec<_> = ctx
.data()
.state
.read()
.unwrap()
.snippets
.iter()
.map(Snippet::format_output)
.filter(|name| name.to_lowercase().contains(&partial.to_lowercase()))
.map(serenity::AutocompleteChoice::from)
.collect();

futures::stream::iter(snippet_list).filter(move |name| {
futures::future::ready(name.to_lowercase().contains(&partial.to_lowercase()))
})
serenity::CreateAutocompleteResponse::new().set_choices(snippet_list)
}

/// Show a snippet
Expand Down 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 @@ -279,12 +282,12 @@ async fn remove_snippet_confirm(ctx: &Context<'_>, snippet: &Snippet) -> Result<
let delete_id = format!("{ctx_id}cancel");
let cancel_id = format!("{ctx_id}delete");

let components = serenity::CreateActionRow::Buttons(vec![
let components = serenity::CreateActionRow::Buttons(Cow::Owned(vec![
serenity::CreateButton::new(&cancel_id).label("Cancel"),
serenity::CreateButton::new(&delete_id)
.label("Delete")
.style(serenity::ButtonStyle::Danger),
]);
]));

let builder: poise::CreateReply = poise::CreateReply::default()
.content(format!(
Expand All @@ -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
2 changes: 1 addition & 1 deletion src/commands/udev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub async fn generate_udev(
) -> Result<(), Error> {
let udev = gen_udev(vendor_id, product_id, libinput_override.unwrap_or(true));

let attachment = CreateAttachment::bytes(udev, "70-opentabletdriver.rules");
let attachment = CreateAttachment::bytes(udev.into_bytes(), "70-opentabletdriver.rules");
let embed = CreateEmbed::new()
.title("Generated udev rules")
.description(
Expand Down
25 changes: 15 additions & 10 deletions src/commands/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,30 @@ use crate::{
Context, Error,
};

use poise::serenity_prelude::{Colour, CreateEmbed, CreateEmbedFooter, EditMessage, Message};
use poise::serenity_prelude::{
self as serenity, Colour, CreateEmbed, CreateEmbedFooter, EditMessage, Message,
};
use regex::Regex;
use serenity::futures::{self, Stream, StreamExt};

#[allow(clippy::unused_async)]
async fn autocomplete_key<'a>(
ctx: Context<'a>,
partial: &'a str,
) -> impl Stream<Item = String> + 'a {
let snippet_list: Vec<String> = {
) -> serenity::CreateAutocompleteResponse<'a> {
let snippet_list: Vec<_> = {
ctx.data()
.state
.read()
.unwrap()
.issue_prefixes
.iter()
.map(|s| s.0.clone())
.filter(|name| name.contains(partial))
.map(serenity::AutocompleteChoice::from)
.collect()
};

futures::stream::iter(snippet_list)
.filter(move |name| futures::future::ready(name.contains(partial)))
serenity::CreateAutocompleteResponse::new().set_choices(snippet_list)
}

/// Create an embed in the current channel.
Expand Down Expand Up @@ -163,15 +165,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 @@ -200,7 +202,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 @@ -293,7 +295,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 @@ -302,6 +306,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
Loading