Post to slack in Go language

Introduction

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

About the source

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())
}

result

When executed, it will be posted as follows.

image.png

Digression

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

Recommended Posts

Post to slack in Go language
Post to Slack in Python
Post from Python to Slack
Post to vim → Python → Slack
Post to Slack via Subscriber
Post to slack with Python 3
Hello World in GO language
Go language to see and remember Part 7 C language in GO language
Post Jenkins console output to Slack
[Go language] How to get terminal input in real time
Write tests in GO language + gin
Do something object-oriented in GO language
Created a package to support AWS Lambda development in Go language
Post a message from IBM Cloud Functions to Slack in Python
The easiest way to get started in Slack socket mode (Go)
Log in to Slack using requests in Python
How to make a request to bitFlyer Lightning's Private API in Go language
Java programmer touched Go language (Implement Java inheritance in Go language)
Image characters and post to slack (python slackbot)
How to multi-process exclusive control in C language
I wrote the hexagonal architecture in go language
Create a web server in Go language (net/http) (2)
I got an error when trying to run Hello World in Go language
Write Pulumi in Go
POST messages from python to Slack via incoming webhook
Try to make a Python module in C language
Go language learning record
Go language environment construction
Introduction to Python language
Go language cheat sheet
Features of Go language
Create a web server in Go language (net / http) (1)
Stumble when converting bidirectional list to JSON in Go
I wrote a CLI tool in Go language to view Qiita's tag feed with CLI
API implementation to toggle values in two ways (go)
[Natural language processing] I tried to visualize the hot topics this week in the Slack community
[Natural language processing] I tried to visualize the remarks of each member in the Slack community
How to temporarily implement a progress bar in a scripting language
I tried to illustrate the time and time in C language
I wrote it in Go to understand the SOLID principle
To write a test in Go, first design the interface
Django Changed to save lots of data in one go
Try HeloWorld in your own language (with How to & code)
Go language to see and remember Part 8 Call GO language from Python
Machine language embedding in C language
Covector to think in function
Heapsort made in C language
To flush stdout in Python
Login to website in Python
Scraping Go To Travel Accommodation
Implement recursive closures in Go
Connect to Postgresql with GO
Programming language in "Hello World"
go language learning miscellaneous notes 1
[Golang] About Go language channel
How to define Go variables
[Go] How to use "... (3 periods)"
Speech to speech in python [text to speech]
Implement Slack chatbot in Python
How to develop in Python
Try to select a language