hookburn-slack 0.2.2

A Rust crate for sending messages to Slack via webhooks
Documentation
// crates/hookburn-slack/src/message.rs
use crate::error::SlackError;
use serde::Serialize;

/// A Slack webhook message.
#[derive(Debug, Clone, Serialize, Default)]
pub struct SlackMessage {
    /// Plain text content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// Block Kit blocks for rich formatting.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub blocks: Vec<SlackBlock>,
    /// Legacy attachments.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub attachments: Vec<SlackAttachment>,
    /// Thread timestamp to reply in a thread.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thread_ts: Option<String>,
    /// Broadcast reply to the channel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reply_broadcast: Option<bool>,
    /// Override the webhook's username.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub username: Option<String>,
    /// Override the webhook's icon (emoji).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon_emoji: Option<String>,
    /// Override the webhook's icon (URL).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon_url: Option<String>,
}

impl SlackMessage {
    /// Builder for messages
    pub fn builder() -> SlackMessageBuilder {
        SlackMessageBuilder::default()
    }
}

/// Block Kit block types.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub enum SlackBlock {
    /// Slack Section
    #[serde(rename = "section")]
    Section(SlackSectionBlock),
    /// Slack Divicer
    #[serde(rename = "divider")]
    Divider,
    /// Slack Header
    #[serde(rename = "header")]
    Header(SlackHeaderBlock),
    /// Slack Actions
    #[serde(rename = "actions")]
    Actions(SlackActionsBlock),
    /// Slack Context
    #[serde(rename = "context")]
    Context(SlackContextBlock),
}

/// A section block containing text, optional fields, and an optional accessory.
#[derive(Debug, Clone, Serialize)]
pub struct SlackSectionBlock {
    /// The main text content of the section.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<SlackText>,
    /// Additional fields displayed side-by-side below the text.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub fields: Vec<SlackText>,
    /// An optional accessory (image, button, etc.) displayed on the right.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accessory: Option<SlackAccessory>,
}

/// A header block.
#[derive(Debug, Clone, Serialize)]
pub struct SlackHeaderBlock {
    /// Slack Text
    pub text: SlackText,
}

/// An actions block containing interactive elements like buttons and date pickers.
#[derive(Debug, Clone, Serialize)]
pub struct SlackActionsBlock {
    /// The interactive elements (buttons, date pickers, etc.).
    pub elements: Vec<SlackElement>,
}

/// A context block with small text elements displayed in a subtle way.
#[derive(Debug, Clone, Serialize)]
pub struct SlackContextBlock {
    /// The text elements displayed in the context block.
    pub elements: Vec<SlackText>,
}
/// Interactive elements for actions blocks.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub enum SlackElement {
    /// Slack Button element
    #[serde(rename = "button")]
    Button(SlackButton),
    /// Slack Date element
    #[serde(rename = "datepicker")]
    DatePicker(SlackDatePicker),
}

/// A button element for interactive Slack messages.
#[derive(Debug, Clone, Serialize)]
pub struct SlackButton {
    /// The button label text.
    pub text: SlackText,
    /// The value sent when the button is clicked.
    pub value: String,
    /// Optional URL to navigate to when clicked (overrides action).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Optional button style: "primary" (green) or "danger" (red).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub style: Option<String>,
}

/// A date picker element for selecting dates in Slack messages.
#[derive(Debug, Clone, Serialize)]
pub struct SlackDatePicker {
    /// The placeholder text displayed before a date is selected.
    pub placeholder: SlackText,
    /// The action ID used to identify the interaction.
    pub action_id: String,
}

/// A text object with formatting options for Slack Block Kit.
#[derive(Debug, Clone, Serialize)]
pub struct SlackText {
    /// The type of text formatting: plain text or markdown.
    #[serde(rename = "type")]
    pub text_type: SlackTextType,
    /// The actual text content.
    pub text: String,
    /// Whether emoji should be rendered in plain text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub emoji: Option<bool>,
}

/// Supported text formatting types for Slack messages.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SlackTextType {
    /// Plain text with no formatting.
    PlainText,
    /// Markdown-style text with formatting support.
    Mrkdwn,
}

/// An accessory element that can be added to section blocks (e.g., images).
#[derive(Debug, Clone, Serialize)]
pub struct SlackAccessory {
    /// The type of accessory (e.g., "image").
    #[serde(rename = "type")]
    pub accessory_type: String,
    /// The URL of the image.
    pub image_url: String,
    /// Alternative text for accessibility.
    pub alt_text: String,
}

/// A legacy attachment for Slack messages (pre-Block Kit).
#[derive(Debug, Clone, Serialize)]
pub struct SlackAttachment {
    /// Optional color accent (hex string like "#36a64f").
    pub color: Option<String>,
    /// Optional text displayed above the attachment.
    pub pretext: Option<String>,
    /// The main text of the attachment.
    pub text: Option<String>,
    /// List of fields displayed in the attachment.
    pub fields: Vec<SlackAttachmentField>,
}

/// A field within a Slack attachment.
#[derive(Debug, Clone, Serialize)]
pub struct SlackAttachmentField {
    /// The field title displayed in bold.
    pub title: String,
    /// The field value.
    pub value: String,
    /// Whether the field should be displayed side-by-side with others.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub short: Option<bool>,
}

/// Builder for constructing Slack messages with a fluent API.
#[derive(Default)]
pub struct SlackMessageBuilder {
    inner: SlackMessage,
}

impl SlackMessageBuilder {
    /// Set the plain text content of the message.
    pub fn text(mut self, text: impl Into<String>) -> Self {
        self.inner.text = Some(text.into());
        self
    }

    /// Add a Block Kit block to the message.
    pub fn block(mut self, block: SlackBlock) -> Self {
        self.inner.blocks.push(block);
        self
    }

    /// Set all blocks for the message (replaces existing).
    pub fn blocks(mut self, blocks: Vec<SlackBlock>) -> Self {
        self.inner.blocks = blocks;
        self
    }

    /// Override the webhook's default username.
    pub fn username(mut self, username: impl Into<String>) -> Self {
        self.inner.username = Some(username.into());
        self
    }

    /// Override the webhook's icon using an emoji.
    pub fn icon_emoji(mut self, emoji: impl Into<String>) -> Self {
        self.inner.icon_emoji = Some(emoji.into());
        self
    }

    /// Override the webhook's icon using a URL.
    pub fn icon_url(mut self, url: impl Into<String>) -> Self {
        self.inner.icon_url = Some(url.into());
        self
    }

    /// Send the message as a threaded reply.
    pub fn thread_ts(mut self, ts: impl Into<String>) -> Self {
        self.inner.thread_ts = Some(ts.into());
        self
    }

    /// Broadcast the reply to the channel.
    pub fn reply_broadcast(mut self, broadcast: bool) -> Self {
        self.inner.reply_broadcast = Some(broadcast);
        self
    }

    /// Build the final Slack message.
    ///
    /// # Errors
    ///
    /// Returns `SlackError::EmptyMessage` if both `text` and `blocks` are empty.
    pub fn build(self) -> Result<SlackMessage, SlackError> {
        if self.inner.text.is_none() && self.inner.blocks.is_empty() {
            return Err(SlackError::EmptyMessage);
        }
        Ok(self.inner)
    }
}