internal

package
v0.21.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// SlackErrChannelNotFound is returned when the target channel does not exist or
	// the bot lacks visibility of it. Non-retryable.
	SlackErrChannelNotFound = "channel_not_found"

	// SlackErrThreadNotFound is returned when the target thread does not exist,
	// typically because the parent message was deleted. Non-retryable.
	SlackErrThreadNotFound = "thread_not_found"

	// SlackErrNoSuchSubTeam is returned when a referenced user group does not exist
	// in the workspace. Non-retryable.
	SlackErrNoSuchSubTeam = "no_such_subteam"

	// SlackErrCantUpdateMessage is returned when the bot attempts to edit a message
	// it is not permitted to modify (e.g. another user's message). Non-retryable.
	SlackErrCantUpdateMessage = "cant_update_message"

	// SlackErrCantDeleteMessage is returned when the bot attempts to delete a message
	// it is not permitted to remove (e.g. another user's message). Non-retryable.
	SlackErrCantDeleteMessage = "cant_delete_message"

	// SlackErrMessageNotFound is returned when the target message does not exist,
	// typically because it was already deleted. Non-retryable.
	SlackErrMessageNotFound = "message_not_found"

	// SlackErrNotInChannel is returned when the bot is not a member of the channel
	// it is trying to interact with. Non-retryable.
	SlackErrNotInChannel = "not_in_channel"

	// SlackErrInvalidBlocks is returned when a message payload contains malformed
	// Block Kit JSON. Non-retryable.
	SlackErrInvalidBlocks = "invalid_blocks"

	// SlackErrIsArchived is returned when the target channel has been archived and
	// no longer accepts messages. Non-retryable.
	SlackErrIsArchived = "is_archived"

	// SlackErrIsInactive is returned when a message cannot be edited or deleted
	// because the channel is frozen, inactive or archived. Non-retryable.
	SlackErrIsInactive = "is_inactive"

	// SlackErrInvalidChannelID is returned when the channel value is not a valid
	// channel ID. Non-retryable.
	SlackErrInvalidChannelID = "invalid_channel_id"

	// SlackErrRestrictedAction is returned when a workspace preference prevents the
	// bot from posting. Non-retryable.
	SlackErrRestrictedAction = "restricted_action"

	// SlackErrRestrictedActionReadOnlyChannel is returned when posting to a read-only
	// channel. Non-retryable.
	SlackErrRestrictedActionReadOnlyChannel = "restricted_action_read_only_channel"

	// SlackErrRestrictedActionThreadOnlyChannel is returned when posting a top-level
	// message to a thread-only channel. Non-retryable.
	SlackErrRestrictedActionThreadOnlyChannel = "restricted_action_thread_only_channel"

	// SlackErrEKMAccessDenied is returned when admins have suspended posting to the
	// channel. Non-retryable.
	SlackErrEKMAccessDenied = "ekm_access_denied"

	// SlackErrEditWindowClosed is returned when workspace settings no longer allow
	// the message to be edited. Non-retryable.
	SlackErrEditWindowClosed = "edit_window_closed"

	// SlackErrInvalidBlocksFormat is returned when the blocks payload is not valid
	// JSON or Block Kit syntax. Non-retryable.
	SlackErrInvalidBlocksFormat = "invalid_blocks_format"

	// SlackErrMsgBlocksTooLong is returned when the blocks payload is too long. Non-retryable.
	SlackErrMsgBlocksTooLong = "msg_blocks_too_long"

	// SlackErrMsgTooLong is returned when the message text is too long. Non-retryable.
	SlackErrMsgTooLong = "msg_too_long"

	// SlackErrTooManyAttachments is returned when a message has more than 100
	// attachments. Non-retryable.
	SlackErrTooManyAttachments = "too_many_attachments"

	// SlackErrAttachmentPayloadLimitExceeded is returned when the attachment payload
	// is too large. Non-retryable.
	SlackErrAttachmentPayloadLimitExceeded = "attachment_payload_limit_exceeded"

	// SlackErrBlockMismatch is returned when rich-text blocks are replaced with
	// non-rich-text blocks in an update. Non-retryable.
	SlackErrBlockMismatch = "block_mismatch"

	// SlackErrNoText is returned when a message has no text. Non-retryable.
	SlackErrNoText = "no_text"

	// SlackErrUpdateFailed is an internal Slack failure when updating a message.
	// Safe to retry.
	SlackErrUpdateFailed = "update_failed"

	// SlackErrNotAuthed is returned when no authentication token was provided. Non-retryable.
	SlackErrNotAuthed = "not_authed"

	// SlackErrInvalidAuth is returned when the token is invalid or the request comes
	// from a disallowed IP. Non-retryable.
	SlackErrInvalidAuth = "invalid_auth"

	// SlackErrAccountInactive is returned when the token belongs to a deleted user or
	// workspace. Non-retryable.
	SlackErrAccountInactive = "account_inactive"

	// SlackErrTokenRevoked is returned when the token has been revoked, or the app has
	// been removed. Non-retryable.
	SlackErrTokenRevoked = "token_revoked"

	// SlackErrTokenExpired is returned when the token has expired. Non-retryable.
	SlackErrTokenExpired = "token_expired"

	// SlackErrMissingScope is returned when the token lacks a scope required by the
	// method. Non-retryable.
	SlackErrMissingScope = "missing_scope"

	// SlackErrInternalError is a transient server-side error returned by Slack when
	// something went wrong on their end. Safe to retry.
	SlackErrInternalError = "internal_error"

	// SlackErrFatalError is a transient error string returned by Slack for unspecified
	// server-side failures. Despite the name, Slack treats this as retryable.
	SlackErrFatalError = "fatal_error"

	// SlackErrServiceUnavailable is a transient error returned when the Slack API
	// is temporarily unavailable. Safe to retry.
	SlackErrServiceUnavailable = "service_unavailable"

	// SlackErrRequestTimeout is a transient error returned when Slack's own
	// processing timed out handling the request. Safe to retry.
	SlackErrRequestTimeout = "request_timeout"

	// SlackErrRateLimited is returned when the client has hit a rate limit.
	// Safe to retry after a delay, using the Retry-After header if present.
	SlackErrRateLimited = "ratelimited"

	// SlackErrRateLimitedV2 is returned when the client has hit a rate limit.
	// Safe to retry after a delay, using the Retry-After header if present.
	SlackErrRateLimitedV2 = "rate_limited"
)

