serenity icon indicating copy to clipboard operation
serenity copied to clipboard

Statically prevent ‘invalid form body’ error when missing fields on `CreateButton`

Open lunacookies opened this issue 4 years ago • 1 comments

There are a number of rules around fields that must be present in button objects:

  • Non-link buttons must have a custom_id, and cannot have a url
  • Link buttons must have a url, and cannot have a custom_id
  • Link buttons do not send an interaction to your app when clicked

Furthermore, type and style are never optional, and must always be present.

However, CreateButton allows leaving all of these blank; when such an incomplete button object is sent to Discord, it returns an ‘invalid form body’ error.

This could be avoided statically through the typesystem by requiring certain fields for certain types of button. For instance, something like this might work:

struct CreateButton {
    kind: CreateButtonKind,
    label: String,
    emoji: Option<ReactionType>,
    disabled: bool,
}

impl CreateButton {
    fn new(kind: CreateButtonKind, label: String) -> Self {
        Self {
            kind,
            label,
            emoji: None,
            disabled: false,
        }
    }

    // methods to set fields
}

enum CreateButtonKind {
    Link {
        url: String,
    },
    NonLink {
        style: Style,
        custom_id: String,
    },
}

enum Style {
    Primary,
    Secondary,
    Success,
    Danger,
}

lunacookies avatar Jul 11 '21 04:07 lunacookies

Related: https://github.com/serenity-rs/serenity/issues/1905

kangalio avatar Sep 12 '22 12:09 kangalio

Implemented in #2166, this issue can be closed

kangalio avatar Oct 25 '22 23:10 kangalio