Add interactif slack message

Signed-off-by: Sacha Al Himdani <sacha@getprobo.com>
This commit is contained in:
Sacha Al Himdani
2025-10-20 17:22:02 +02:00
parent de004ce8d7
commit 0073846d3b
23 changed files with 1833 additions and 173 deletions

View File

@@ -21,63 +21,161 @@ import (
"fmt"
"io"
"net/http"
"go.gearno.de/kit/httpclient"
"go.gearno.de/kit/log"
)
const (
slackAPIPostMessage = "https://slack.com/api/chat.postMessage"
slackAPIUpdateMessage = "https://slack.com/api/chat.update"
slackAPIConversationJoin = "https://slack.com/api/conversations.join"
)
type (
Client struct {
webhookURL string
httpClient *http.Client
}
webhookMessage struct {
Text string `json:"text,omitempty"`
Blocks []block `json:"blocks,omitempty"`
}
block struct {
Type string `json:"type"`
Text *textItem `json:"text,omitempty"`
}
textItem struct {
Type string `json:"type"`
Text string `json:"text"`
SlackResponse struct {
OK bool `json:"ok,omitempty"`
TS string `json:"ts,omitempty"`
Channel string `json:"channel,omitempty"`
Error string `json:"error,omitempty"`
}
)
func NewClient(webhookURL string, httpClient *http.Client) *Client {
func NewClient(logger *log.Logger) *Client {
httpClientOpts := []httpclient.Option{
httpclient.WithLogger(logger),
}
return &Client{
webhookURL: webhookURL,
httpClient: httpClient,
httpClient: httpclient.DefaultPooledClient(httpClientOpts...),
}
}
func (c *Client) PostMessage(ctx context.Context, text string) error {
msg := webhookMessage{
Text: text,
Blocks: []block{
{
Type: "section",
Text: &textItem{
Type: "mrkdwn",
Text: text,
},
},
},
func (c *Client) CreateMessage(ctx context.Context, accessToken string, channelID string, body map[string]any) (*SlackResponse, error) {
payload := map[string]any{
"channel": channelID,
"text": body["text"],
"blocks": body["blocks"],
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(msg); err != nil {
if err := json.NewEncoder(&buf).Encode(payload); err != nil {
return nil, fmt.Errorf("cannot marshal message: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, slackAPIPostMessage, &buf)
if err != nil {
return nil, fmt.Errorf("cannot create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := c.httpClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("cannot send request: %w", err)
}
defer resp.Body.Close()
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d, response body: %s", resp.StatusCode, string(responseBody))
}
var slackResponse SlackResponse
if err := json.NewDecoder(bytes.NewReader(responseBody)).Decode(&slackResponse); err != nil {
return nil, fmt.Errorf("failed to parse Slack response: %w (body: %s)", err, string(responseBody))
}
if !slackResponse.OK {
return nil, fmt.Errorf("Slack API error: %s (channel: %s, response: %s)", slackResponse.Error, channelID, string(responseBody))
}
return &slackResponse, nil
}
func (c *Client) UpdateInteractiveMessage(ctx context.Context, responseURL string, body map[string]any) error {
updatePayload := map[string]any{
"replace_original": true,
"text": body["text"],
"blocks": body["blocks"],
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(updatePayload); err != nil {
return fmt.Errorf("cannot marshal interactive message update: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, responseURL, &buf)
if err != nil {
return fmt.Errorf("cannot create interactive message update request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(httpReq)
if err != nil {
return fmt.Errorf("cannot send interactive message update request: %w", err)
}
defer resp.Body.Close()
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d, response body: %s", resp.StatusCode, string(responseBody))
}
// Slack can return either plain text "ok" or JSON {"ok":true}
bodyStr := string(responseBody)
if bodyStr == "ok" || bodyStr == "" {
return nil
}
var slackResponse SlackResponse
if err := json.NewDecoder(bytes.NewReader(responseBody)).Decode(&slackResponse); err == nil {
if slackResponse.OK {
return nil
}
if slackResponse.Error != "" {
return fmt.Errorf("Slack error: %s", slackResponse.Error)
}
}
return fmt.Errorf("unexpected Slack response: %s", bodyStr)
}
func (c *Client) UpdateMessage(ctx context.Context, accessToken string, channelID string, messageTS string, body map[string]any) error {
payload := map[string]any{
"channel": channelID,
"ts": messageTS,
"text": body["text"],
"blocks": body["blocks"],
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(payload); err != nil {
return fmt.Errorf("cannot marshal message: %w", err)
}
body := buf.Bytes()
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.webhookURL, bytes.NewReader(body))
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, slackAPIUpdateMessage, &buf)
if err != nil {
return fmt.Errorf("cannot create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := c.httpClient.Do(httpReq)
if err != nil {
@@ -85,20 +183,76 @@ func (c *Client) PostMessage(ctx context.Context, text string) error {
}
defer resp.Body.Close()
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("unexpected status code: %d, failed to read response body: %w", resp.StatusCode, err)
}
return fmt.Errorf("unexpected status code: %d, response body: %s", resp.StatusCode, string(responseBody))
}
var errorResponse map[string]any
var buf bytes.Buffer
buf.Write(body)
if err := json.NewDecoder(&buf).Decode(&errorResponse); err != nil {
return fmt.Errorf("unexpected status code: %d, response body: %s", resp.StatusCode, string(body))
}
var slackResponse SlackResponse
if err := json.NewDecoder(bytes.NewReader(responseBody)).Decode(&slackResponse); err != nil {
return fmt.Errorf("failed to parse Slack response: %w (body: %s)", err, string(responseBody))
}
return fmt.Errorf("unexpected status code: %d, response: %+v", resp.StatusCode, errorResponse)
if !slackResponse.OK {
return fmt.Errorf("Slack API error: %s", slackResponse.Error)
}
return nil
}
func (c *Client) JoinChannel(ctx context.Context, accessToken string, channelID string) error {
payload := map[string]any{
"channel": channelID,
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(payload); err != nil {
return fmt.Errorf("cannot marshal request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, slackAPIConversationJoin, &buf)
if err != nil {
return fmt.Errorf("cannot create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := c.httpClient.Do(httpReq)
if err != nil {
return fmt.Errorf("cannot send request: %w", err)
}
defer resp.Body.Close()
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d, response body: %s", resp.StatusCode, string(responseBody))
}
var slackResponse SlackResponse
if err := json.NewDecoder(bytes.NewReader(responseBody)).Decode(&slackResponse); err != nil {
return fmt.Errorf("failed to parse Slack response: %w (body: %s)", err, string(responseBody))
}
if !slackResponse.OK {
if slackResponse.Error == "already_in_channel" {
return nil
}
if slackResponse.Error == "channel_not_found" || slackResponse.Error == "is_private" {
return fmt.Errorf("cannot join private channel - bot must be invited manually")
}
return fmt.Errorf("Slack API error: %s", slackResponse.Error)
}
return nil

View File

@@ -18,13 +18,11 @@ import (
"context"
"errors"
"fmt"
"net/http"
"time"
"github.com/getprobo/probo/pkg/connector"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/crypto/cipher"
"go.gearno.de/kit/httpclient"
"go.gearno.de/kit/log"
"go.gearno.de/kit/pg"
)
@@ -35,7 +33,6 @@ type (
logger *log.Logger
encryptionKey cipher.EncryptionKey
interval time.Duration
httpClient *http.Client
}
Config struct {
@@ -44,18 +41,11 @@ type (
)
func NewSender(pg *pg.Client, logger *log.Logger, encryptionKey cipher.EncryptionKey, cfg Config) *Sender {
httpClientOpts := []httpclient.Option{
httpclient.WithLogger(logger),
}
httpClient := httpclient.DefaultPooledClient(httpClientOpts...)
return &Sender{
pg: pg,
logger: logger,
encryptionKey: encryptionKey,
interval: cfg.Interval,
httpClient: httpClient,
}
}
@@ -70,6 +60,10 @@ LOOP:
s.logger.ErrorCtx(ctx, "cannot send slack message", log.Error(err))
}
if err := s.batchUpdateMessages(ctx); err != nil {
s.logger.ErrorCtx(ctx, "cannot update slack message", log.Error(err))
}
goto LOOP
}
}
@@ -101,7 +95,14 @@ func (s *Sender) batchSendMessages(ctx context.Context) error {
return err
}
if sendErr := s.sendMessage(ctx, tx, message); sendErr != nil {
channelID, messageTS, sendErr := s.sendMessage(ctx, tx, message)
message.ChannelID = channelID
message.MessageTS = messageTS
now := time.Now()
message.UpdatedAt = now
if sendErr != nil {
errorMsg := sendErr.Error()
message.Error = &errorMsg
message.UpdatedAt = time.Now()
@@ -114,9 +115,7 @@ func (s *Sender) batchSendMessages(ctx context.Context) error {
return nil
}
now := time.Now()
message.SentAt = &now
message.UpdatedAt = now
if err := message.Update(ctx, tx); err != nil {
return fmt.Errorf("cannot update slack message: %w", err)
@@ -136,7 +135,137 @@ func (s *Sender) batchSendMessages(ctx context.Context) error {
}
}
func (s *Sender) sendMessage(ctx context.Context, tx pg.Conn, message *coredata.SlackMessage) error {
func (s *Sender) sendMessage(ctx context.Context, tx pg.Conn, message *coredata.SlackMessage) (*string, *string, error) {
tenantID := message.ID.TenantID()
scope := coredata.NewScope(tenantID)
var connectors coredata.Connectors
if err := connectors.LoadAllByOrganizationIDProtocolAndProvider(
ctx,
tx,
scope,
message.OrganizationID,
coredata.ConnectorProtocolOAuth2,
coredata.ConnectorProviderSlack,
s.encryptionKey,
); err != nil {
return nil, nil, fmt.Errorf("cannot load slack connectors: %w", err)
}
if len(connectors) == 0 {
return nil, nil, fmt.Errorf("no slack connectors configured for organization")
}
c := connectors[0]
if c.Connection == nil {
return nil, nil, fmt.Errorf("slack connector has nil connection")
}
slackConn, ok := c.Connection.(*connector.SlackConnection)
if !ok {
return nil, nil, fmt.Errorf("slack connector must have SlackConnection type, got %T", c.Connection)
}
if slackConn.Settings.ChannelID == "" {
return nil, nil, fmt.Errorf("slack connector %s has no channel ID", c.ID)
}
if slackConn.AccessToken == "" {
return nil, nil, fmt.Errorf("slack connector %s has no access token", c.ID)
}
client := NewClient(s.logger)
if message.Type == coredata.SlackMessageTypeWelcome {
if err := client.JoinChannel(ctx, slackConn.AccessToken, slackConn.Settings.ChannelID); err != nil {
s.logger.ErrorCtx(ctx, "failed to join Slack channel", log.Error(err))
}
}
slackResp, err := client.CreateMessage(ctx, slackConn.AccessToken, slackConn.Settings.ChannelID, message.Body)
if err != nil {
s.logger.ErrorCtx(ctx, "failed to post message to Slack", log.Error(err))
return nil, nil, fmt.Errorf("failed to post message to Slack: %w", err)
}
return &slackResp.Channel, &slackResp.TS, nil
}
func (s *Sender) batchUpdateMessages(ctx context.Context) error {
for {
err := s.pg.WithTx(
ctx,
func(tx pg.Conn) (err error) {
update := &coredata.SlackMessageUpdate{}
defer func() {
if r := recover(); r != nil {
panicErr := fmt.Sprintf("panic recovered: %v", r)
update.Error = &panicErr
update.UpdatedAt = time.Now()
if updateErr := update.Update(ctx, tx); updateErr != nil {
s.logger.ErrorCtx(ctx, "cannot update slack message update after panic", log.Error(updateErr))
}
s.logger.ErrorCtx(ctx, "panic while updating slack message", log.String("error", panicErr), log.String("update_id", update.ID.String()))
err = fmt.Errorf("panic recovered: %v", r)
}
}()
err = update.LoadNextUnsentForUpdate(ctx, tx)
if err != nil {
return err
}
message := &coredata.SlackMessage{}
if err := message.LoadById(ctx, tx, coredata.NewScope(update.SlackMessageID.TenantID()), update.SlackMessageID); err != nil {
return fmt.Errorf("cannot load slack message: %w", err)
}
updateErr := s.updateMessage(ctx, tx, message, update)
now := time.Now()
update.UpdatedAt = now
if updateErr != nil {
errorMsg := updateErr.Error()
update.Error = &errorMsg
update.UpdatedAt = time.Now()
if err := update.Update(ctx, tx); err != nil {
return fmt.Errorf("cannot update slack message update with error: %w", err)
}
s.logger.ErrorCtx(ctx, "error updating slack message", log.Error(updateErr), log.String("update_id", update.ID.String()))
return nil
}
update.SentAt = &now
if err := update.Update(ctx, tx); err != nil {
return fmt.Errorf("cannot update slack message update: %w", err)
}
return nil
},
)
if errors.Is(err, coredata.ErrNoUnsentSlackMessageUpdate{}) {
return nil
}
if err != nil {
return err
}
}
}
func (s *Sender) updateMessage(ctx context.Context, tx pg.Conn, message *coredata.SlackMessage, update *coredata.SlackMessageUpdate) error {
if message.ChannelID == nil || message.MessageTS == nil {
return fmt.Errorf("slack message has no channel ID or message TS")
}
tenantID := message.ID.TenantID()
scope := coredata.NewScope(tenantID)
@@ -157,20 +286,25 @@ func (s *Sender) sendMessage(ctx context.Context, tx pg.Conn, message *coredata.
return fmt.Errorf("no slack connectors configured for organization")
}
for _, c := range connectors {
slackConn, ok := c.Connection.(*connector.SlackConnection)
if !ok {
return fmt.Errorf("slack connector must have SlackConnection type")
}
c := connectors[0]
if c.Connection == nil {
return fmt.Errorf("slack connector has nil connection")
}
if slackConn.Settings.WebhookURL == "" {
return fmt.Errorf("slack connector %s has no webhook URL", c.ID)
}
slackConn, ok := c.Connection.(*connector.SlackConnection)
if !ok {
return fmt.Errorf("slack connector must have SlackConnection type, got %T", c.Connection)
}
client := NewClient(slackConn.Settings.WebhookURL, s.httpClient)
if err := client.PostMessage(ctx, message.Body); err != nil {
return fmt.Errorf("failed to post message to Slack: %w", err)
}
if slackConn.AccessToken == "" {
return fmt.Errorf("slack connector %s has no access token", c.ID)
}
client := NewClient(s.logger)
if err := client.UpdateMessage(ctx, slackConn.AccessToken, *message.ChannelID, *message.MessageTS, update.Body); err != nil {
s.logger.ErrorCtx(ctx, "failed to update message on Slack", log.Error(err))
return fmt.Errorf("failed to update message on Slack: %w", err)
}
return nil

56
pkg/slack/signature.go Normal file
View File

@@ -0,0 +1,56 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package slack
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"time"
)
// VerifySignature implements the verification algorithm described in https://api.slack.com/authentication/verifying-requests-from-slack
func VerifySignature(signingSecret, timestamp, signature string, body []byte) error {
// Check timestamp to prevent replay attacks
ts, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil {
return fmt.Errorf("invalid timestamp: %w", err)
}
now := time.Now().Unix()
if abs(now-ts) > 60*5 { // 5 minutes
return fmt.Errorf("request timestamp too old")
}
baseString := fmt.Sprintf("v0:%s:%s", timestamp, body)
h := hmac.New(sha256.New, []byte(signingSecret))
h.Write([]byte(baseString))
expected := "v0=" + hex.EncodeToString(h.Sum(nil))
if !hmac.Equal([]byte(expected), []byte(signature)) {
return fmt.Errorf("signature mismatch")
}
return nil
}
func abs(n int64) int64 {
if n < 0 {
return -n
}
return n
}