0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

slackにGo言語で、postする

Last updated at Posted at 2020-12-27

はじめに

外部ライブラリを使用しないで、Slackに投稿する方法が気になったので、自分で組んでみた。
Slackの設定は、Bot Token Scopeschat:writefiles:writeを有効にする。
そして投稿したいチャンネルにアプリ許可を出しておくこと
test.pngという名の画像ファイルをあらかじめ用意しておくこと

ソースについて

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            = "{表示されたトークンを記載}"
	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())
}

結果

実行すると以下の通り投稿される。

image.png

余談

以下のリンクのライブラリを使用するともっと簡単にできるけど、機能を確認することや理解ならば、上のソースコードだけのほうが楽かな

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?