Skip to content
Merged
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
2,347 changes: 1,052 additions & 1,295 deletions Cargo.lock

Large diffs are not rendered by default.

16 changes: 9 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,25 @@
name = "tabletbot"
version = "1.0.0"
authors = [ "InfinityGhost" ]
edition = "2021"
edition = "2024"

[dependencies]
# Serialization
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"
dotenvy = "0.15.7"
futures = "0.3.30"
aformat = "0.1.3"
4 changes: 4 additions & 0 deletions default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
, pkg-config
, openssl
, fetchurl
, aws-lc
, ...
}:

Expand All @@ -16,11 +17,14 @@ rustPlatform.buildRustPackage rec {

buildInputs = [
openssl
aws-lc
];

src = ./.;

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

};
}
6 changes: 3 additions & 3 deletions flake.lock

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

13 changes: 13 additions & 0 deletions src/commands/meta.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use crate::{Context, Error};

#[poise::command(prefix_command, hide_in_help)]
pub async fn register(ctx: Context<'_>) -> Result<(), Error> {
poise::builtins::register_application_commands_buttons(ctx).await?;

Ok(())
}

#[must_use]
pub fn commands() -> [crate::Command; 1] {
[register()]
}
49 changes: 25 additions & 24 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod meta;
pub mod snippets;
pub mod udev;
pub mod utils;
Expand All @@ -6,26 +7,30 @@ 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};

use poise::CreateReply;
use poise::serenity_prelude::{
self as serenity, Colour, ComponentInteraction, ComponentInteractionCollector, CreateActionRow,
CreateButton, CreateEmbed, CreateEmbedFooter, CreateInteractionResponse,
CreateInteractionResponseMessage,
};
use poise::CreateReply;

#[poise::command(prefix_command, hide_in_help)]
pub async fn register(ctx: Context<'_>) -> Result<(), Error> {
poise::builtins::register_application_commands_buttons(ctx).await?;

Ok(())
#[must_use]
pub fn commands() -> Vec<crate::Command> {
meta::commands()
.into_iter()
.chain(snippets::commands())
.chain(utils::commands())
.chain(udev::commands())
.collect()
}

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 +70,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 +97,16 @@ 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![
CreateButton::new(&*prev_button_id).emoji('◀'),
CreateButton::new(&*next_button_id).emoji('▶'),
]);
let components =
serenity::CreateComponent::ActionRow(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,9 +136,9 @@ 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))
while let Some(press) = ComponentInteractionCollector::new(ctx.serenity_context())
.filter(move |press| press.data.custom_id.starts_with(ctx_id.as_str()))
.timeout(std::time::Duration::from_mins(3))
.await
{
match Kind::from_id(&press.data.custom_id, &ctx_id) {
Expand All @@ -155,7 +156,7 @@ pub async fn paginate_lists(

press
.create_response(
ctx.serenity_context(),
ctx.http(),
CreateInteractionResponse::UpdateMessage(
CreateInteractionResponseMessage::new().embed(
serenity::CreateEmbed::new()
Expand Down
111 changes: 63 additions & 48 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::{
Context, Error,
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 @@ -118,9 +118,9 @@ pub async fn edit_snippet(
}

{
let mut rwlock_guard = ctx.data().state.write().unwrap();
let editing_snippet = rwlock_guard.snippets.iter_mut().find(|s| s.format_output().eq(&id_and_title)).unwrap();
*editing_snippet = snippet.clone();
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 All @@ -133,7 +133,7 @@ pub async fn edit_snippet(
let content = &&format!("The snippet '{id_and_title}' does not exist");
respond_err(&ctx, title, content).await;
}
};
}

Ok(())
}
Expand Down Expand Up @@ -209,8 +209,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 @@ -227,7 +229,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 @@ -282,12 +284,13 @@ 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![
serenity::CreateButton::new(&cancel_id).label("Cancel"),
serenity::CreateButton::new(&delete_id)
.label("Delete")
.style(serenity::ButtonStyle::Danger),
]);
let components =
serenity::CreateComponent::ActionRow(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 @@ -300,9 +303,9 @@ async fn remove_snippet_confirm(ctx: &Context<'_>, snippet: &Snippet) -> Result<

ctx.send(builder).await?;

while let Some(press) = serenity::ComponentInteractionCollector::new(ctx)
while let Some(press) = serenity::ComponentInteractionCollector::new(ctx.serenity_context())
.filter(move |press| press.data.custom_id.starts_with(&ctx_id.to_string()))
.timeout(std::time::Duration::from_secs(60))
.timeout(std::time::Duration::from_mins(1))
.await
{
if press.data.custom_id == delete_id {
Expand All @@ -323,7 +326,7 @@ async fn handle_delete(
rm_snippet(ctx, snippet);
interaction
.create_response(
ctx,
ctx.http(),
CreateInteractionResponse::UpdateMessage(
CreateInteractionResponseMessage::new()
.content("Deleted!")
Expand All @@ -346,7 +349,7 @@ async fn handle_cancel(
) -> Result<(), Error> {
interaction
.create_response(
ctx,
ctx.http(),
CreateInteractionResponse::UpdateMessage(
CreateInteractionResponseMessage::new()
.content("Aborted.")
Expand All @@ -357,3 +360,15 @@ async fn handle_cancel(
.await?;
Ok(())
}

#[must_use]
pub fn commands() -> [crate::Command; 6] {
[
snippet(),
create_snippet(),
remove_snippet(),
export_snippet(),
list_snippets(),
edit_snippet(),
]
}
Loading