Variables

View Source
var ErrNotConnected = errors.New("client not connected: Connect() must be called first")

ErrNotConnected is returned when an API method is called before Connect().

View Source
var ErrPostOutcomeUnknown = errors.New("outcome of Slack post is unknown")

ErrPostOutcomeUnknown is returned (wrapping the underlying error) by SlackAPIClient.ChatPostMessage when the call failed in a way where the message may still have been posted, e.g. a timeout or a Slack fatal_error. Such errors are not retried, since a retry could create a duplicate message.

View Source
var ErrTooManyMessages = errors.New("too many messages in channel")

ErrTooManyMessages is returned (wrapped) by SlackAPIClient.ListBotMessages when the channel has too many messages since oldest to read within [maxBotMessagesPages] pages. Unlike other errors, it depends on how far back the messages are read, so a read from a later oldest time may still succeed.

Functions

func DecryptWebhookPayload

func DecryptWebhookPayload(w *types.Webhook, key []byte) (map[string]any, error)

DecryptWebhookPayload decrypts the encrypted webhook payload (if any) and returns it, or nil if payload is empty. This function does not modify the state of the webhook.

func EncryptWebhookPayload

func EncryptWebhookPayload(w *types.Webhook, key []byte) error

EncryptWebhookPayload encrypts the existing webhook payload (if any) and replaces it with an encrypted version. This function modifies the state of the webhook.

func FormatSlackTimestamp added in v0.17.0

func FormatSlackTimestamp(t time.Time) string

FormatSlackTimestamp formats t as a Slack message timestamp, e.g. "1700000000.123456". Slack timestamps have a fixed number of decimals (and of seconds digits until the year 2286), so timestamps in this format compare correctly as strings.

func Hash

func Hash(input ...string) string

func HashBytes

func HashBytes(b []byte) []byte

func IsCtxCanceledErr

func IsCtxCanceledErr(err error) bool

func IsTransientError added in v0.17.0

func IsTransientError(err error) bool

IsTransientError reports whether err should be considered transient and safe to retry. This includes both errors that Slack explicitly classifies as retryable, as well as certain client-side errors like timeouts that may indicate a temporary issue. Wrapped errors are unwrapped, so errors returned after exhausted retries are still reported as transient.

func MaxCallDuration added in v0.17.0

func MaxCallDuration(cfg *config.SlackClientConfig) time.Duration

