slack

package
v0.0.0-...-72f1ef6 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2026 License: GPL-3.0 Imports: 29 Imported by: 0

Documentation

Overview

Package slack provides a Slack API client and interaction handlers.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoDMToUpdate indicates no DM exists to update.
	ErrNoDMToUpdate = errors.New("no DM found to update")
)

Errors.

Functions

This section is empty.

Types

type API

type API interface {
	// Team operations.
	GetTeamInfoContext(ctx context.Context) (*slack.TeamInfo, error)
	AuthTestContext(ctx context.Context) (*slack.AuthTestResponse, error)

	// Conversation operations.
	GetConversationInfoContext(ctx context.Context, input *slack.GetConversationInfoInput) (*slack.Channel, error)
	GetConversationHistoryContext(ctx context.Context, params *slack.GetConversationHistoryParameters) (*slack.GetConversationHistoryResponse, error)
	GetConversationsContext(ctx context.Context, params *slack.GetConversationsParameters) ([]slack.Channel, string, error)
	OpenConversationContext(ctx context.Context, params *slack.OpenConversationParameters) (*slack.Channel, bool, bool, error)
	GetUsersInConversationContext(ctx context.Context, params *slack.GetUsersInConversationParameters) ([]string, string, error)

	// Message operations.
	PostMessageContext(ctx context.Context, channelID string, options ...slack.MsgOption) (string, string, error)
	UpdateMessageContext(ctx context.Context, channelID, timestamp string, options ...slack.MsgOption) (string, string, string, error)
	SearchMessagesContext(ctx context.Context, query string, params slack.SearchParameters) (*slack.SearchMessages, error)

	// Reaction operations.
	AddReactionContext(ctx context.Context, name string, item slack.ItemRef) error
	RemoveReactionContext(ctx context.Context, name string, item slack.ItemRef) error

	// User operations.
	GetUserInfoContext(ctx context.Context, userID string) (*slack.User, error)
	GetUserPresenceContext(ctx context.Context, userID string) (*slack.UserPresence, error)

	// View operations.
	PublishViewContext(ctx context.Context, request slack.PublishViewContextRequest) (*slack.ViewResponse, error)
}

API defines the interface for Slack API operations. This abstraction allows for easier testing by enabling mock implementations.

type Client

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

Client wraps the Slack API client with caching.

func New

func New(token, signingSecret string) *Client

New creates a new Slack client with caching.

func (*Client) API

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

API returns the underlying Slack API client for compatibility. This unwraps the API interface to return the raw *slack.Client. Only use this when integrating with code that hasn't been refactored to use the API interface yet.

func (*Client) BotInfo

func (c *Client) BotInfo(ctx context.Context) (*slack.AuthTestResponse, error)

BotInfo returns information about the authenticated bot user (cached for 30 minutes).

func (*Client) ChannelHistory

func (c *Client) ChannelHistory(
	ctx context.Context, channelID string, oldest, latest string, limit int,
) (*slack.GetConversationHistoryResponse, error)

ChannelHistory retrieves channel message history with optional time filtering.

func (*Client) EventsHandler

func (c *Client) EventsHandler(writer http.ResponseWriter, r *http.Request)

EventsHandler handles Slack events.

func (*Client) FindDMMessagesInHistory

func (c *Client) FindDMMessagesInHistory(ctx context.Context, userID, prURL string, since time.Time) ([]DMLocation, error)

FindDMMessagesInHistory searches Slack DM history to find existing messages about a PR. This is the fallback when cache/datastore don't have the DM location. Searches since the given time in DM history using the Slack API directly.

func (*Client) HasRecentDMAboutPR

func (c *Client) HasRecentDMAboutPR(ctx context.Context, userID, prURL string) (bool, error)

HasRecentDMAboutPR checks if we recently sent a DM to this user about this PR (within last hour). This prevents duplicate DMs during rolling deployments.

func (*Client) InteractionsHandler

func (c *Client) InteractionsHandler(writer http.ResponseWriter, r *http.Request)

