slack

package
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 26, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxSectionTextLen    = 3000
	MaxBlocksLen         = 50
	MaxModalBlocksLen    = 100
	MaxFieldTextLen      = 2000
	MaxBlockIDLen        = 255
	MaxMarkdownBlockLen  = 12000
	MaxPlainTextLen      = 150
	MaxButtonActionIDLen = 255
	MaxButtonTextLen     = 75
)

Slack Block Kit character limits (from official documentation)

View Source
const SlackTextLimit = 4000

SlackTextLimit is the maximum character limit for a single Slack message

View Source
const SocketModeURL = "wss://wss.slack.com/ws"

SocketModeURL is the Slack Socket Mode WebSocket endpoint

Variables

View Source
var ActionIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,255}$`)

ActionIDPattern validates action_id format (alphanumeric + _ - only, max 255 chars)

View Source
var AllowedFileTypes = map[string]bool{
	"pdf": true, "doc": true, "docx": true, "xls": true, "xlsx": true,
	"ppt": true, "pptx": true, "txt": true, "rtfd": true, "zip": true,
	"mp3": true, "mov": true, "mp4": true, "wav": true, "key": true,
}

AllowedFileTypes defines Slack-supported file extensions for file_input

View Source
var AllowedURLSchemes = []string{"http://", "https://", "mailto:", "ftp://"}

AllowedURLSchemes defines which URL schemes are allowed in links

View Source
var ButtonValuePattern = regexp.MustCompile(`^[a-zA-Z0-9_-]+:[a-zA-Z0-9_-]+:[a-zA-Z0-9_-]+$`)

ButtonValuePattern validates permission button values Format: behavior:sessionID:messageID (alphanumeric + _ - only)

Functions

func BuildAccessibilityLabel added in v0.12.0

func BuildAccessibilityLabel(label string) map[string]any

BuildAccessibilityLabel creates accessibility label for button

func BuildAccessoryImage added in v0.12.0

func BuildAccessoryImage(imageURL, altText string) map[string]any

BuildAccessoryImage creates an image accessory for section blocks Reference: https://api.slack.com/reference/block-kit/composition-objects#image

func BuildActionsBlock added in v0.12.0

func BuildActionsBlock(elements []map[string]any) []map[string]any

BuildActionsBlock creates an actions block with interactive elements Reference: https://api.slack.com/reference/block-kit/blocks#actions

func BuildAdvancedLayout added in v0.12.0

func BuildAdvancedLayout(title string, fields map[string]string, footer string) []map[string]any

BuildAdvancedLayout creates a complex layout using section/fields combinations

func BuildApprovalBlock added in v0.12.0

func BuildApprovalBlock(requestID, title, description string) []map[string]interface{}

BuildApprovalBlock creates a block with Approve/Reject buttons. Used for: dangerous command approval requests.

func BuildButton added in v0.12.0

func BuildButton(text, actionID, value string, style string) map[string]any

BuildButton creates a button element

func BuildButtonWithURL added in v0.12.0

func BuildButtonWithURL(text, actionID, url string) map[string]any

BuildButtonWithURL creates a button that opens a URL

func BuildButtonWithURLValidation added in v0.12.0

func BuildButtonWithURLValidation(text, actionID, rawURL string) (map[string]any, error)

BuildButtonWithURLValidation creates a button with URL validation

func BuildButtonWithValidation added in v0.12.0

func BuildButtonWithValidation(text, actionID, value string, style string) (map[string]any, error)

BuildButtonWithValidation creates a button with full validation

func BuildCallBlock added in v0.12.0

func BuildCallBlock(callID string) []map[string]any

BuildCallBlock creates a call block for huddles/meetings Reference: https://api.slack.com/reference/block-kit/blocks#call

func BuildChannelMention added in v0.12.0

func BuildChannelMention(channelID string) map[string]any

BuildChannelMention creates a channel mention for rich_text_section

func BuildCheckboxes added in v0.12.0

func BuildCheckboxes(options []map[string]any, actionID string, initialOptions []map[string]any) map[string]any

BuildCheckboxes creates a checkbox group

func BuildConfirmationBlock added in v0.12.0

func BuildConfirmationBlock(title, message string) []map[string]interface{}

BuildConfirmationBlock creates a simple confirmation message.

func BuildConfirmationDialog added in v0.12.0

func BuildConfirmationDialog(title, text, confirmText, denyText string) map[string]any

BuildConfirmationDialog creates a confirmation dialog Reference: https://api.slack.com/reference/block-kit/composition-objects#confirm

func BuildConfirmationDialogWithStyle added in v0.12.0

func BuildConfirmationDialogWithStyle(title, text, confirmText, denyText, style string) map[string]any

BuildConfirmationDialogWithStyle creates a confirmation dialog with style (primary/danger)

func BuildContextActionsBlock added in v0.12.0

func BuildContextActionsBlock(contextItems []map[string]any, actions []map[string]any) []map[string]any

BuildContextActionsBlock creates a context actions block for quick actions Reference: https://api.slack.com/reference/block-kit/blocks#context-actions-block

func BuildContextBlock added in v0.12.0

func BuildContextBlock(elements []map[string]any) []map[string]any

BuildContextBlock creates a context block with multiple elements Reference: https://api.slack.com/reference/block-kit/blocks#context

func BuildConversationFilter added in v0.12.0

func BuildConversationFilter(include []string, excludeBotUsers, excludeExternalSharedChannels bool) map[string]any

BuildConversationFilter creates a filter for conversations select

func BuildConversationsSelectWithFilter added in v0.12.0

func BuildConversationsSelectWithFilter(placeholder, actionID string, filter map[string]any, defaultToCurrentConversation bool) map[string]any

BuildConversationsSelectWithFilter creates a conversations select with filter

func BuildDatePicker added in v0.12.0

func BuildDatePicker(placeholder, actionID string, initialDate string) map[string]any

BuildDatePicker creates a date picker

func BuildDeliveryPolicy added in v0.12.0

func BuildDeliveryPolicy(persistence string) map[string]any

BuildDeliveryPolicy creates a delivery policy for messages

func BuildDispatchActionConfig added in v0.12.0

func BuildDispatchActionConfig(triggerActions []string) map[string]any

BuildDispatchActionConfig creates a dispatch action config for input elements Reference: https://api.slack.com/reference/block-kit/composition-objects#dispatch_action_config

func BuildDividerBlock added in v0.12.0

func BuildDividerBlock() []map[string]any

BuildDividerBlock creates a simple divider Reference: https://api.slack.com/reference/block-kit/blocks#divider

func BuildElementWithValidation added in v0.12.0

func BuildElementWithValidation(elemType, actionID string, validateFunc func() error) (map[string]any, error)

BuildElementWithValidation wraps element creation with validation

func BuildEmoji added in v0.12.0

func BuildEmoji(name string) map[string]any

BuildEmoji creates an emoji element for rich_text_section

func BuildExternalSelectWithMinQuery added in v0.12.0

func BuildExternalSelectWithMinQuery(placeholder, actionID string, minQueryLength int, initialOption map[string]any) map[string]any

BuildExternalSelectWithMinQuery creates an external select with minimum query length

func BuildFeedbackButtons added in v0.12.0

func BuildFeedbackButtons(positiveActionID, negativeActionID string) map[string]any

BuildFeedbackButtons creates thumbs up/down feedback buttons Reference: https://api.slack.com/reference/block-kit/block-elements#feedback-buttons-element

func BuildFileBlock added in v0.12.0

func BuildFileBlock(externalID string) []map[string]any

BuildFileBlock creates a file block (requires file to be uploaded first) Reference: https://api.slack.com/reference/block-kit/blocks#file

func BuildFileInput added in v0.12.0

func BuildFileInput(actionID string, filetypes []string, maxFiles int) map[string]any

BuildFileInput creates a file input element for file uploads Reference: https://api.slack.com/reference/block-kit/block-elements#file-input-element

func BuildFilter added in v0.12.0

func BuildFilter(includeTypes []string, excludeExternalSharedChannels bool) map[string]any

BuildFilter creates a filter for conversations_select Reference: https://api.slack.com/reference/block-kit/composition-objects#filter_conversations

func BuildHeaderBlock added in v0.12.0

func BuildHeaderBlock(text string) []map[string]any

BuildHeaderBlock creates a header block (text must be plain_text, max 150 chars) Reference: https://api.slack.com/reference/block-kit/blocks#header

func BuildIconButton added in v0.12.0

func BuildIconButton(iconName string, actionID string, confirm map[string]any) map[string]any

BuildIconButton creates an icon-only button (minimal UI) Reference: https://api.slack.com/reference/block-kit/block-elements#icon-button-element

func BuildImageBlock added in v0.12.0

func BuildImageBlock(imageURL, altText, title string) []map[string]any

BuildImageBlock creates an image block Reference: https://api.slack.com/reference/block-kit/blocks#image

func BuildInputBlock added in v0.12.0

func BuildInputBlock(label, placeholder string, element map[string]any, optional bool) map[string]any

BuildInputBlock creates an input block for modals Reference: https://api.slack.com/reference/block-kit/blocks#input

func BuildLink(text, url string) map[string]any

BuildLink creates a link for rich_text_section

func BuildMarkdownBlock added in v0.12.0

func BuildMarkdownBlock(markdownText string) []map[string]any

BuildMarkdownBlock creates a markdown block for rendering markdown content Reference: https://api.slack.com/reference/block-kit/blocks#markdown-block

func BuildMrkdwnText added in v0.12.0

func BuildMrkdwnText(text string, verbatim bool) map[string]any

BuildMrkdwnText creates a mrkdwn text object Reference: https://api.slack.com/reference/block-kit/composition-objects#text

func BuildMultiEmailInput added in v0.12.0

func BuildMultiEmailInput(actionID, placeholder string, maxValues int) map[string]any

BuildMultiEmailInput creates a multi-email input field

func BuildOption added in v0.12.0

func BuildOption(label, value string) map[string]any

BuildOption creates an option object for select menus, radio buttons, checkboxes Reference: https://api.slack.com/reference/block-kit/composition-objects#option

func BuildOptionGroup added in v0.12.0

func BuildOptionGroup(label string, options []map[string]any) map[string]any

BuildOptionGroup creates an option group for select menus Reference: https://api.slack.com/reference/block-kit/composition-objects#option-group

func BuildOptionWithDescription added in v0.12.0

func BuildOptionWithDescription(label, value, description string) map[string]any

BuildOptionWithDescription creates an option with description

func BuildOptionWithValidation added in v0.12.0

func BuildOptionWithValidation(label, value string) (map[string]any, error)

BuildOptionWithValidation creates an option with validation

func BuildPermissionApprovedBlocks added in v0.12.0

func BuildPermissionApprovedBlocks(tool, input string) []map[string]any

BuildPermissionApprovedBlocks builds blocks to show after permission is approved.

func BuildPermissionDeniedBlocks added in v0.12.0

func BuildPermissionDeniedBlocks(tool, input, reason string) []map[string]any

BuildPermissionDeniedBlocks builds blocks to show after permission is denied.

func BuildPermissionRequestBlocks added in v0.12.0

func BuildPermissionRequestBlocks(req *provider.PermissionRequest, sessionID string) []map[string]any

BuildPermissionRequestBlocks builds Slack Block Kit for a Claude Code permission request. It displays the tool name, command preview, and approval/denial buttons.

func BuildPlainText added in v0.12.0

func BuildPlainText(text string, emoji bool) map[string]any

BuildPlainText creates a plain_text text object

func BuildPlainTextInput added in v0.12.0

func BuildPlainTextInput(placeholder, actionID string, initialValue string, multiline bool, maxLength int, minLength int) map[string]any

BuildPlainTextInput creates a plain text input field

func BuildPlainTextInputWithValidation added in v0.12.0

func BuildPlainTextInputWithValidation(placeholder, actionID, initialValue string, multiline bool, maxLength, minLength int) (map[string]any, error)

BuildPlainTextInputWithValidation creates a plain text input with validation

func BuildPlanBlock added in v0.12.0

func BuildPlanBlock(title string, sections []map[string]any) []map[string]any

BuildPlanBlock creates a plan block for displaying structured plans Reference: https://api.slack.com/reference/block-kit/blocks#plan-block

func BuildPlanItem added in v0.12.0

func BuildPlanItem(text string, itemType string) map[string]any

BuildPlanItem creates an item for plan section

func BuildPlanSection added in v0.12.0

func BuildPlanSection(sectionTitle string, items []map[string]any, status string) map[string]any

BuildPlanSection creates a section for plan block

func BuildRadioButtons added in v0.12.0

func BuildRadioButtons(options []map[string]any, actionID string, initialOption map[string]any) map[string]any

BuildRadioButtons creates a radio button group

func BuildResponseURLPlaceholder added in v0.12.0

func BuildResponseURLPlaceholder(actionID string) map[string]any

BuildResponseURLPlaceholder creates a placeholder for response URLs

func BuildRichTextBlock added in v0.12.0

func BuildRichTextBlock(elements []map[string]any) []map[string]any

BuildRichTextBlock creates a rich_text block for formatted content Reference: https://api.slack.com/reference/block-kit/blocks#rich_text

func BuildRichTextElement added in v0.12.0

func BuildRichTextElement(elementType string, text string) map[string]any

BuildRichTextElement creates a rich text element

func BuildRichTextInput added in v0.12.0

func BuildRichTextInput(actionID, placeholder string, initialValue string, focusOnLoad bool) map[string]any

BuildRichTextInput creates a rich text input field Reference: https://api.slack.com/reference/block-kit/block-elements#rich-text-input-element

func BuildRichTextList added in v0.12.0

func BuildRichTextList(elements []map[string]any, style string) map[string]any

BuildRichTextList creates a rich_text_list element Reference: https://api.slack.com/reference/block-kit/block-elements#rich_text_list

func BuildRichTextPreformatted added in v0.12.0

func BuildRichTextPreformatted(elements []map[string]any) map[string]any

BuildRichTextPreformatted creates a rich_text_preformatted element

func BuildRichTextQuote added in v0.12.0

func BuildRichTextQuote(elements []map[string]any) map[string]any

BuildRichTextQuote creates a rich_text_quote element

func BuildRichTextRange added in v0.12.0

func BuildRichTextRange(start, end int, style map[string]any) map[string]any

BuildRichTextRange creates a rich text range for styling

func BuildRichTextSection added in v0.12.0

func BuildRichTextSection(elements []map[string]any) map[string]any

BuildRichTextSection creates a rich_text section element

func BuildRichTextSectionBold added in v0.12.0

func BuildRichTextSectionBold(text string) map[string]any

BuildRichTextSectionBold creates bold text element for rich_text_section

func BuildRichTextSectionCode added in v0.12.0

func BuildRichTextSectionCode(text string) map[string]any

BuildRichTextSectionCode creates code text element for rich_text_section

func BuildRichTextSectionItalic added in v0.12.0

func BuildRichTextSectionItalic(text string) map[string]any

BuildRichTextSectionItalic creates italic text element for rich_text_section

func BuildRichTextSectionLink(text, url string) map[string]any

BuildRichTextSectionLink creates link text element for rich_text_section

func BuildRichTextSectionText added in v0.12.0

func BuildRichTextSectionText(text string) map[string]any

BuildRichTextSectionText creates text element for rich_text_section

func BuildSectionBlock added in v0.12.0

func BuildSectionBlock(text string, fields []map[string]any, accessory map[string]any) []map[string]any

BuildSectionBlock creates a section block with text Reference: https://api.slack.com/reference/block-kit/blocks#section

func BuildSectionBlockWithFields added in v0.12.0

func BuildSectionBlockWithFields(fields []map[string]any) []map[string]any

BuildSectionBlockWithFields creates a section block with only fields (no text)

func BuildSelectionBlock added in v0.12.0

func BuildSelectionBlock(title string, options []SelectionOption) []map[string]interface{}

BuildSelectionBlock creates a block with selection buttons. Used for: multi-choice prompts.

func BuildSlackFileObject added in v0.12.0

func BuildSlackFileObject(id string, url string) map[string]any

BuildSlackFileObject creates a slack_file composition object

func BuildStaticSelect added in v0.12.0

func BuildStaticSelect(options []map[string]any, placeholder, actionID string, initialOption map[string]any) map[string]any

BuildStaticSelect creates a static select menu

func BuildStyleObject added in v0.12.0

func BuildStyleObject(bold, italic, strike, code bool) map[string]any

BuildStyleObject creates a style object for rich text

func BuildTableBlock added in v0.12.0

func BuildTableBlock(headers []string, rows [][]string, columns int) []map[string]any

BuildTableBlock creates a table block for displaying tabular data Reference: https://api.slack.com/reference/block-kit/blocks#table-block

func BuildTaskCardBlock added in v0.12.0

func BuildTaskCardBlock(title, description, assignee, dueDate, status string, actions []map[string]any) []map[string]any

BuildTaskCardBlock creates a task card block for task management Reference: https://api.slack.com/reference/block-kit/blocks#task-card-block

func BuildTriggerObject added in v0.12.0

func BuildTriggerObject(interactiveTrigger string) map[string]any

BuildTriggerObject creates a trigger composition object

func BuildURLSource added in v0.12.0

func BuildURLSource(actionID, url string) (map[string]any, error)

BuildURLSource creates a URL source element for external data Reference: https://api.slack.com/reference/block-kit/block-elements#url-source-element SECURITY: Validates URL scheme to prevent SSRF and XSS attacks

func BuildURLSourceUnsafe added in v0.12.0

func BuildURLSourceUnsafe(actionID, url string) map[string]any

BuildURLSourceUnsafe creates a URL source element without validation (use with caution) Only use this when you have already validated the URL through other means

func BuildUserMention added in v0.12.0

func BuildUserMention(userID string) map[string]any

BuildUserMention creates a user mention for rich_text_section

func BuildVideoBlock added in v0.12.0

func BuildVideoBlock(videoURL, thumbnailURL, title, description string, authorName, providerName string) []map[string]any

BuildVideoBlock creates a video block (for apps with video permissions) Reference: https://api.slack.com/reference/block-kit/blocks#video

func BuildWorkflowButton added in v0.12.0

func BuildWorkflowButton(text string, workflow struct{ ID string }, style string) map[string]any

BuildWorkflowButton creates a button that triggers a Slack workflow Reference: https://api.slack.com/reference/block-kit/block-elements#workflow-button-element

func BuildWorkflowObject added in v0.12.0

func BuildWorkflowObject(workflowID string, inputs map[string]any) map[string]any

BuildWorkflowObject creates a workflow composition object

func ChunkMessageMarkdown added in v0.12.0

func ChunkMessageMarkdown(text string, limit int) []string

chunkMessageMarkdown splits a markdown message into chunks, keeping code blocks together as much as possible.

func FormatChannelAllMention added in v0.12.0

func FormatChannelAllMention() string

FormatChannelMention creates a @channel mention

func FormatChannelMention added in v0.12.0

func FormatChannelMention(channelID, channelName string) string

FormatChannelMention creates a channel mention: <#C123|channel-name>

func FormatChannelMentionByID added in v0.12.0

func FormatChannelMentionByID(channelID string) string

FormatChannelMentionByID creates a channel mention with just ID: <#C123>

func FormatCommand added in v0.12.0

func FormatCommand(command string) string

FormatCommand creates a command formatting

func FormatDate added in v0.12.0

func FormatDate(timestamp int64) string

FormatDate creates a simple date formatting

func FormatDateLong added in v0.12.0

func FormatDateLong(timestamp int64) string

FormatDateLong creates a long date formatting (e.g., "Monday, January 1, 2024")

func FormatDateShort added in v0.12.0

func FormatDateShort(timestamp int64) string

FormatDateShort creates a short date formatting (e.g., "Jan 1, 2024")

func FormatDateTime added in v0.12.0

func FormatDateTime(timestamp int64, format, fallback string) string

FormatDateTime creates a date formatting: <!date^timestamp^format|fallback> Reference: https://api.slack.com/reference/surfaces/formatting#date-formatting

func FormatDateTimeCombined added in v0.12.0

func FormatDateTimeCombined(timestamp int64) string

FormatDateTimeCombined creates combined date and time formatting

func FormatDateTimeWithLink(timestamp int64, format, linkURL, fallback string) string

FormatDateTimeWithLink creates a date formatting with link: <!date^timestamp^format^link|fallback>

func FormatEmail added in v0.12.0

func FormatEmail(email string) string

FormatEmail creates an email link

func FormatEveryoneMention added in v0.12.0

func FormatEveryoneMention() string

FormatEveryoneMention creates a @everyone mention

func FormatHereMention added in v0.12.0

func FormatHereMention() string

FormatHereMention creates a @here mention

func FormatObject added in v0.12.0

func FormatObject(objectType, objectID, objectText string) string

FormatObject creates an object mention (for boards, clips, etc.)

func FormatSpecialMention added in v0.12.0

func FormatSpecialMention(mentionType string) string

FormatSpecialMention creates a special mention: <!here>, <!channel>, <!everyone>

func FormatSubteamMention added in v0.12.0

func FormatSubteamMention(subteamID, subteamHandle string) string

FormatSubteamMention creates a user group mention: <!subteam^S123|@group>

func FormatTime added in v0.12.0

func FormatTime(timestamp int64) string

FormatTime creates a time formatting (e.g., "2:30 PM")

func FormatURL added in v0.12.0

func FormatURL(url, text string) string

FormatURL creates a link: <url|text> or <url>

func FormatUserMention added in v0.12.0

func FormatUserMention(userID, userName string) string

FormatUserMention creates a user mention: <@U123|username>

func FormatUserMentionByID added in v0.12.0

func FormatUserMentionByID(userID string) string

FormatUserMentionByID creates a user mention with just ID: <@U123>

func IsAllowedScheme added in v0.12.0

func IsAllowedScheme(scheme string) bool

IsAllowedScheme checks if a URL scheme is in the allowed list

func NewContextWithTraceID added in v0.12.0

func NewContextWithTraceID(ctx context.Context) (context.Context, string)

NewContextWithTraceID creates a new context with a generated trace ID Returns the context and the trace ID

func RateLimitKey added in v0.12.0

func RateLimitKey(userID, ip string) string

RateLimitKey generates a rate limit key based on user ID and IP

func RuneCount added in v0.12.0

func RuneCount(s string) int

RuneCount counts Unicode runes (characters) instead of bytes

func SanitizeCommand added in v0.12.0

func SanitizeCommand(command string) string

SanitizeCommand sanitizes command string for safe display in code blocks

func SanitizeErrorMessage added in v0.12.0

func SanitizeErrorMessage(err error) string

SanitizeErrorMessage removes potentially sensitive information from error messages

func SanitizeForDisplay added in v0.12.0

func SanitizeForDisplay(content string, maxLength int) string

SanitizeForDisplay removes potentially dangerous content for display

func SanitizeForRegex added in v0.12.0

func SanitizeForRegex(input string) string

SanitizeForRegex escapes special regex characters in user input

func SanitizeMarkdown added in v0.12.0

func SanitizeMarkdown(content string) string

SanitizeMarkdown removes potentially dangerous markdown patterns

func TraceIDFromContext added in v0.12.0

func TraceIDFromContext(ctx context.Context) string

TraceIDFromContext extracts the trace ID from context

func TruncateByRune added in v0.12.0

func TruncateByRune(s string, maxRunes int) string

TruncateByRune truncates string by rune count, not byte count

func TruncateMrkdwn added in v0.12.0

func TruncateMrkdwn(text string, maxLen int) string

TruncateMrkdwn truncates mrkdwn text to max length while preserving formatting It avoids cutting in the middle of code blocks or special syntax

func TruncateText added in v0.12.0

func TruncateText(text string, maxLen int) string

TruncateText truncates text to max length with ellipsis

func ValidateAccessibilityLabel added in v0.12.0

func ValidateAccessibilityLabel(label string) error

ValidateAccessibilityLabel validates accessibility label for button (max 75 chars)

func ValidateActionID added in v0.12.0

func ValidateActionID(actionID string) error

ValidateActionID validates action_id format

func ValidateAndTruncateBlocks added in v0.12.0

func ValidateAndTruncateBlocks(blocks []map[string]any) ([]map[string]any, error)

ValidateAndTruncateBlocks validates blocks and truncates if necessary

func ValidateBlock added in v0.12.0

func ValidateBlock(block map[string]any, index int) error

ValidateBlock validates a single block

func ValidateBlockID added in v0.12.0

func ValidateBlockID(blockID string) string

ValidateBlockID validates block_id length

func ValidateBlockWithDetails added in v0.12.0

func ValidateBlockWithDetails(block map[string]any, index int) []error

ValidateBlockWithDetails returns detailed validation errors

func ValidateBlocks added in v0.12.0

func ValidateBlocks(blocks []map[string]any, isModal bool) error

ValidateBlocks validates an array of blocks

func ValidateButtonComplete added in v0.12.0

func ValidateButtonComplete(button map[string]any) error

ValidateButtonComplete performs complete validation for button element

func ValidateButtonURL added in v0.12.0

func ValidateButtonURL(buttonURL string) error

ValidateButtonURL validates URL for button elements

func ValidateButtonURLLength added in v0.12.0

func ValidateButtonURLLength(buttonURL string) error

ValidateButtonURLLength validates button URL length (max 3000 chars)

func ValidateButtonValue added in v0.12.0

func ValidateButtonValue(value string) (string, string, string, error)

ValidateButtonValue validates permission button value format Returns (behavior, sessionID, messageID, error)

func ValidateComplete added in v0.12.0

func ValidateComplete(block map[string]any) error

ValidateComplete validates all fields in a block for comprehensive validation

func ValidateConfirmationDialog added in v0.12.0

func ValidateConfirmationDialog(title, text, confirmText, denyText string) (string, string, string, string)

ValidateConfirmationDialog validates confirmation dialog fields

func ValidateConfirmationDialogText added in v0.12.0

func ValidateConfirmationDialogText(title, text, confirmText, denyText string) (string, string, string, string)

ValidateConfirmationDialogText validates confirmation dialog text fields

func ValidateEmailFormat added in v0.12.0

func ValidateEmailFormat(email string) bool

ValidateEmailFormat performs basic email validation

func ValidateEmoji added in v0.12.0

func ValidateEmoji(text string, allowEmoji bool) string

ValidateEmoji validates and optionally removes emoji from text

func ValidateFileComplete added in v0.12.0

func ValidateFileComplete(file map[string]any) error

ValidateFileComplete performs complete validation for file block

func ValidateFileInput added in v0.12.0

func ValidateFileInput(element map[string]any) error

ValidateFileInput validates file input element

func ValidateImageComplete added in v0.12.0

func ValidateImageComplete(image map[string]any) error

ValidateImageComplete performs complete validation for image block

func ValidateImageURL added in v0.12.0

func ValidateImageURL(imageURL string) error

ValidateImageURL validates URL for image blocks

func ValidateInitialValue added in v0.12.0

func ValidateInitialValue(initialValue string, maxLength int) string

ValidateInitialValue validates initial_value for input elements

func ValidateInitialValueForInput added in v0.12.0

func ValidateInitialValueForInput(initialValue string, maxLength int) string

ValidateInitialValueForInput validates initial_value for input elements

func ValidateMentionFormat added in v0.12.0

func ValidateMentionFormat(mention string) bool

ValidateMentionFormat validates Slack mention format

func ValidateMrkdwnText added in v0.12.0

func ValidateMrkdwnText(text string) string

ValidateMrkdwnText validates mrkdwn text content

func ValidateOptionValue added in v0.12.0

func ValidateOptionValue(value string) error

ValidateOptionValue validates option value in select menus

func ValidatePlainText added in v0.12.0

func ValidatePlainText(text string, withEmoji bool) string

ValidatePlainText validates plain_text object content

func ValidatePlanBlock added in v0.12.0

func ValidatePlanBlock(block map[string]any) error

ValidatePlanBlock validates plan block

func ValidateRegexPattern added in v0.12.0

func ValidateRegexPattern(pattern string) (string, error)

ValidateRegexPattern validates regex pattern to prevent ReDoS

func ValidateRichTextInput added in v0.12.0

func ValidateRichTextInput(element map[string]any) error

ValidateRichTextInput validates rich text input element

func ValidateTableBlock added in v0.12.0

func ValidateTableBlock(block map[string]any) error

ValidateTableBlock validates table block

func ValidateTaskCardBlock added in v0.12.0

func ValidateTaskCardBlock(block map[string]any) error

ValidateTaskCardBlock validates task card block

func ValidateTextObject added in v0.12.0

func ValidateTextObject(text map[string]any) error

ValidateTextObject validates a text object

func ValidateTokenFormat added in v0.12.0

func ValidateTokenFormat(token string) bool

ValidateTokenFormat validates Slack token format with safe regex

func ValidateToolName added in v0.12.0

func ValidateToolName(toolName string) string

ValidateToolName validates tool name for safe display

func ValidateURL added in v0.12.0

func ValidateURL(rawURL string) error

ValidateURL checks if a URL uses an allowed scheme

func ValidateURLFormat added in v0.12.0

func ValidateURLFormat(rawURL string) bool

ValidateURLFormat performs basic URL validation

func WithFocusOnLoad added in v0.12.0

func WithFocusOnLoad(element map[string]any) map[string]any

BuildFocusOnLoad sets focus on an input element when a modal loads

func WithTraceID added in v0.12.0

func WithTraceID(ctx context.Context, traceID string) context.Context

WithTraceID returns a new context with the given trace ID

Types

type Adapter

type Adapter struct {
	*base.Adapter
	// contains filtered or unexported fields
}

func NewAdapter

func NewAdapter(config *Config, logger *slog.Logger, opts ...base.AdapterOption) *Adapter

func (*Adapter) AddReaction added in v0.11.1

func (a *Adapter) AddReaction(ctx context.Context, reaction base.Reaction) error

AddReaction adds a reaction to a message

func (*Adapter) SendAttachment

func (a *Adapter) SendAttachment(ctx context.Context, channelID, threadTS string, attachment base.Attachment) error

SendAttachment sends an attachment to a Slack channel

func (*Adapter) SendMessage

func (a *Adapter) SendMessage(ctx context.Context, sessionID string, msg *base.ChatMessage) error

func (*Adapter) SendMessageWithOptions

func (a *Adapter) SendMessageWithOptions(ctx context.Context, sessionID string, msg *MessageContent, opts SendMessageOptions) error

SendMessageWithOptions sends a message with full options support This includes: message chunking, thread support, rate limiting

func (*Adapter) SendToChannel

func (a *Adapter) SendToChannel(ctx context.Context, channelID, text, threadTS string) error

func (*Adapter) SetEngine added in v0.12.0

func (a *Adapter) SetEngine(eng *engine.Engine)

SetEngine sets the engine for the adapter (used for slash commands)

func (*Adapter) SetSender

func (a *Adapter) SetSender(fn func(ctx context.Context, sessionID string, msg *base.ChatMessage) error)

func (*Adapter) SetSlashCommandHandler added in v0.11.1

func (a *Adapter) SetSlashCommandHandler(fn func(cmd SlashCommand))

SetSlashCommandHandler sets the handler for slash commands

func (*Adapter) Start

func (a *Adapter) Start(ctx context.Context) error

Start starts the adapter (overrides base.Adapter.Start to support Socket Mode)

func (*Adapter) Stop

func (a *Adapter) Stop() error

Stop waits for pending webhook goroutines to complete

func (*Adapter) UpdateMessage added in v0.12.0

func (a *Adapter) UpdateMessage(ctx context.Context, channelID, messageTS string, blocks []any, fallbackText string) error

UpdateMessage updates an existing Slack message using chat.update API Used for streaming AI responses with "typing indicator" UX

type BlockBuilder added in v0.12.0

type BlockBuilder struct{}

BlockBuilder builds Slack Block Kit messages for various event types

func NewBlockBuilder added in v0.12.0

func NewBlockBuilder() *BlockBuilder

NewBlockBuilder creates a new BlockBuilder instance

func (*BlockBuilder) BuildAnswerBlock added in v0.12.0

func (b *BlockBuilder) BuildAnswerBlock(content string) []map[string]any

BuildAnswerBlock builds a section block for AI answer text Used for: provider.EventTypeAnswer Strategy: Stream updates via chat.update, supports mrkdwn formatting

func (*BlockBuilder) BuildChunkedAnswerBlocks added in v0.12.0

func (b *BlockBuilder) BuildChunkedAnswerBlocks(content string) [][]map[string]any

BuildChunkedAnswerBlocks builds answer blocks with automatic chunking If content exceeds SlackTextLimit, it will be split into multiple blocks

func (*BlockBuilder) BuildChunkedSectionBlocks added in v0.12.0

func (b *BlockBuilder) BuildChunkedSectionBlocks(text string) [][]map[string]any

BuildChunkedSectionBlocks builds section blocks with automatic chunking

func (*BlockBuilder) BuildDividerBlock added in v0.12.0

func (b *BlockBuilder) BuildDividerBlock() []map[string]any

BuildDividerBlock creates a simple divider

func (*BlockBuilder) BuildErrorBlock added in v0.12.0

func (b *BlockBuilder) BuildErrorBlock(message string, isDangerBlock bool) []map[string]any

BuildErrorBlock builds blocks for error messages Used for: provider.EventTypeError, danger_block Strategy: Send immediately (not aggregated) for critical feedback

func (*BlockBuilder) BuildSessionStatsBlock added in v0.12.0

func (b *BlockBuilder) BuildSessionStatsBlock(stats *event.SessionStatsData, style SessionStatsStyle) []map[string]any

BuildSessionStatsBlock builds a rich statistics summary block Used for: session_stats events at end of each turn Strategy: Send as final summary with visual polish

func (*BlockBuilder) BuildStatsBlock added in v0.12.0

func (b *BlockBuilder) BuildStatsBlock(stats *event.EventMeta) []map[string]any

BuildStatsBlock builds a section block with statistics Used for: provider.EventTypeResult (end of turn) Strategy: Send as final summary

func (*BlockBuilder) BuildThinkingBlock added in v0.12.0

func (b *BlockBuilder) BuildThinkingBlock(content string) []map[string]any

BuildThinkingBlock builds a context block for thinking status Used for: provider.EventTypeThinking Strategy: Send immediately (not aggregated) for instant feedback

func (*BlockBuilder) BuildToolResultBlock added in v0.12.0

func (b *BlockBuilder) BuildToolResultBlock(success bool, durationMs int64, output string, hasButton bool) []map[string]any

BuildToolResultBlock builds a section block for tool execution result Used for: provider.EventTypeToolResult Strategy: Can be aggregated, includes optional button to expand output

func (*BlockBuilder) BuildToolUseBlock added in v0.12.0

func (b *BlockBuilder) BuildToolUseBlock(toolName, input string, truncated bool) []map[string]any

BuildToolUseBlock builds a section block for tool invocation Used for: provider.EventTypeToolUse Strategy: Can be aggregated with similar tool events

type CallbackChannel added in v0.12.0

type CallbackChannel struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

CallbackChannel represents the channel in a Slack callback.

type CallbackMessage added in v0.12.0

type CallbackMessage struct {
	Ts   string `json:"ts"`
	Type string `json:"type"`
	Text string `json:"text"`
}

CallbackMessage represents the message in a Slack callback.

type CallbackTeam added in v0.12.0

type CallbackTeam struct {
	ID     string `json:"id"`
	Domain string `json:"domain"`
}

CallbackTeam represents the team in a Slack callback.

type CallbackUser added in v0.12.0

type CallbackUser struct {
	ID       string `json:"id"`
	Username string `json:"username"`
}

CallbackUser represents the user in a Slack callback.

type Config

type Config struct {
	BotToken      string
	AppToken      string
	SigningSecret string
	SystemPrompt  string
	// Mode: "http" (default) or "socket" for WebSocket connection
	Mode string
	// ServerAddr: HTTP server address (e.g., ":8080")
	ServerAddr string

	// Permission Policy for Direct Messages
	// "allow" - Allow all DMs (default)
	// "pairing" - Only allow when user is paired
	// "block" - Block all DMs
	DMPolicy string

	// Permission Policy for Group Messages
	// "allow" - Allow all group messages (default)
	// "mention" - Only allow when bot is mentioned
	// "block" - Block all group messages
	GroupPolicy string

	// AllowedUsers: List of user IDs who can interact with the bot (whitelist)
	AllowedUsers []string
	// BlockedUsers: List of user IDs who cannot interact with the bot (blacklist)
	BlockedUsers []string
	// BotUserID: Bot's user ID (e.g., "U1234567890") - used for mention detection
	BotUserID string

	// SlashCommandRateLimit: Maximum requests per second per user for slash commands
	// Default: 10.0 requests/second
	SlashCommandRateLimit float64
	// contains filtered or unexported fields
}

func (*Config) ContainsBotMention added in v0.12.0

func (c *Config) ContainsBotMention(text string) bool

ContainsBotMention checks if message text contains a bot mention Slack mention format: <@U1234567890> or <!here> or <!channel> Uses regex for exact matching to prevent false positives

func (*Config) IsSocketMode

func (c *Config) IsSocketMode() bool

IsSocketMode returns true if Socket Mode is enabled

func (*Config) IsUserAllowed added in v0.12.0

func (c *Config) IsUserAllowed(userID string) bool

IsUserAllowed checks if a user is allowed to interact with the bot

func (*Config) MarkPaired added in v0.12.0

func (c *Config) MarkPaired(userID string)

MarkPaired marks a user as having an active DM with the bot

func (*Config) ShouldProcessChannel added in v0.12.0

func (c *Config) ShouldProcessChannel(channelType, channelID string) bool

ShouldProcessChannel checks if messages from a channel should be processed channelType: "dm" or "channel" or "group"

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the configuration based on the selected mode

type ErrorClass added in v0.12.0

type ErrorClass int

ErrorClass classifies Slack API errors for handling decisions

const (
	// Retryable - errors that should be retried with backoff
	Retryable ErrorClass = iota
	// Fatal - errors that should not be retried (auth, invalid, etc.)
	Fatal
	// UserError - errors that indicate user action needed (channel not found, etc.)
	UserError
	// Unknown - errors that are not recognized, default to retry
	Unknown
)

func GetErrorClass added in v0.12.0

func GetErrorClass(err error) ErrorClass

GetErrorClass returns the ErrorClass for a given error

type Event

type Event struct {
	Token     string          `json:"token"`
	TeamID    string          `json:"team_id"`
	APIAppID  string          `json:"api_app_id"`
	Type      string          `json:"type"`
	EventID   string          `json:"event_id"`
	EventTime int64           `json:"event_time"`
	Event     json.RawMessage `json:"event"`
	Challenge string          `json:"challenge"`
}

type EventHandler

type EventHandler func(eventType string, data json.RawMessage)

EventHandler handles incoming Slack events

type MessageContent

type MessageContent struct {
	Content string
}

MessageContent represents the content of a message to send

type MessageEvent

type MessageEvent struct {
	Type        string `json:"type"`
	Channel     string `json:"channel"`
	ChannelType string `json:"channel_type"`
	User        string `json:"user"`
	Text        string `json:"text"`
	TS          string `json:"ts"`
	EventTS     string `json:"event_ts"`
	BotID       string `json:"bot_id,omitempty"`
	SubType     string `json:"subtype,omitempty"`
	ThreadTS    string `json:"thread_ts,omitempty"`      // Thread identifier
	ParentUser  string `json:"parent_user_id,omitempty"` // Parent message user
	BotUserID   string `json:"bot_user_id,omitempty"`    // Bot user ID for mentions
}

type MrkdwnFormatter added in v0.12.0

type MrkdwnFormatter struct{}

MrkdwnFormatter provides utilities for converting Markdown to Slack mrkdwn format

func NewMrkdwnFormatter added in v0.12.0

func NewMrkdwnFormatter() *MrkdwnFormatter

NewMrkdwnFormatter creates a new MrkdwnFormatter

func (*MrkdwnFormatter) Format added in v0.12.0

func (f *MrkdwnFormatter) Format(text string) string

Format converts Markdown text to Slack mrkdwn format Handles: bold, italic, strikethrough, code blocks, links Order: links -> bold -> italic -> strikethrough -> escape (to preserve URLs and code)

func (*MrkdwnFormatter) FormatCodeBlock added in v0.12.0

func (f *MrkdwnFormatter) FormatCodeBlock(code, language string) string

FormatCodeBlock formats code with optional language hint

type RateLimitError added in v0.12.0

type RateLimitError struct {
	RetryAfter time.Duration // Duration to wait before retrying
}

RateLimitError represents a rate limit error with retry-after information

func (*RateLimitError) Error added in v0.12.0

func (e *RateLimitError) Error() string

type RetryConfig

type RetryConfig struct {
	MaxAttempts int
	BaseDelay   time.Duration
	MaxDelay    time.Duration
}

RetryConfig configures the retry behavior

type SelectionOption added in v0.12.0

type SelectionOption struct {
	Label string
	Value string
	Emoji string
}

SelectionOption represents an option for selection buttons.

type SendMessageOptions

type SendMessageOptions struct {
	ChannelID string
	ThreadTS  string
	Markdown  bool // Whether to convert markdown to mrkdwn
}

SendMessageOptions contains options for sending messages

type SessionStatsStyle added in v0.12.0

type SessionStatsStyle string

SessionStatsStyle defines the visual style for session statistics

const (
	// StatsStyleCompact - Minimal single-line summary
	StatsStyleCompact SessionStatsStyle = "compact"
	// StatsStyleCard - Rich card with emoji indicators (recommended)
	StatsStyleCard SessionStatsStyle = "card"
	// StatsStyleDetailed - Full breakdown with all metrics
	StatsStyleDetailed SessionStatsStyle = "detailed"
)

type SlackAction added in v0.12.0

type SlackAction struct {
	ActionID string `json:"action_id"`
	BlockID  string `json:"block_id"`
	ID       string `json:"id"`
	Name     string `json:"name"`
	Type     string `json:"type"`
	Value    string `json:"value"`
	Style    string `json:"style"`
}

SlackAction represents an action within a Slack interaction callback.

type SlackInteractionCallback added in v0.12.0

type SlackInteractionCallback struct {
	Type        string          `json:"type"`
	User        CallbackUser    `json:"user"`
	Channel     CallbackChannel `json:"channel"`
	Message     CallbackMessage `json:"message"`
	ResponseURL string          `json:"response_url"`
	TriggerID   string          `json:"trigger_id"`
	Actions     []SlackAction   `json:"actions"`
	Team        CallbackTeam    `json:"team"`
}

SlackInteractionCallback represents a Slack interaction callback payload.

type SlashCommand added in v0.11.1

type SlashCommand struct {
	Command     string
	Text        string
	UserID      string
	ChannelID   string
	ResponseURL string
}

SlashCommand represents a Slack slash command

type SlashCommandRateLimiter added in v0.12.0

type SlashCommandRateLimiter struct {
	// contains filtered or unexported fields
}

SlashCommandRateLimiter provides per-user rate limiting using token bucket algorithm

func NewSlashCommandRateLimiter added in v0.12.0

func NewSlashCommandRateLimiter() *SlashCommandRateLimiter

NewSlashCommandRateLimiter creates a new rate limiter with default settings

func NewSlashCommandRateLimiterWithConfig added in v0.12.0

func NewSlashCommandRateLimiterWithConfig(rps float64, burst int) *SlashCommandRateLimiter

NewSlashCommandRateLimiterWithConfig creates a new rate limiter with custom settings If rps is 0 or negative, defaultRateLimit will be used

func (*SlashCommandRateLimiter) Allow added in v0.12.0

func (r *SlashCommandRateLimiter) Allow(userID string) bool

Allow checks if a request from the given user is allowed Returns true if the request is within rate limit, false if rate limited

func (*SlashCommandRateLimiter) Stop added in v0.12.0

func (r *SlashCommandRateLimiter) Stop()

Stop gracefully stops the rate limiter cleanup goroutine

type SocketModeConfig

type SocketModeConfig struct {
	AppToken string // xapp-* token
	BotToken string // xoxb-* token
}

SocketModeConfig holds configuration for Socket Mode connection

type SocketModeConnection

type SocketModeConnection struct {
	// contains filtered or unexported fields
}

SocketModeConnection manages a WebSocket connection to Slack's Socket Mode

func NewSocketModeConnection

func NewSocketModeConnection(config SocketModeConfig, logger *slog.Logger) *SocketModeConnection

NewSocketModeConnection creates a new Socket Mode connection

func (*SocketModeConnection) IsConnected

func (s *SocketModeConnection) IsConnected() bool

IsConnected returns true if the connection is active

func (*SocketModeConnection) RegisterHandler

func (s *SocketModeConnection) RegisterHandler(eventType string, handler EventHandler)

RegisterHandler registers an event handler for a specific event type

func (*SocketModeConnection) Send

func (s *SocketModeConnection) Send(data map[string]any) error

Send sends a message over the WebSocket connection

func (*SocketModeConnection) SetReconnectCallbacks added in v0.11.2

func (s *SocketModeConnection) SetReconnectCallbacks(onReconnect func(), onReconnectFail func(error))

SetReconnectCallbacks sets callbacks for reconnection events

func (*SocketModeConnection) Start

func (s *SocketModeConnection) Start(ctx context.Context) error

Start begins the Socket Mode connection

func (*SocketModeConnection) Stop

func (s *SocketModeConnection) Stop() error

Stop closes the Socket Mode connection

type ValidationError added in v0.12.0

type ValidationError struct {
	BlockType string
	Field     string
	Message   string
}

ValidationError represents a block validation error

func (*ValidationError) Error added in v0.12.0

func (e *ValidationError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL