Skip to content
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

Swap to native async traits where possible #310

Draft
wants to merge 5 commits into
base: next
Choose a base branch
from
Draft
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 change: 0 additions & 1 deletion Cargo.lock

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

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ repository = "https://github.com/serenity-rs/poise/"
tokio = { version = "1.25.1", default-features = false } # for async in general
futures-util = { version = "0.3.13", default-features = false } # for async in general
poise_macros = { path = "macros", version = "0.6.1" } # remember to update the version on changes!
async-trait = { version = "0.1.48", default-features = false } # various traits
regex = { version = "1.6.0", default-features = false, features = ["std"] } # prefix
tracing = { version = "0.1.40", features = ["log"] } # warning about weird state
derivative = "2.2.0"
Expand Down
4 changes: 2 additions & 2 deletions macros/src/command/slash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ pub fn generate_parameters(inv: &Invocation) -> Result<Vec<proc_macro2::TokenStr
quote::quote! { Some(|o| o.kind(::poise::serenity_prelude::CommandOptionType::Integer)) }
} else {
quote::quote! { Some(|o| {
poise::create_slash_argument!(#type_, o)
<#type_ as poise::SlashArgument>::create(o)
#min_value_setter #max_value_setter
#min_length_setter #max_length_setter
}) }
Expand All @@ -101,7 +101,7 @@ pub fn generate_parameters(inv: &Invocation) -> Result<Vec<proc_macro2::TokenStr
__non_exhaustive: (),
} ),*]) }
} else {
quote::quote! { poise::slash_argument_choices!(#type_) }
quote::quote! { <#type_ as ::poise::SlashArgument>::choices() }
}
} else {
quote::quote! { Cow::Borrowed(&[]) }
Expand Down
2 changes: 1 addition & 1 deletion macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ for example for command-specific help (i.e. `~help command_name`). Escape newlin
SlashContext, which contain a variety of context data each. Context provides some utility methods to
access data present in both PrefixContext and SlashContext, like `author()` or `created_at()`.

All following parameters are inputs to the command. You can use all types that implement `poise::PopArgument`, `serenity::ArgumentConvert` or `std::str::FromStr`.
All following parameters are inputs to the command. You can use all types that implement `PopArgument` (for prefix) or `SlashArgument` (for slash).
You can also wrap types in `Option` or `Vec` to make them optional or variadic. In addition, there
are multiple attributes you can use on parameters:

Expand Down
59 changes: 59 additions & 0 deletions src/argument.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use std::str::FromStr;

use crate::{
serenity_prelude as serenity, PopArgument, PopArgumentResult, SlashArgError, SlashArgument,
};

/// A wrapper for `T` to implement [`SlashArgument`] and [`PopArgument`] via [`FromStr`].
///
/// This is useful if you need to take an argument via a string, but immediately convert it via [`FromStr`].
pub struct StrArg<T>(pub T);

impl<T> SlashArgument for StrArg<T>
where
T: FromStr,
T::Err: std::error::Error + Send + Sync + 'static,
{
fn create(builder: serenity::CreateCommandOption) -> serenity::CreateCommandOption {
builder.kind(serenity::CommandOptionType::String)
}

async fn extract(
_: &serenity::Context,
_: &serenity::CommandInteraction,
value: &serenity::ResolvedValue<'_>,
) -> Result<Self, SlashArgError> {
let serenity::ResolvedValue::String(value) = value else {
return Err(SlashArgError::new_command_structure_mismatch(
"expected a String",
));
};

match T::from_str(value) {
Ok(value) => Ok(Self(value)),
Err(err) => Err(SlashArgError::Parse {
error: err.into(),
input: String::from(*value),
}),
}
}
}

impl<'a, T> PopArgument<'a> for StrArg<T>
where
T: FromStr,
T::Err: std::error::Error + Send + Sync + 'static,
{
async fn pop_from(
args: &'a str,
attachment_index: usize,
ctx: &serenity::Context,
msg: &serenity::Message,
) -> PopArgumentResult<'a, Self> {
let (args, attach_idx, value) = String::pop_from(args, attachment_index, ctx, msg).await?;
match T::from_str(&value) {
Ok(value) => Ok((args, attach_idx, Self(value))),
Err(err) => Err((Box::new(err), Some(value))),
}
}
}
9 changes: 3 additions & 6 deletions src/choice_parameter.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Contains the [`ChoiceParameter`] trait and the blanket [`crate::SlashArgument`] and
//! [`crate::PopArgument`] impl

use crate::{serenity_prelude as serenity, CowVec};
use crate::{serenity_prelude as serenity, CowVec, PopArgumentResult};

/// This trait is implemented by [`crate::macros::ChoiceParameter`]. See its docs for more
/// information
Expand All @@ -22,7 +22,6 @@ pub trait ChoiceParameter: Sized {
fn localized_name(&self, locale: &str) -> Option<&'static str>;
}

#[async_trait::async_trait]
impl<T: ChoiceParameter> crate::SlashArgument for T {
async fn extract(
_: &serenity::Context,
Expand Down Expand Up @@ -55,17 +54,15 @@ impl<T: ChoiceParameter> crate::SlashArgument for T {
}
}

#[async_trait::async_trait]
impl<'a, T: ChoiceParameter> crate::PopArgument<'a> for T {
async fn pop_from(
args: &'a str,
attachment_index: usize,
ctx: &serenity::Context,
msg: &serenity::Message,
) -> Result<(&'a str, usize, Self), (Box<dyn std::error::Error + Send + Sync>, Option<String>)>
{
) -> PopArgumentResult<'a, Self> {
let (args, attachment_index, s) =
crate::pop_prefix_argument!(String, args, attachment_index, ctx, msg).await?;
<String as crate::PopArgument<'a>>::pop_from(args, attachment_index, ctx, msg).await?;

Ok((
args,
Expand Down
14 changes: 6 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ For another example of subcommands, see `examples/feature_showcase/subcommands.r
Also see the [`command`] macro docs

```rust
use poise::serenity_prelude as serenity;
use poise::{StrArg, serenity_prelude as serenity};
type Data = ();
type Error = Box<dyn std::error::Error + Send + Sync>;
type Context<'a> = poise::Context<'a, Data, Error>;
Expand All @@ -190,9 +190,9 @@ type Context<'a> = poise::Context<'a, Data, Error>;
)]
async fn my_huge_ass_command(
ctx: Context<'_>,
#[description = "Consectetur"] ip_addr: std::net::IpAddr, // implements FromStr
#[description = "Amet"] user: serenity::Member, // implements ArgumentConvert
#[description = "Sit"] code_block: poise::CodeBlock, // implements PopArgument
#[description = "Amet"] user: serenity::Member,
#[description = "Consectetur"] #[rename = "ip_addr"] StrArg(ip_addr): StrArg<std::net::IpAddr>,
#[description = "Sit"] code_block: poise::CodeBlock,
#[description = "Dolor"] #[flag] my_flag: bool,
#[description = "Ipsum"] #[lazy] always_none: Option<String>,
#[description = "Lorem"] #[rest] rest: String,
Expand Down Expand Up @@ -381,6 +381,7 @@ underlying this framework, so that's what I chose.
Also, poise is a stat in Dark Souls
*/

mod argument;
pub mod builtins;
pub mod choice_parameter;
pub mod cooldown;
Expand All @@ -400,7 +401,7 @@ pub mod macros {

#[doc(no_inline)]
pub use {
choice_parameter::*, cooldown::*, dispatch::*, framework::*, macros::*, modal::*,
argument::*, choice_parameter::*, cooldown::*, dispatch::*, framework::*, macros::*, modal::*,
prefix_argument::*, reply::*, slash_argument::*, structs::*, track_edits::*,
};

Expand All @@ -410,9 +411,6 @@ pub mod samples {
pub use crate::builtins::*;
}

#[doc(hidden)]
pub use {async_trait::async_trait, futures_util};

/// This module re-exports a bunch of items from all over serenity. Useful if you can't
/// remember the full paths of serenity items.
///
Expand Down
26 changes: 15 additions & 11 deletions src/modal.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! Modal trait and utility items for implementing it (mainly for the derive macro)

use std::future::Future;

use crate::serenity_prelude as serenity;

/// Meant for use in derived [`Modal::parse`] implementation
Expand Down Expand Up @@ -40,10 +42,7 @@ pub fn find_modal_text(

/// Underlying code for the modal spawning convenience function which abstracts over the kind of
/// interaction
async fn execute_modal_generic<
M: Modal,
F: std::future::Future<Output = Result<(), serenity::Error>>,
>(
async fn execute_modal_generic<M: Modal, F: Future<Output = Result<(), serenity::Error>>>(
ctx: &serenity::Context,
create_interaction_response: impl FnOnce(serenity::CreateInteractionResponse) -> F,
modal_custom_id: String,
Expand Down Expand Up @@ -169,7 +168,6 @@ pub async fn execute_modal_on_component_interaction<M: Modal>(
/// Ok(())
/// }
/// ```
#[async_trait::async_trait]
pub trait Modal: Sized {
/// Returns an interaction response builder which creates the modal for this type
///
Expand All @@ -187,18 +185,24 @@ pub trait Modal: Sized {
///
/// For a variant that is triggered on component interactions, see [`execute_modal_on_component_interaction`].
// TODO: add execute_with_defaults? Or add a `defaults: Option<Self>` param?
async fn execute<U: Send + Sync, E>(
fn execute<U: Send + Sync, E>(
ctx: crate::ApplicationContext<'_, U, E>,
) -> Result<Option<Self>, serenity::Error> {
execute_modal(ctx, None::<Self>, None).await
) -> impl Future<Output = Result<Option<Self>, serenity::Error>> + Send
where
Self: Send,
{
execute_modal(ctx, None::<Self>, None)
}

/// Calls `execute_modal(ctx, Some(defaults), None)`. See [`execute_modal`]
// TODO: deprecate this in favor of execute_modal()?
async fn execute_with_defaults<U: Send + Sync, E>(
fn execute_with_defaults<U: Send + Sync, E>(
ctx: crate::ApplicationContext<'_, U, E>,
defaults: Self,
) -> Result<Option<Self>, serenity::Error> {
execute_modal(ctx, Some(defaults), None).await
) -> impl Future<Output = Result<Option<Self>, serenity::Error>> + Send
where
Self: Send,
{
execute_modal(ctx, Some(defaults), None)
}
}
Loading
Loading