InteractionsHandler handles Slack interactive components.

func (*Client) InvalidateChannel

func (c *Client) InvalidateChannel(channelID string)

InvalidateChannel removes cached data for a specific channel (helpful during setup).

func (*Client) IsBotInChannel

func (c *Client) IsBotInChannel(ctx context.Context, channelID string) bool

IsBotInChannel checks if the bot is a member of the specified channel with adaptive caching.

func (*Client) IsUserActive

func (c *Client) IsUserActive(ctx context.Context, userID string) bool

IsUserActive checks if a user is currently active.

func (*Client) IsUserInChannel

func (c *Client) IsUserInChannel(ctx context.Context, channelID, userID string) bool

IsUserInChannel checks if a specific user is a member of the specified channel.

func (*Client) PostThread

func (c *Client) PostThread(ctx context.Context, channelID, text string, attachments []slack.Attachment) (string, error)

PostThread creates a new thread in a channel for a PR with retry logic.

func (*Client) PostThreadReply

func (c *Client) PostThreadReply(ctx context.Context, channelID, threadTS, text string) error

PostThreadReply posts a reply to an existing thread with retry logic.

func (*Client) PublishHomeView

func (c *Client) PublishHomeView(ctx context.Context, userID string, blocks []slack.Block) error

PublishHomeView publishes a view to a user's app home with retry logic.

func (*Client) ResolveChannelID

func (c *Client) ResolveChannelID(ctx context.Context, channelName string) string

ResolveChannelID resolves a channel name (e.g., "all-codegroove" or "#all-codegroove") to a channel ID. Returns the channel ID if found, or the original input if it's already an ID or can't be resolved.

func (*Client) SaveDMMessageInfo

func (c *Client) SaveDMMessageInfo(ctx context.Context, userID, prURL, channelID, messageTS, messageText string) error

SaveDMMessageInfo saves DM message info to state store for future updates.

func (*Client) SearchMessages

func (c *Client) SearchMessages(ctx context.Context, query string, params *slack.SearchParameters) (*slack.SearchMessages, error)

SearchMessages searches for messages using the Slack API.

func (*Client) SendDirectMessage

func (c *Client) SendDirectMessage(ctx context.Context, userID, text string) (dmChannelID, messageTS string, err error)

SendDirectMessage sends a direct message to a user with retry logic.

func (*Client) SendDirectMessageWithBlocks

func (c *Client) SendDirectMessageWithBlocks(ctx context.Context, userID string, blocks []slack.Block) (dmChannelID, messageTS string, err error)

SendDirectMessageWithBlocks sends a direct message to a user with Block Kit blocks.

func (*Client) SetHomeViewHandler

func (c *Client) SetHomeViewHandler(handler func(ctx context.Context, teamID, userID string) error)

SetHomeViewHandler registers a callback for app_home_opened events.

func (*Client) SetManager

func (c *Client) SetManager(manager *Manager)

SetManager sets the manager reference for cache invalidation.

func (*Client) SetReportHandler

func (c *Client) SetReportHandler(handler func(ctx context.Context, teamID, userID string) error)

SetReportHandler registers a callback for /goose report slash command.

func (*Client) SetStateStore

func (c *Client) SetStateStore(store StateStore)

SetStateStore sets the state store for DM message tracking.

func (*Client) SetTeamID

func (c *Client) SetTeamID(teamID string)

SetTeamID sets the team ID for this client.

func (*Client) SlashCommandHandler

func (c *Client) SlashCommandHandler(writer http.ResponseWriter, r *http.Request)

SlashCommandHandler handles Slack slash commands.

func (*Client) UpdateDMMessage

func (c *Client) UpdateDMMessage(ctx context.Context, userID, prURL, newText string) error

UpdateDMMessage updates a previously sent DM message. Returns nil and logs debug if no DM exists, returns error if update fails.

func (*Client) UpdateMessage

func (c *Client) UpdateMessage(ctx context.Context, channelID, timestamp, text string) error

UpdateMessage updates an existing message with retry logic.