MaxCallDuration returns an upper bound for how long a Slack API call made by SlackAPIClient can take, including retries: the larger of the rate limit and transient error retry budgets, plus the HTTP timeout of the last attempt. Time spent waiting for a free concurrency slot (see config.SlackClientConfig.Concurrency) is not included.

func NewPrefixedMetrics added in v0.6.0

func NewPrefixedMetrics(inner types.Metrics, prefix string) types.Metrics

NewPrefixedMetrics returns a types.Metrics that prepends prefix to every metric name. If prefix is empty the inner instance is returned unchanged.

func NewUniqueFieldsLogger added in v0.19.0

func NewUniqueFieldsLogger(logger types.Logger) types.Logger

NewUniqueFieldsLogger wraps logger in a UniqueFieldsLogger. It returns nil if logger is nil, and logger itself if it is already a UniqueFieldsLogger.

func ParseSlackTimestamp added in v0.17.0

func ParseSlackTimestamp(ts string) (time.Time, error)

ParseSlackTimestamp parses a Slack message timestamp, e.g. "1700000000.123456". See FormatSlackTimestamp. Decimals beyond microseconds are ignored, and a missing fraction is treated as zero.

func SlackErrorCode added in v0.17.0

func SlackErrorCode(err error) string

SlackErrorCode returns the Slack API error code of err, e.g. "channel_not_found". The error may wrap a slack.SlackErrorResponse, or be a bare known Slack error code. An empty string is returned for other errors.

func TrySend

func TrySend[T any](ctx context.Context, msg T, sinkCh chan<- T) error

func WithRateLimitGate added in v0.4.0

func WithRateLimitGate(g rateLimitSignaler) func(*SlackAPIClient)

WithRateLimitGate is a functional option that wires a RateLimitSignaler into the SlackAPIClient so that a detected 429 is broadcast to all callers.

Types

type Cache

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

Cache is a wrapper around a cache store that provides methods for getting, setting, and deleting cached items.

func NewCache

func NewCache(cacheStore store.StoreInterface, keyPrefix string, logger types.Logger) *Cache

NewCache creates a new Cache instance with the provided cache store, key prefix, and logger. The key prefix is optional, but may be useful for namespacing cache keys.

func (*Cache) Delete

func (c *Cache) Delete(ctx context.Context, key string) error

Delete removes the item from the cache with the given key. This method returns an error if the deletion fails, since an explicit delete is expected to always succeed. Note: The key is prefixed with the cache's keyPrefix.

func (*Cache) Get

func (c *Cache) Get(ctx context.Context, key string) (string, bool)

Get retrieves an item from the cache with the given key. If the item is not found, it returns an empty string and false. If an error occurs during retrieval, it logs the error and returns an empty string and false (or panics if WithPanicOnError is set). Note: The key is prefixed with the cache's keyPrefix.

func (*Cache) Set

func (c *Cache) Set(ctx context.Context, key string, value string, expiration time.Duration)

Set stores an item in the cache with the given key and expiration duration. If an error occurs during storage, it logs the error (or panics if WithPanicOnError is set). Note: The key is prefixed with the cache's keyPrefix.

func (*Cache) SetWithRandomExpiration

func (c *Cache) SetWithRandomExpiration(ctx context.Context, key string, value string, minExpiration time.Duration, variation time.Duration)

SetWithRandomExpiration stores an item in the cache with a key, value, and a random expiration time. The expiration time is calculated by adding a random variation to a minimum expiration duration. The random variation is between 0 and the absolute value of the provided variation duration. If an error occurs during storage, it logs the error (or panics if WithPanicOnError is set). Note: The key is prefixed with the cache's keyPrefix.

func (*Cache) WithPanicOnError

func (c *Cache) WithPanicOnError() *Cache

WithPanicOnError enables panicking on cache errors instead of logging them, in all Get and Set methods. This is useful for testing and debugging purposes, but should be used with caution in production environments. The default behavior is to log errors, not to panic.

type ChannelSummary

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

func NewChannelSummary

func NewChannelSummary(channel slack.Channel) *ChannelSummary

NewChannelSummary creates a new ChannelSummary from a slack.Channel object. We map only the fields we need, and ignore the rest.

type SlackAPIClient

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

func NewSlackAPIClient

func NewSlackAPIClient(cacheStore cachestore.StoreInterface, cacheKeyPrefix string, logger types.Logger, metrics types.Metrics, cfg *config.SlackClientConfig, opts ...func(*SlackAPIClient)) *SlackAPIClient

