Golang Slack Bots

Developing Slack Bots with Go: Part 1

Posted on

In my previous post I wrote a guide on how to post a simple Slack message using a bot with PHP. Now we will do the same thing but instead with Go. I have also decided to send a json request instead of a form-url encoded request like we did with PHP. There are some differences, let’s take a look.

Once again you will need to create a bot for your Slack workspace which I have covered in a previous post here.

Make sure you have your bot and that you have added this bot to a public channel. You will need your bot API token, the channel name as it is written with the hashtag, e.g. “#general”. Finally you will also need a message that you would like to send to your channel.

The token will need to be sent as an authorization header, the rest will be part of our json body.

In the above code we start by creating a “PostMessage” struct and adding our endpoint url for the chat.postMessage method as defined in the docs. The “PostMessage” will be marshalled to json and put into our post body. struct We then define our token which we will later add to our authorization header. We go ahead and fill our “PostMessage” struct with our channel and message. Then we marshall this which turns our struct into a json string. Finally we build our request with all these bits of information making sure to add our Content-Type and Authorization headers.

We can run this by typing “go run main.go” like so:

This will result in a message in the Slack channel #general

A test message to Slack using Go

Thank you for reading, don’t forget to leave a comment if you found this guide helpful or if you have any questions!

Got Something To Say?

Your email address will not be published. Required fields are marked *