func (*Client) UserInfo

func (c *Client) UserInfo(ctx context.Context, userID string) (*slack.User, error)

UserInfo gets user information including timezone with retry logic.

func (*Client) UserPresence

func (c *Client) UserPresence(ctx context.Context, userID string) (string, error)

UserPresence gets user presence (active/away) with retry logic.

func (*Client) UserTimezone

func (c *Client) UserTimezone(ctx context.Context, userID string) (string, error)

UserTimezone returns the IANA timezone string for a user (e.g., "America/New_York"). Uses caching to minimize API calls.

func (*Client) VerifySignature

func (c *Client) VerifySignature(signature, timestamp string, body []byte) bool

VerifySignature verifies a Slack request signature (exported for use by EventRouter).

func (*Client) WorkspaceInfo

func (c *Client) WorkspaceInfo(ctx context.Context) (*slack.TeamInfo, error)

WorkspaceInfo returns information about the current workspace (cached for 1 hour).

type ConfigManager

type ConfigManager interface {
	Config(org string) (*config.RepoConfig, bool)
}

ConfigManager defines the interface for configuration management. This interface allows for easier testing by enabling mock implementations.

type DMLocation

type DMLocation struct {
	ChannelID string
	MessageTS string
}

DMLocation represents a DM message location in Slack.

type EventRouter

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

EventRouter routes Slack events to workspace-specific clients.

func NewEventRouter

func NewEventRouter(manager *Manager) *EventRouter

NewEventRouter creates a new event router.

func (*EventRouter) HandleEvents

func (er *EventRouter) HandleEvents(w http.ResponseWriter, req *http.Request)

HandleEvents routes incoming Slack events to the appropriate workspace client.

func (*EventRouter) HandleInteractions

func (er *EventRouter) HandleInteractions(w http.ResponseWriter, req *http.Request)

HandleInteractions routes Slack interactions to the appropriate workspace client.

func (*EventRouter) HandleSlashCommand

func (er *EventRouter) HandleSlashCommand(w http.ResponseWriter, req *http.Request)

HandleSlashCommand routes slash commands to the appropriate workspace client.

type GitHubManager

type GitHubManager interface {
	AllOrgs() []string
	ClientForOrg(org string) (*github.Client, bool)
}

GitHubManager defines the interface for GitHub client management. This interface allows for easier testing by enabling mock implementations.

type HomeHandler

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

HomeHandler handles app_home_opened events for a workspace.

func NewHomeHandler

func NewHomeHandler(
	slackManager *Manager,
	githubManager GitHubManager,
	configManager ConfigManager,
	stateStore state.Store,
	reverseMapping UserMapper,
) *HomeHandler

NewHomeHandler creates a new home view handler.

func (*HomeHandler) HandleAppHomeOpened

func (h *HomeHandler) HandleAppHomeOpened(ctx context.Context, teamID, slackUserID string) error

HandleAppHomeOpened updates the app home view when a user opens it.

type Manager

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

Manager manages Slack clients for multiple workspaces.

func NewManager

func NewManager(signingSecret string) *Manager

NewManager creates a new Slack client manager.

func (*Manager) Client

func (m *Manager) Client(ctx context.Context, teamID string) (*Client, error)

Client returns a Slack client for the given workspace. If the client doesn't exist in cache, it fetches the token from GSM.

func (*Manager) InvalidateCache

func (m *Manager) InvalidateCache(teamID string)

InvalidateCache removes a workspace from the cache, forcing a reload on next access.

func (*Manager) ListWorkspaces

func (m *Manager) ListWorkspaces() []*WorkspaceMetadata

ListWorkspaces returns metadata for all cached workspaces.

func (*Manager) RegisterWorkspace

func (m *Manager) RegisterWorkspace(ctx context.Context, teamID string, slackClient *slack.Client)

RegisterWorkspace registers a pre-configured Slack client for a workspace. This is only for integration testing - in production, clients are fetched from GSM.

func (*Manager) SetHomeViewHandler