func (*SlackAPIClient) API

func (c *SlackAPIClient) API() *slack.Client

func (*SlackAPIClient) BotIsInChannel

func (c *SlackAPIClient) BotIsInChannel(ctx context.Context, channelID string) (bool, error)

func (*SlackAPIClient) BotUserID

func (c *SlackAPIClient) BotUserID() string

func (*SlackAPIClient) ChatDeleteMessage

func (c *SlackAPIClient) ChatDeleteMessage(ctx context.Context, channelID string, ts string) error

func (*SlackAPIClient) ChatPostMessage

func (c *SlackAPIClient) ChatPostMessage(ctx context.Context, channelID string, options ...slack.MsgOption) (string, error)

func (*SlackAPIClient) ChatUpdateMessage

func (c *SlackAPIClient) ChatUpdateMessage(ctx context.Context, channelID string, options ...slack.MsgOption) (string, error)

func (*SlackAPIClient) Connect

func (*SlackAPIClient) GetChannelInfo

func (c *SlackAPIClient) GetChannelInfo(ctx context.Context, channelID string) (*slack.Channel, error)

func (*SlackAPIClient) GetUserIDsInChannel

func (c *SlackAPIClient) GetUserIDsInChannel(ctx context.Context, channelID string) (map[string]struct{}, error)

func (*SlackAPIClient) GetUserInfo

func (c *SlackAPIClient) GetUserInfo(ctx context.Context, userID string) (*slack.User, error)

func (*SlackAPIClient) ListBotChannels

func (c *SlackAPIClient) ListBotChannels(ctx context.Context) ([]*ChannelSummary, error)

func (*SlackAPIClient) ListBotMessages added in v0.17.0

func (c *SlackAPIClient) ListBotMessages(ctx context.Context, channelID string, oldest time.Time, eventType string) ([]slack.Message, error)

ListBotMessages returns the top-level messages in a channel that were posted by this bot after oldest, and have message metadata with the given event type. Metadata is included in the returned messages. Messages are matched on the bot ID, since messages posted with as_user=false (e.g. with a custom username) are returned as bot_message without a user ID. An error wrapping ErrTooManyMessages is returned if the channel has too many messages since oldest to read within a bounded number of pages.

func (*SlackAPIClient) ListUserGroupMembers

func (c *SlackAPIClient) ListUserGroupMembers(ctx context.Context, groupID string) (map[string]struct{}, error)

func (*SlackAPIClient) MessageHasReplies

func (c *SlackAPIClient) MessageHasReplies(ctx context.Context, channelID, ts string) (bool, error)

func (*SlackAPIClient) NewSocketModeClient

func (c *SlackAPIClient) NewSocketModeClient() *SocketModeClientWrapper

func (*SlackAPIClient) OpenModal

func (c *SlackAPIClient) OpenModal(ctx context.Context, triggerID string, request slack.ModalViewRequest) error

func (*SlackAPIClient) PostEphemeral

func (c *SlackAPIClient) PostEphemeral(ctx context.Context, channelID, userID string, options ...slack.MsgOption) (string, error)

func (*SlackAPIClient) SendResponse

func (c *SlackAPIClient) SendResponse(ctx context.Context, channelID, responseURL, responseType, text string) error

func (*SlackAPIClient) UpdateModal added in v0.18.0

func (c *SlackAPIClient) UpdateModal(ctx context.Context, viewID string, request slack.ModalViewRequest) error

UpdateModal replaces the content of an open modal view, identified by its view ID. It fails (with a non-retryable error) if the user has closed the modal.

type SlackErrorClass added in v0.17.0

type SlackErrorClass int

SlackErrorClass groups Slack API error codes by how callers should react to them.

