|
| 1 | +package slack |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + |
| 8 | + "github.com/nlopes/slack" |
| 9 | +) |
| 10 | + |
| 11 | +// Client Slack bot client. |
| 12 | +// needed scopes: chat:write, channels:read, groups:read, im:read, mpim:read |
| 13 | +type Client interface { |
| 14 | + SendMessage(msg string) error |
| 15 | +} |
| 16 | + |
| 17 | +// New creates a new instance. Needs the bot token and the channel name |
| 18 | +func New(token string, channel string) (Client, error) { |
| 19 | + slackClient := slack.New(token) |
| 20 | + if _, err := slackClient.AuthTest(); err != nil { |
| 21 | + return nil, err |
| 22 | + } |
| 23 | + var slackChannelID string |
| 24 | + var cursor string |
| 25 | + for { |
| 26 | + var err error |
| 27 | + var channels []slack.Channel |
| 28 | + // needed scopes: |
| 29 | + channels, cursor, err = slackClient.GetConversations(&slack.GetConversationsParameters{ |
| 30 | + ExcludeArchived: "true", |
| 31 | + Limit: 1000, |
| 32 | + Types: []string{"public_channel", "private_channel"}, |
| 33 | + Cursor: cursor, |
| 34 | + }) |
| 35 | + if err != nil { |
| 36 | + return nil, fmt.Errorf("error getting channel ids from slack. error: %v", err) |
| 37 | + } |
| 38 | + if len(channels) == 0 { |
| 39 | + return nil, fmt.Errorf("error getting channel ids from slack") |
| 40 | + } |
| 41 | + |
| 42 | + for _, c := range channels { |
| 43 | + if c.Name == channel { |
| 44 | + slackChannelID = c.ID |
| 45 | + break |
| 46 | + } |
| 47 | + } |
| 48 | + if slackChannelID != "" { |
| 49 | + break |
| 50 | + } |
| 51 | + } |
| 52 | + if slackChannelID == "" { |
| 53 | + return nil, fmt.Errorf("error finding slack channel %s", channel) |
| 54 | + } |
| 55 | + return &client{ |
| 56 | + slackChannelID: slackChannelID, |
| 57 | + slackClient: slackClient, |
| 58 | + }, nil |
| 59 | +} |
| 60 | + |
| 61 | +type client struct { |
| 62 | + slackChannelID string |
| 63 | + slackClient *slack.Client |
| 64 | +} |
| 65 | + |
| 66 | +// SendMessage sends a message to thr slack channel |
| 67 | +func (c *client) SendMessage(msg string) error { |
| 68 | + if c.slackChannelID == "" { |
| 69 | + return errors.New("no channel found") |
| 70 | + } |
| 71 | + if _, _, err := c.slackClient.PostMessageContext(context.Background(), |
| 72 | + c.slackChannelID, |
| 73 | + slack.MsgOptionText(msg, false), |
| 74 | + slack.MsgOptionAsUser(false), |
| 75 | + ); err != nil { |
| 76 | + return err |
| 77 | + } |
| 78 | + return nil |
| 79 | +} |
0 commit comments