func (m *Manager) SetHomeViewHandler(handler func(ctx context.Context, teamID, userID string) error)

SetHomeViewHandler sets the home view handler on all current and future clients.

func (*Manager) SetReportHandler

func (m *Manager) SetReportHandler(handler func(ctx context.Context, teamID, userID string) error)

SetReportHandler sets the report handler on all current and future clients.

func (*Manager) SetStateStore

func (m *Manager) SetStateStore(store StateStore)

SetStateStore sets the state store for DM message tracking.

func (*Manager) StoreWorkspace

func (m *Manager) StoreWorkspace(ctx context.Context, metadata *WorkspaceMetadata, token string) error

StoreWorkspace stores a workspace's token and metadata in GSM.

type OAuthExchanger

type OAuthExchanger interface {
	ExchangeCode(ctx context.Context, clientID, clientSecret, code string) (*slack.OAuthV2Response, error)
}

OAuthExchanger exchanges OAuth authorization codes for access tokens.

type OAuthHandler

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

OAuthHandler handles the OAuth callback from Slack.

func NewOAuthHandler

func NewOAuthHandler(manager *Manager, clientID, clientSecret string) *OAuthHandler

NewOAuthHandler creates a new OAuth handler. If manager is passed (implements WorkspaceStorer), it's used for both storage and debug listing.

func (*OAuthHandler) HandleCallback

func (h *OAuthHandler) HandleCallback(writer http.ResponseWriter, req *http.Request)

HandleCallback handles the OAuth callback from Slack.

func (*OAuthHandler) HandleDebug

func (h *OAuthHandler) HandleDebug(writer http.ResponseWriter, _ *http.Request)

HandleDebug returns JSON with installed workspaces (for debugging).

func (*OAuthHandler) HandleInstall

func (h *OAuthHandler) HandleInstall(writer http.ResponseWriter, _ *http.Request)

HandleInstall serves the "Add to Slack" installation page.

type OAuthResponse

type OAuthResponse struct {
	TeamID    string `json:"team_id"`
	TeamName  string `json:"team_name"`
	BotUserID string `json:"bot_user_id"`
}

OAuthResponse is a simplified response for debugging.

type ReportHandler

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

ReportHandler handles manual daily report generation via slash command.

func NewReportHandler

func NewReportHandler(
	slackManager *Manager,
	githubManager GitHubManager,
	stateStore state.Store,
	reverseMapping UserMapper,
) *ReportHandler

NewReportHandler creates a new report handler.

func (*ReportHandler) HandleReportCommand

func (h *ReportHandler) HandleReportCommand(ctx context.Context, teamID, slackUserID string) error

HandleReportCommand handles the /goose report slash command. It generates and sends a daily report for the requesting user, bypassing time window and interval checks.

type StateStore

type StateStore interface {
	DMMessage(ctx context.Context, userID, prURL string) (state.DMInfo, bool)
	SaveDMMessage(ctx context.Context, userID, prURL string, info state.DMInfo) error
}

StateStore interface for DM message tracking.

type UserMapper

type UserMapper interface {
	LookupGitHub(ctx context.Context, slackAPI usermapping.SlackAPI, slackUserID, org, emailDomain string) (*usermapping.ReverseMapping, error)
	SetOverrides(overrides map[string]string)
}

UserMapper defines the interface for Slack-to-GitHub user mapping. This interface allows for easier testing by enabling mock implementations.

type WorkspaceMetadata

type WorkspaceMetadata struct {
	TeamID      string `json:"team_id"`
	TeamName    string `json:"team_name"`
	BotUserID   string `json:"bot_user_id"`
	AccessToken string `json:"-"` // Never serialize token to JSON
}

WorkspaceMetadata contains metadata about a Slack workspace installation.

type WorkspaceStorer

type WorkspaceStorer interface {
	StoreWorkspace(ctx context.Context, metadata *WorkspaceMetadata, token string) error
}

WorkspaceStorer stores workspace credentials after OAuth completion.

Jump to

Keyboard shortcuts

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