const (
	// SlackErrorClassOther covers unknown errors and errors without special handling.
	SlackErrorClassOther SlackErrorClass = iota

	// SlackErrorClassTransient covers server-side errors that are safe to retry.
	SlackErrorClassTransient

	// SlackErrorClassRateLimited covers rate limit errors. Safe to retry after a delay.
	SlackErrorClassRateLimited

	// SlackErrorClassAuth covers authentication and authorization errors that affect
	// every API call made with the token, not just the current request. The exception is
	// [SlackErrMissingScope], which only affects the methods that require the missing scope.
	SlackErrorClassAuth

	// SlackErrorClassChannelUnavailable covers errors where the channel does not exist
	// or no longer accepts posts from the bot (archived, inactive, read-only, restricted).
	SlackErrorClassChannelUnavailable

	// SlackErrorClassNotInChannel covers errors where the bot is not a member of the channel.
	SlackErrorClassNotInChannel

	// SlackErrorClassMessageUnavailable covers errors where an existing message is gone
	// or can no longer be edited or deleted by the bot.
	SlackErrorClassMessageUnavailable

	// SlackErrorClassInvalidContent covers errors where the message payload itself is
	// rejected (malformed or too large blocks, text or attachments).
	SlackErrorClassInvalidContent
)

func ClassifySlackError added in v0.17.0

func ClassifySlackError(err error) SlackErrorClass

ClassifySlackError returns the SlackErrorClass of a Slack API error. The error may be a bare Slack error code, or wrap a slack.SlackErrorResponse or slack.RateLimitedError (e.g. after exhausted retries). A nil error, or an error that is not a known Slack error, returns SlackErrorClassOther.

type SocketModeClientWrapper

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

SocketModeClientWrapper is a wrapper around the slack-go/socketmode.Client.

func NewSocketModeClientWrapper

func NewSocketModeClientWrapper(client *socketmode.Client, logger types.Logger) *SocketModeClientWrapper

NewSocketModeClientWrapper creates a new instance of SocketModeClientWrapper.

func (*SocketModeClientWrapper) Ack

Ack acknowledges the given socketmode request.

func (*SocketModeClientWrapper) AckWithFieldErrorMsg added in v0.10.0

func (s *SocketModeClientWrapper) AckWithFieldErrorMsg(ctx context.Context, evt *socketmode.Event, fieldName, errMsg string)

AckWithFieldErrorMsg acknowledges the given socketmode request with a field error message.

func (*SocketModeClientWrapper) AckWithPayload added in v0.10.0

func (s *SocketModeClientWrapper) AckWithPayload(ctx context.Context, req *socketmode.Request, payload any)

AckWithPayload acknowledges the given socketmode request with a payload.

func (*SocketModeClientWrapper) Events

func (s *SocketModeClientWrapper) Events() chan socketmode.Event

Events returns the channel that receives incoming socketmode events.

func (*SocketModeClientWrapper) RunContext

func (s *SocketModeClientWrapper) RunContext(ctx context.Context) error

RunContext is a blocking function that connects the Slack Socket Mode API and handles all incoming requests and outgoing responses.

type UniqueFieldsLogger added in v0.19.0

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

UniqueFieldsLogger is a types.Logger wrapper that guarantees unique field keys in each log line.

Logger implementations such as zerolog append fields, so adding the same key twice (e.g. a channel logger that already has channel_id, extended with the fields of an issue) results in duplicate JSON keys. UniqueFieldsLogger collects the fields itself, where a later value replaces an earlier one with the same key, and passes them to the wrapped logger once, when the first log line is written.

func (*UniqueFieldsLogger) Debug added in v0.19.0

func (l *UniqueFieldsLogger) Debug(msg string)

Debug logs a message at debug level.

func (*UniqueFieldsLogger) Debugf added in v0.19.0

func (l *UniqueFieldsLogger) Debugf(format string, args ...any)

Debugf logs a formatted message at debug level.

func (*UniqueFieldsLogger) Error added in v0.19.0

func (l *UniqueFieldsLogger) Error(msg string)

Error logs a message at error level.

func (*UniqueFieldsLogger) Errorf added in v0.19.0

func (l *UniqueFieldsLogger) Errorf(format string, args ...any)

Errorf logs a formatted message at error level.

func (*UniqueFieldsLogger) Info added in v0.19.0

func (l *UniqueFieldsLogger) Info(msg string)

Info logs a message at info level.

func (*UniqueFieldsLogger) Infof added in v0.19.0

func (l *UniqueFieldsLogger) Infof(format string, args ...any)

Infof logs a formatted message at info level.

func (*UniqueFieldsLogger) WithField added in v0.19.0

func (l *UniqueFieldsLogger) WithField(key string, value any) types.Logger

WithField returns a new logger with the field added. An existing field with the same key is replaced.

func (*UniqueFieldsLogger) WithFields added in v0.19.0

func (l *UniqueFieldsLogger) WithFields(fields map[string]any) types.Logger

WithFields returns a new logger with the fields added. Existing fields with the same keys are replaced.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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