forked from kelos-dev/kelos
-
Notifications
You must be signed in to change notification settings - Fork 0
feat: implement SlackSource with Socket Mode listener #36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jkahuja
wants to merge
3
commits into
AIE-17-slack-api-types
Choose a base branch
from
AIE-17-slack-source
base: AIE-17-slack-api-types
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+622
−0
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,271 @@ | ||
| package source | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "strings" | ||
| "sync" | ||
|
|
||
| "github.com/slack-go/slack" | ||
| "github.com/slack-go/slack/slackevents" | ||
| "github.com/slack-go/slack/socketmode" | ||
| ctrl "sigs.k8s.io/controller-runtime" | ||
| ) | ||
|
|
||
| // SlackSource discovers work items from Slack messages via Socket Mode. | ||
| // A background goroutine listens for Slack events and accumulates WorkItems | ||
| // in an internal queue. Discover() drains the queue on each call. | ||
| type SlackSource struct { | ||
| // BotToken is the Bot User OAuth Token (xoxb-...). | ||
| BotToken string | ||
| // AppToken is the App-Level Token for Socket Mode (xapp-...). | ||
| AppToken string | ||
| // TriggerCommand is an optional slash command or message prefix. | ||
| // When empty, every non-threaded message triggers a task. | ||
| TriggerCommand string | ||
| // Channels restricts listening to specific channel IDs. Empty = all. | ||
| Channels []string | ||
| // AllowedUsers restricts which user IDs can trigger tasks. Empty = all. | ||
| AllowedUsers []string | ||
|
|
||
| mu sync.Mutex | ||
| pending []WorkItem | ||
| counter int | ||
| started bool | ||
| selfUserID string | ||
| api *slack.Client | ||
| cancel context.CancelFunc | ||
| } | ||
|
|
||
| // Discover returns accumulated WorkItems since the last call. | ||
| // On the first call it starts the Socket Mode listener. | ||
| func (s *SlackSource) Discover(ctx context.Context) ([]WorkItem, error) { | ||
| if !s.started { | ||
| if err := s.Start(ctx); err != nil { | ||
| return nil, fmt.Errorf("Starting Slack source: %w", err) | ||
| } | ||
| s.started = true | ||
| } | ||
|
|
||
| s.mu.Lock() | ||
| items := s.pending | ||
| s.pending = nil | ||
| s.mu.Unlock() | ||
|
|
||
| return items, nil | ||
| } | ||
|
|
||
| // Start connects to Slack via Socket Mode and begins listening for events. | ||
| func (s *SlackSource) Start(ctx context.Context) error { | ||
| log := ctrl.Log.WithName("slack-source") | ||
|
|
||
| s.api = slack.New( | ||
| s.BotToken, | ||
| slack.OptionAppLevelToken(s.AppToken), | ||
| ) | ||
|
|
||
| authResp, err := s.api.AuthTestContext(ctx) | ||
| if err != nil { | ||
| return fmt.Errorf("Slack auth test failed: %w", err) | ||
| } | ||
| s.selfUserID = authResp.UserID | ||
| log.Info("Authenticated with Slack", "botUserID", s.selfUserID) | ||
|
|
||
| sm := socketmode.New(s.api) | ||
|
|
||
| ctx, s.cancel = context.WithCancel(ctx) | ||
knechtionscoding marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| go func() { | ||
| if err := sm.RunContext(ctx); err != nil { | ||
| log.Error(err, "Socket Mode connection closed") | ||
| } | ||
| }() | ||
|
|
||
| go func() { | ||
| for evt := range sm.Events { | ||
| switch evt.Type { | ||
| case socketmode.EventTypeEventsAPI: | ||
| s.handleEventsAPI(sm, evt) | ||
| case socketmode.EventTypeSlashCommand: | ||
| s.handleSlashCommand(sm, evt) | ||
| } | ||
| } | ||
| }() | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| // Stop shuts down the Socket Mode listener. | ||
| func (s *SlackSource) Stop() { | ||
| if s.cancel != nil { | ||
| s.cancel() | ||
| } | ||
| } | ||
knechtionscoding marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| func (s *SlackSource) handleEventsAPI(sm *socketmode.Client, evt socketmode.Event) { | ||
| log := ctrl.Log.WithName("slack-source") | ||
|
|
||
| eventsAPIEvent, ok := evt.Data.(slackevents.EventsAPIEvent) | ||
| if !ok { | ||
| sm.Ack(*evt.Request) | ||
| return | ||
| } | ||
| sm.Ack(*evt.Request) | ||
|
|
||
| innerEvent, ok := eventsAPIEvent.InnerEvent.Data.(*slackevents.MessageEvent) | ||
| if !ok { | ||
| return | ||
| } | ||
|
|
||
| body, ok := shouldProcess(innerEvent.User, innerEvent.SubType, innerEvent.ThreadTimeStamp, innerEvent.Text, s.selfUserID, s.TriggerCommand) | ||
| if !ok { | ||
| return | ||
| } | ||
|
|
||
| if !matchesChannel(innerEvent.Channel, s.Channels) { | ||
| return | ||
| } | ||
| if !matchesUser(innerEvent.User, s.AllowedUsers) { | ||
| return | ||
| } | ||
|
|
||
| userName := innerEvent.User | ||
| if info, err := s.api.GetUserInfo(innerEvent.User); err == nil { | ||
| userName = info.RealName | ||
| if userName == "" { | ||
| userName = info.Name | ||
| } | ||
| } | ||
|
|
||
| permalink := "" | ||
| if link, err := s.api.GetPermalink(&slack.PermalinkParameters{ | ||
| Channel: innerEvent.Channel, | ||
| Ts: innerEvent.TimeStamp, | ||
| }); err == nil { | ||
| permalink = link | ||
| } | ||
|
|
||
| channelName := innerEvent.Channel | ||
| if info, err := s.api.GetConversationInfo(&slack.GetConversationInfoInput{ | ||
| ChannelID: innerEvent.Channel, | ||
| }); err == nil { | ||
| channelName = info.Name | ||
| } | ||
greptile-apps[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| s.mu.Lock() | ||
| s.counter++ | ||
| item := buildWorkItem(innerEvent.TimeStamp, s.counter, userName, body, permalink, channelName) | ||
| s.pending = append(s.pending, item) | ||
| s.mu.Unlock() | ||
|
|
||
| log.Info("Queued Slack message as work item", "number", item.Number, "user", userName, "channel", channelName) | ||
| } | ||
|
|
||
| func (s *SlackSource) handleSlashCommand(sm *socketmode.Client, evt socketmode.Event) { | ||
| log := ctrl.Log.WithName("slack-source") | ||
|
|
||
| cmd, ok := evt.Data.(slack.SlashCommand) | ||
| if !ok { | ||
| sm.Ack(*evt.Request) | ||
| return | ||
| } | ||
| sm.Ack(*evt.Request) | ||
|
|
||
| if cmd.UserID == s.selfUserID { | ||
| return | ||
| } | ||
| if !matchesChannel(cmd.ChannelID, s.Channels) { | ||
| return | ||
| } | ||
| if !matchesUser(cmd.UserID, s.AllowedUsers) { | ||
| return | ||
| } | ||
|
|
||
| body := strings.TrimSpace(cmd.Text) | ||
| if body == "" { | ||
| return | ||
| } | ||
|
|
||
| userName := cmd.UserName | ||
| channelName := cmd.ChannelName | ||
|
|
||
| s.mu.Lock() | ||
| s.counter++ | ||
| item := buildWorkItem(cmd.TriggerID, s.counter, userName, body, "", channelName) | ||
greptile-apps[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| s.pending = append(s.pending, item) | ||
| s.mu.Unlock() | ||
|
|
||
| log.Info("Queued slash command as work item", "number", item.Number, "user", userName, "channel", channelName) | ||
| } | ||
|
|
||
| // shouldProcess decides whether a Slack message should become a WorkItem. | ||
| // It returns the processed body text and true if the message should trigger, | ||
| // or an empty string and false if it should be ignored. | ||
| func shouldProcess(userID, subtype, threadTS, text, selfUserID, triggerCmd string) (string, bool) { | ||
| if userID == selfUserID { | ||
| return "", false | ||
| } | ||
| if subtype == "bot_message" { | ||
| return "", false | ||
| } | ||
| if threadTS != "" { | ||
| return "", false | ||
| } | ||
| if text == "" { | ||
| return "", false | ||
| } | ||
|
|
||
| if triggerCmd != "" { | ||
| if !strings.HasPrefix(text, triggerCmd) { | ||
| return "", false | ||
| } | ||
| body := strings.TrimSpace(strings.TrimPrefix(text, triggerCmd)) | ||
| if body == "" { | ||
| return "", false | ||
| } | ||
| return body, true | ||
| } | ||
|
|
||
| return text, true | ||
greptile-apps[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| // matchesChannel returns true if channelID is in the allowed list, | ||
| // or if the allowed list is empty (all channels permitted). | ||
| func matchesChannel(channelID string, allowed []string) bool { | ||
| if len(allowed) == 0 { | ||
| return true | ||
| } | ||
| for _, id := range allowed { | ||
| if id == channelID { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| // matchesUser returns true if userID is in the allowed list, | ||
| // or if the allowed list is empty (all users permitted). | ||
| func matchesUser(userID string, allowed []string) bool { | ||
| if len(allowed) == 0 { | ||
| return true | ||
| } | ||
| for _, id := range allowed { | ||
| if id == userID { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| // buildWorkItem constructs a WorkItem from Slack message fields. | ||
| func buildWorkItem(id string, number int, userName, body, permalink, channelName string) WorkItem { | ||
| return WorkItem{ | ||
| ID: id, | ||
| Number: number, | ||
| Title: userName, | ||
| Body: body, | ||
| URL: permalink, | ||
| Labels: []string{channelName}, | ||
| Kind: "SlackMessage", | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.