Skip to content

Commit

Permalink
ADD: slack support
Browse files Browse the repository at this point in the history
  • Loading branch information
fileformat committed Apr 15, 2024
1 parent 40a9f29 commit 107735b
Show file tree
Hide file tree
Showing 6 changed files with 257 additions and 7 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ boo
/completions/
dist/
*.dll
.DS_Store
**/*.env
*.exe
*.exe~
Expand Down
224 changes: 224 additions & 0 deletions cmd/slack.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
package cmd

import (
"bytes"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"strings"
"time"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var (
slack_channel string
slack_bot_token string
)

var slackCmd = &cobra.Command{
Use: "slack",
Short: "Post to a Slack channel",
Long: `Post on a Slack channel. Note: \n * You need to set the SLACK_BOT_TOKEN in the environment`,
Args: cobra.ExactArgs(1),
RunE: slackPost,
}

func InitSlack() {
rootCmd.AddCommand(slackCmd)

slackCmd.Flags().StringVar(&slack_channel, "channel", "", "Slack Channel ID")

addImageFlag(slackCmd)

viper.BindEnv("SLACK_BOT_TOKEN")
}

type slackSectionText struct {
Type string `json:"type"`
Text string `json:"text"`
}

type slackSectionBlock struct {
Type string `json:"type"`
Text slackSectionText `json:"text"`
}

type slackSlackFile struct {
Id string `json:"id"`
}

type slackImageBlock struct {
Type string `json:"type"`
Image slackSlackFile `json:"slack_file"`
AltText string `json:"alt_text"`
}

type slackPostMessage struct {
Channel string `json:"channel"`
Text string `json:"text,omitempty"`
Blocks []interface{} `json:"blocks"`
}

func slackPost(cmd *cobra.Command, args []string) error {

slack_bot_token = viper.GetString("slack_bot_token")

hasImage, err := checkImage()
if err != nil {
return err
}

body, bodyErr := getInput(args[0])
if bodyErr != nil {
return bodyErr
}

blocks := make([]interface{}, 0)

sectionBlock := slackSectionBlock{
Type: "section",
Text: slackSectionText{
Type: "mrkdwn",
Text: body,
},
}
blocks = append(blocks, sectionBlock)

if hasImage {
photoId, photoErr := slackUploadImage()
if photoErr != nil {
return photoErr
}
blocks = append(blocks, slackImageBlock{
Type: "image",
Image: slackSlackFile{
Id: photoId,
},
AltText: "Image",
})
}

message := slackPostMessage{
Channel: slack_channel,
Text: fmt.Sprintf("Plain text: %s", body),
Blocks: blocks,
}

bytesBody, jsonErr := json.Marshal(message)
if jsonErr != nil {
return jsonErr
}
slog.Info("Slack body", "body", string(bytesBody))

bodyReader := bytes.NewReader(bytesBody)

req, reqErr := http.NewRequest(http.MethodPost, "https://slack.com/api/chat.postMessage", bodyReader)
if reqErr != nil {
return reqErr
}

req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", slack_bot_token))
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
req.Header.Set("User-Agent", UserAgent)
client := http.Client{
Timeout: 30 * time.Second,
}

res, resErr := client.Do(req)
if resErr != nil {
return resErr
}

resBody, readErr := io.ReadAll(res.Body)
if readErr != nil {
return readErr
}
slog.Info("Slack response", "status", res.Status, "body", resBody)
return nil
}

type slackGetUploadURLExternal struct {
Ok bool `json:"ok"`
UploadURL string `json:"upload_url"`
FileId string `json:"file_id"`
}

func slackUploadImage() (string, error) {

imageStat, statErr := os.Stat(imageFile)
if statErr != nil {
return "", statErr
}

requestURL := fmt.Sprintf("https://slack.com/api/files.getUploadURLExternal?filename=%s&length=%d", imageFile, imageStat.Size())
urlReq, urlReqErr := http.NewRequest("GET", requestURL, nil)
if urlReqErr != nil {
return "", urlReqErr
}
urlReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", slack_bot_token))
urlReq.Header.Set("User-Agent", UserAgent)
client := http.Client{
Timeout: 30 * time.Second,
}

urlResp, urlRespErr := client.Do(urlReq)
if urlRespErr != nil {
return "", urlRespErr
}
var uploadURL = slackGetUploadURLExternal{}
uploadURLBody, uploadURLErr := io.ReadAll(urlResp.Body)
if uploadURLErr != nil {
return "", uploadURLErr
}
jsonErr := json.Unmarshal(uploadURLBody, &uploadURL)
if jsonErr != nil {
return "", jsonErr
}

if !uploadURL.Ok {
return "", fmt.Errorf("failed to get upload URL: %s", uploadURLBody)
}

f, _ := os.Open(imageFile)
defer f.Close()

// post the image to the upload URL
postReq, postReqErr := http.NewRequest("POST", uploadURL.UploadURL, f)
if postReqErr != nil {
return "", postReqErr
}
postReq.Header.Set("Content-Type", "image/jpeg")
postReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", slack_bot_token))
postReq.Header.Set("User-Agent", UserAgent)

_, postErr := client.Do(postReq)
if postErr != nil {
return "", postErr
}

// complete the upload
completeBody := fmt.Sprintf("{\"files\": [{\"id\":\"%s\"}]}", uploadURL.FileId)
completeReq, completeReqErr := http.NewRequest("POST", "https://slack.com/api/files.completeUploadExternal", strings.NewReader(completeBody))
if completeReqErr != nil {
return "", completeReqErr
}
completeReq.Header.Set("Content-Type", "application/json; charset=UTF-8")
completeReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", slack_bot_token))
completeReq.Header.Set("User-Agent", UserAgent)

_, completeRespErr := client.Do(completeReq)
if completeRespErr != nil {
return "", completeRespErr
}

//discovered after much pain: sleep for 1 second
time.Sleep(5 * time.Second)

slog.Info("Uploaded image", "file_id", uploadURL.FileId)
return uploadURL.FileId, nil
}
12 changes: 8 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,29 @@ module github.com/fileformat/social-post

go 1.21.3

require (
github.com/g8rswimmer/go-twitter/v2 v2.1.5
github.com/muesli/mango-cobra v1.2.0
github.com/muesli/roff v0.1.0
github.com/spf13/cobra v1.8.0
github.com/spf13/viper v1.17.0
)

require (
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/muesli/mango v0.1.0 // indirect
github.com/muesli/mango-cobra v1.2.0 // indirect
github.com/muesli/mango-pflag v0.1.0 // indirect
github.com/muesli/roff v0.1.0
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/sagikazarmark/locafero v0.3.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.10.0 // indirect
github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/cobra v1.8.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.17.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
Expand Down
19 changes: 19 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,20 @@ github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnht
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po=
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY=
github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
github.com/g8rswimmer/go-twitter/v2 v2.1.5 h1:Uj9Yuof2UducrP4Xva7irnUJfB9354/VyUXKmc2D5gg=
github.com/g8rswimmer/go-twitter/v2 v2.1.5/go.mod h1:/55xWb313KQs25X7oZrNSEwLQNkYHhPsDwFstc45vhc=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
Expand Down Expand Up @@ -96,6 +102,8 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
Expand Down Expand Up @@ -127,8 +135,12 @@ github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/X
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
Expand All @@ -146,8 +158,12 @@ github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdU
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sagikazarmark/locafero v0.3.0 h1:zT7VEGWC2DTflmccN/5T1etyKvxSxpHsjb9cJvm4SvQ=
github.com/sagikazarmark/locafero v0.3.0/go.mod h1:w+v7UsPNFwzF1cHuOajOOzoq4U7v/ig1mpRjqV+Bu1U=
Expand All @@ -174,6 +190,7 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
Expand Down Expand Up @@ -477,6 +494,8 @@ google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGj
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
Expand Down
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ func main() {
cmd.InitEmail()
cmd.InitFacebook()
cmd.InitMastodon()
cmd.InitSlack()

cmd.Execute()

Expand Down
7 changes: 4 additions & 3 deletions run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ if [ -f ".env" ]; then
echo "INFO: loading .env"
export $(cat .env)
fi
export PATH=$PATH:$(pwd)/dist

#social-post email --subject="testing on $(date -u)" --to=fileformat@gmail.com "custom ua!"
#social-post facebook --image=${TEST_IMAGE} --image-caption="$(date -u)" "this is the shields!"
#social-post mastodon "from run.sh without image at $(date -u)!"
social-post mastodon --image=${TEST_IMAGE} --image-caption="$(date -u)" "from run.sh at $(date -u)!"
#go test -timeout 30s -run "^TestBadger$" github.com/FileFormatInfo/fflint/cmd/fflint
#social-post mastodon --image=${TEST_IMAGE} --image-caption="$(date -u)" "from run.sh at $(date -u)!"
#go test -timeout 30s -run "^TestBadger$" github.com/FileFormatInfo/fflint/cmd/fflint
./dist/social-post slack --channel ${SLACK_CHANNEL} --image=/Users/andrew/Downloads/vlz300.png "from *social-post-cli* at _$(date -u)_"

0 comments on commit 107735b

Please sign in to comment.