I was curious about how to post to Slack without using an external library, so I built it myself.
The Slack setting enables chat: write
and files: write
in Bot Token Scopes
.
And give the app permission to the channel you want to post
Prepare an image file named test.png in advance
main.go
package main
import (
"bytes"
"context"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
)
const (
SLACKPOSTMESSAGE = "https://slack.com/api/chat.postMessage"
SLACKPOSTFILE = "https://slack.com/api/files.upload"
TOKEN = "{List the displayed token}"
CHANNEL = "general"
)
}
func postSlackfile() string {
filename := "./test.png "
file, err := os.Open(filename)
if err != nil {
return ""
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", filepath.Base(filename))
if err != nil {
return ""
}
_, err = io.Copy(part, file)
if err != nil {
return ""
}
err = writer.Close()
if err != nil {
return ""
}
values := url.Values{
"token": {TOKEN},
}
values.Add("channels", CHANNEL)
values.Add("filename", filepath.Base(filename))
req, err := http.NewRequest("POST", SLACKPOSTFILE, body)
if err != nil {
return ""
}
req = req.WithContext(context.Background())
req.URL.RawQuery = (values).Encode()
req.Header.Add("Content-Type", writer.FormDataContentType())
client := &http.Client{}
// client.Timeout = time.Second * 15
resp, err := client.Do(req)
if err != nil {
return ""
}
defer resp.Body.Close()
body2, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ""
}
return string(body2)
}
func postSlackMessage(text string) string {
urldata := SLACKPOSTMESSAGE
values := url.Values{}
values.Set("token", TOKEN)
values.Add("channel", CHANNEL)
values.Add("text", text)
client := &http.Client{}
client.Timeout = time.Second * 15
req, err := http.NewRequest("POST", urldata, strings.NewReader(values.Encode()))
if err != nil {
return ""
}
//
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
return ""
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ""
}
return string(body)
}
func main(){
fmt.Println(postSlackMessage("Hello World\nbbb"))
fmt.Println(postSlackfile())
}
When executed, it will be posted as follows.
It's easier to do with the library linked below, but if you want to see and understand the features, just the source code above is easier.
https://github.com/nlopes/slack