SlideShare a Scribd company logo
1 of 45
Download to read offline
How to
Develop
Slack Bot
Using
Golang?
https://www.bacancytechnology.com
Introduction
Want to learn to build a slack bot using
Golang? Not sure where you can start? Here
we are to lessen your frustration and ease
your struggles. With the help of the go-slack
package, we will see how to set up a slack
workspace and connect the slack bot with
Golang.




In this tutorial, we will mainly focus on
setting up and creating a bot that can
interact with Slack channels and
workspace. The guide is mainly divided into
two sections:
Slack Set Up: Workspace setup and add
a bot app to it
Golang Set Up and Installation: Coding
part setup in which the bot app will be
sending requests to a Go backend via
Web Socket, termed Socket Mode in the
slack world.




Without further ado, let’s get started with
our tutorial: How to develop Slack Bot using
Golang.
Create Slack
Workspace
Go to slack and click Create a Workspace.
Add required details, a team or company
name, a channel name, and invite other
teammates who can interact with the bot.
Want the best? Demand the best! Get the
best!
Contact Bacancy and hire Golang
developer from us today to meet your
product requirements. All you need is our
highly skilled Golang experts. Period.
Create Slack
Application
Create a Slack application, visit the slack
website and select From scratch option.
Add an application name that will be
allowed by Workspace for further use.
Create a bot with the application.
Click on Bots; this will redirect to the Help
Page, select Add Scopes, and add
permissions to the application.
Click on Review Scopes to Add and add four
main scopes, which make the bot work with
the application.
Now install the application; if you’re not the
owner, then you have to request permission
from an Admin.
The next step is to select a channel the bot
can use to post on as an application.
Click Allow and get the OAuth token and
Webhook URL required for the
authentication process.
Invite the app to a channel. In my case, I
used a channel name slack-bot-golang.
Now, type a command message starting
with this /.; now we can invite the bot by
typing /invite @NameOfYourbot.
Basic Golang
Set-Up and
Installation
Create a new directory where we attach
all code further, set up communication
with the Slack channel, and write a code
with the authentication token.
We use the go-slack package that supports
the regular REST API, WebSockets, RTM,
and Events, and we use the godotenv
package to read environment variables.
Develop Slack
Bot using
Golan
First, create a .env file used to store slack
credentials, including channel ID. Find the
Token in the web UI where the application
is created; channel ID can be found in the
UI; go to Get channel details by clicking on
the dropdown arrow of the channel.
Let’s start coding. Create main.go. Start
with connecting to the workspace and post
a simple message to check if everything is
working.
Next, create a slack attachment, which
includes a message that we send to the
channel and add some fields to send extra
contextual data; it’s totally on us if we want
to add this data or not.
// main.go
package main
import (
"fmt"
"os"
"time"
"github.com/joho/godotenv"
"github.com/slack-go/slack"
)
func main() {
godotenv.Load(".env")
token :=
os.Getenv("SLACK_AUTH_TOKEN")
channelID :=
os.Getenv("SLACK_CHANNEL_ID")
client := slack.New(token,
slack.OptionDebug(true))
attachment := slack.Attachment{
Pretext: "Super Bot Message",
Text: "some text",
Color: "4af030",
Fields: []slack.AttachmentField{
{
Title: "Date",
Value: time.Now().String(),
},
},
}
_, timestamp, err := client.PostMessage(
channelID,
slack.MsgOptionAttachments(attachment
),
)
if err != nil {
panic(err)
}
fmt.Printf("Message sent at %s",
timestamp)
}
Run the below command to execute the
program. You can see a new message in
the slack channel.
go run main.go
Slack Events
API Call
Now, use slack events API and handle
events in the Slack channels. Our bot listen
to only mentioned events; if anyone
mentions the bot, it will receive a triggered
event. These events are delivered via
WebSocket.
First, we need to activate the section Socket
Mode; this allows the bot to connect via
WebSocket.
Now, add Event Subscriptions. Find it in the
Features tab, and toggle the button to
activate it. Then add the app_mention
scope to event subscriptions. This will
trigger mentioned new event in the
application.
The final thing is to generate an application
token. Currently, we have a bot token only,
but for events, we need an application
token.
Go to Settings->Basic Information and
scroll down to section App-Level Tokens
and click on Generate Tokens and Scope
and give a name for your Token.
On the app side, we need to add
connections:write scope to that token,
make sure to save the token by adding it to
the .env file as SLACK_APP_TOKEN.
To use Socket Mode, add a sub package of
slack-go called socketmode.
Next, create a new client for the socket
mode; with this, we have two clients, one
for regular API and one for WebSocket
events.
Now connect the WebSocket client by
calling socketmode.New and forward the
regular client as input and add
OptionAppLevelToken to the regular client
as is now required to connect to the Socket.


At last, we call socketClient.Run() , which
will block and process new WebSocket
messages on a channel at
socketClient.Events. We Put a for loop that
will continuously check for new events and
add a type switch to handle different
events. We attach a go-routine that will
handle incoming messages in the
background to listen to new events. And
with this, we trigger an event on the
EventAPI in Slack.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/joho/godotenv"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
"github.com/slack-go/slack/socketmode"
)
func main() {
godotenv.Load(".env")
token :=
os.Getenv("SLACK_AUTH_TOKEN")
appToken :=
os.Getenv("SLACK_APP_TOKEN")
client := slack.New(token,
slack.OptionDebug(true),
slack.OptionAppLevelToken(appToken))
socketClient := socketmode.New(
client,
socketmode.OptionDebug(true),
socketmode.OptionLog(log.New(os.Stdout,
"socketmode: ",
log.Lshortfile|log.LstdFlags)),
)
ctx, cancel :=
context.WithCancel(context.Background())
defer cancel()
go func(ctx context.Context, client
*slack.Client, socketClient
*socketmode.Client) {
for {
select {
case <-ctx.Done():
log.Println("Shutting down
socketmode listener")
return
case event := <-socketClient.Events:
switch event.Type {
case
socketmode.EventTypeEventsAPI:
eventsAPI, ok := event.Data.
(slackevents.EventsAPIEvent)
if !ok {
log.Printf("Could not type cast
the event to the EventsAPI: %vn", event)
}
}
}
}(ctx, client, socketClient)
socketClient.Run()
}


To test, run the program and enter the Slack
app or web, and mention by bot by using
@yourbotname.
go run main.go
You should be able to see the event being
logged in the command line running the
bot. The event we get is of the type
event_callback, and that contains a payload
with the actual event that was performed.
Next, start to implement the
HandleEventMessage , which will continue
the type switching. We can use the type
field to know how to handle the Event. Then
we can reach the payload event by using the
InnerEvent field.


func HandleEventMessage(event
slackevents.EventsAPIEvent, client
*slack.Client) error {
switch event.Type {
case slackevents.CallbackEvent:
innerEvent := event.InnerEvent
switch evnt := innerEvent.Data.(type) {
err :=
HandleAppMentionEventToBot(evnt,
if err != nil {
return err
}
}
default:
return errors.New("unsupported event
type")
}
return nil
}
Replace the previous log in the main
function that prints the event with the new
HandleEventMessage function.
log.Println(eventsAPI)
replace with
err := HandleEventMessage(eventsAPI,
client)
if err != nil {
log.Fatal(err)
}
We need to make the bot respond to the
user who mentioned it.
Next start with logging into the application
and adding the users:read scope to the bot
token, as we did earlier. After adding the
scope to the token, we will create the
HandleAppMentionEventToBot
This function will take a
*slackevents.AppMentionEvent and a
slack.Client as input so it can respond.
The event contains the user ID in the
event.User with which we can fetch user
details. The channel response is also
available during the event.Channel. The
data we need is the actual message the user
sent while mentioning, which we can fetch
from the event.Text.


func
HandleAppMentionEventToBot(event
*slackevents.AppMentionEvent, client
*slack.Client) error {
user, err :=
client.GetUserInfo(event.User)
if err != nil {
return err
}
text := strings.ToLower(event.Text)
attachment := slack.Attachment{}
if strings.Contains(text, "hello") ||
strings.Contains(text, "hi") {
attachment.Text = fmt.Sprintf("Hello
%s", user.Name)
attachment.Color = "#4af030"
} else if strings.Contains(text, "weather")
{
attachment.Text =
fmt.Sprintf("Weather is sunny today. %s",
user.Name)
attachment.Color = "#4af030"
} else {
attachment.Text = fmt.Sprintf("I am
good. How are you %s?", user.Name)
attachment.Color = "#4af030"
}
_, _, err =
client.PostMessage(event.Channel,
slack.MsgOptionAttachments(attachment
))
if err != nil {
return fmt.Errorf("failed to post
message: %w", err)
}
return nil
}
Now restart the program and say hello or hi
and say something else to see whether it
works as expected. You have missed some
scope if you get a “missing_scope” error.
Run the
Application
Here is the output of my currently running
a bot
Github
Repository:
Slack Bot Using
Golang
Example
If you want to visit the source code, please
clone the repository and set up the
project on your system. You can try
playing around with the demo application
and explore more.
Here’s the github repository: slack-bot-
using-golang-example
Conclusion
I hope the purpose of this tutorial: How to
Develop Slack Bot using Golang is served
as expected. This is a basic step-by-step
guide to get you started with
implementing slack bot with the go-slack
package. Write us back if you have any
questions, suggestions, or feedback. Feel
free to clone the repository and play
around with the code.

More Related Content

Similar to Develop Slack Bot Using Golang in Less Than 40 Steps

How to create a real time chat application using socket.io, golang, and vue js-
How to create a real time chat application using socket.io, golang, and vue js-How to create a real time chat application using socket.io, golang, and vue js-
How to create a real time chat application using socket.io, golang, and vue js-Katy Slemon
 
Real-time Automation Result in Slack Channel
Real-time Automation Result in Slack ChannelReal-time Automation Result in Slack Channel
Real-time Automation Result in Slack ChannelRapidValue
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
Google Wave 20/20: Product, Protocol, Platform
Google Wave 20/20: Product, Protocol, PlatformGoogle Wave 20/20: Product, Protocol, Platform
Google Wave 20/20: Product, Protocol, PlatformPamela Fox
 
How to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST FrameworkHow to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST FrameworkKaty Slemon
 
JSF 2.0 (JavaEE Webinar)
JSF 2.0 (JavaEE Webinar)JSF 2.0 (JavaEE Webinar)
JSF 2.0 (JavaEE Webinar)Roger Kitain
 
Integrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat applicationIntegrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat applicationErick Ranes Akbar Mawuntu
 
StackMob & Appcelerator Module Part One
StackMob & Appcelerator Module Part OneStackMob & Appcelerator Module Part One
StackMob & Appcelerator Module Part OneAaron Saunders
 
M365 global developer bootcamp 2019 PA
M365 global developer bootcamp 2019  PAM365 global developer bootcamp 2019  PA
M365 global developer bootcamp 2019 PAThomas Daly
 
Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...naseeb20
 
Creating Sentiment Line Chart with Watson
Creating Sentiment Line Chart with Watson Creating Sentiment Line Chart with Watson
Creating Sentiment Line Chart with Watson Dev_Events
 
How to Create a WhatsApp Chatbot using Flask Python Framework
How to Create a WhatsApp Chatbot using Flask Python FrameworkHow to Create a WhatsApp Chatbot using Flask Python Framework
How to Create a WhatsApp Chatbot using Flask Python FrameworkKommunicate Intentive Inc
 
The Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTree
The Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTreeThe Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTree
The Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTreeRedBlackTree
 
How to implement golang jwt authentication and authorization
How to implement golang jwt authentication and authorizationHow to implement golang jwt authentication and authorization
How to implement golang jwt authentication and authorizationKaty Slemon
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioKaty Slemon
 
OpenSocial Intro
OpenSocial IntroOpenSocial Intro
OpenSocial IntroPamela Fox
 

Similar to Develop Slack Bot Using Golang in Less Than 40 Steps (20)

Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017
Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017
Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017
 
How to create a real time chat application using socket.io, golang, and vue js-
How to create a real time chat application using socket.io, golang, and vue js-How to create a real time chat application using socket.io, golang, and vue js-
How to create a real time chat application using socket.io, golang, and vue js-
 
Real-time Automation Result in Slack Channel
Real-time Automation Result in Slack ChannelReal-time Automation Result in Slack Channel
Real-time Automation Result in Slack Channel
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
Wave Workshop
Wave WorkshopWave Workshop
Wave Workshop
 
Google Wave 20/20: Product, Protocol, Platform
Google Wave 20/20: Product, Protocol, PlatformGoogle Wave 20/20: Product, Protocol, Platform
Google Wave 20/20: Product, Protocol, Platform
 
How to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST FrameworkHow to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST Framework
 
Open tok api_tutorials
Open tok api_tutorialsOpen tok api_tutorials
Open tok api_tutorials
 
OpenTok_API_Tutorials.pdf
OpenTok_API_Tutorials.pdfOpenTok_API_Tutorials.pdf
OpenTok_API_Tutorials.pdf
 
JSF 2.0 (JavaEE Webinar)
JSF 2.0 (JavaEE Webinar)JSF 2.0 (JavaEE Webinar)
JSF 2.0 (JavaEE Webinar)
 
Integrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat applicationIntegrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat application
 
StackMob & Appcelerator Module Part One
StackMob & Appcelerator Module Part OneStackMob & Appcelerator Module Part One
StackMob & Appcelerator Module Part One
 
M365 global developer bootcamp 2019 PA
M365 global developer bootcamp 2019  PAM365 global developer bootcamp 2019  PA
M365 global developer bootcamp 2019 PA
 
Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...
 
Creating Sentiment Line Chart with Watson
Creating Sentiment Line Chart with Watson Creating Sentiment Line Chart with Watson
Creating Sentiment Line Chart with Watson
 
How to Create a WhatsApp Chatbot using Flask Python Framework
How to Create a WhatsApp Chatbot using Flask Python FrameworkHow to Create a WhatsApp Chatbot using Flask Python Framework
How to Create a WhatsApp Chatbot using Flask Python Framework
 
The Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTree
The Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTreeThe Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTree
The Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTree
 
How to implement golang jwt authentication and authorization
How to implement golang jwt authentication and authorizationHow to implement golang jwt authentication and authorization
How to implement golang jwt authentication and authorization
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
 
OpenSocial Intro
OpenSocial IntroOpenSocial Intro
OpenSocial Intro
 

More from Katy Slemon

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfKaty Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfKaty Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfKaty Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfKaty Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfKaty Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfKaty Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfKaty Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfKaty Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfKaty Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfKaty Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfKaty Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfKaty Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfKaty Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfKaty Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfKaty Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfKaty Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfKaty Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfKaty Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfKaty Slemon
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfUncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfKaty Slemon
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfUncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
 

Recently uploaded

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Recently uploaded (20)

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

Develop Slack Bot Using Golang in Less Than 40 Steps

  • 3. Want to learn to build a slack bot using Golang? Not sure where you can start? Here we are to lessen your frustration and ease your struggles. With the help of the go-slack package, we will see how to set up a slack workspace and connect the slack bot with Golang. In this tutorial, we will mainly focus on setting up and creating a bot that can interact with Slack channels and workspace. The guide is mainly divided into two sections:
  • 4. Slack Set Up: Workspace setup and add a bot app to it Golang Set Up and Installation: Coding part setup in which the bot app will be sending requests to a Go backend via Web Socket, termed Socket Mode in the slack world. Without further ado, let’s get started with our tutorial: How to develop Slack Bot using Golang.
  • 6. Go to slack and click Create a Workspace.
  • 7. Add required details, a team or company name, a channel name, and invite other teammates who can interact with the bot. Want the best? Demand the best! Get the best! Contact Bacancy and hire Golang developer from us today to meet your product requirements. All you need is our highly skilled Golang experts. Period.
  • 9. Create a Slack application, visit the slack website and select From scratch option. Add an application name that will be allowed by Workspace for further use. Create a bot with the application.
  • 10. Click on Bots; this will redirect to the Help Page, select Add Scopes, and add permissions to the application.
  • 11. Click on Review Scopes to Add and add four main scopes, which make the bot work with the application. Now install the application; if you’re not the owner, then you have to request permission from an Admin.
  • 12. The next step is to select a channel the bot can use to post on as an application.
  • 13. Click Allow and get the OAuth token and Webhook URL required for the authentication process.
  • 14. Invite the app to a channel. In my case, I used a channel name slack-bot-golang. Now, type a command message starting with this /.; now we can invite the bot by typing /invite @NameOfYourbot.
  • 15.
  • 17. Create a new directory where we attach all code further, set up communication with the Slack channel, and write a code with the authentication token. We use the go-slack package that supports the regular REST API, WebSockets, RTM, and Events, and we use the godotenv package to read environment variables.
  • 19. First, create a .env file used to store slack credentials, including channel ID. Find the Token in the web UI where the application is created; channel ID can be found in the UI; go to Get channel details by clicking on the dropdown arrow of the channel.
  • 20. Let’s start coding. Create main.go. Start with connecting to the workspace and post a simple message to check if everything is working. Next, create a slack attachment, which includes a message that we send to the channel and add some fields to send extra contextual data; it’s totally on us if we want to add this data or not. // main.go package main import ( "fmt" "os" "time" "github.com/joho/godotenv" "github.com/slack-go/slack" )
  • 21. func main() { godotenv.Load(".env") token := os.Getenv("SLACK_AUTH_TOKEN") channelID := os.Getenv("SLACK_CHANNEL_ID") client := slack.New(token, slack.OptionDebug(true)) attachment := slack.Attachment{ Pretext: "Super Bot Message", Text: "some text", Color: "4af030", Fields: []slack.AttachmentField{ {
  • 22. Title: "Date", Value: time.Now().String(), }, }, } _, timestamp, err := client.PostMessage( channelID, slack.MsgOptionAttachments(attachment ), ) if err != nil { panic(err) } fmt.Printf("Message sent at %s", timestamp) }
  • 23. Run the below command to execute the program. You can see a new message in the slack channel. go run main.go
  • 25. Now, use slack events API and handle events in the Slack channels. Our bot listen to only mentioned events; if anyone mentions the bot, it will receive a triggered event. These events are delivered via WebSocket. First, we need to activate the section Socket Mode; this allows the bot to connect via WebSocket.
  • 26. Now, add Event Subscriptions. Find it in the Features tab, and toggle the button to activate it. Then add the app_mention scope to event subscriptions. This will trigger mentioned new event in the application.
  • 27. The final thing is to generate an application token. Currently, we have a bot token only, but for events, we need an application token. Go to Settings->Basic Information and scroll down to section App-Level Tokens and click on Generate Tokens and Scope and give a name for your Token.
  • 28. On the app side, we need to add connections:write scope to that token, make sure to save the token by adding it to the .env file as SLACK_APP_TOKEN. To use Socket Mode, add a sub package of slack-go called socketmode. Next, create a new client for the socket mode; with this, we have two clients, one for regular API and one for WebSocket events.
  • 29. Now connect the WebSocket client by calling socketmode.New and forward the regular client as input and add OptionAppLevelToken to the regular client as is now required to connect to the Socket. At last, we call socketClient.Run() , which will block and process new WebSocket messages on a channel at socketClient.Events. We Put a for loop that will continuously check for new events and add a type switch to handle different events. We attach a go-routine that will handle incoming messages in the background to listen to new events. And with this, we trigger an event on the EventAPI in Slack.
  • 31. token := os.Getenv("SLACK_AUTH_TOKEN") appToken := os.Getenv("SLACK_APP_TOKEN") client := slack.New(token, slack.OptionDebug(true), slack.OptionAppLevelToken(appToken)) socketClient := socketmode.New( client, socketmode.OptionDebug(true), socketmode.OptionLog(log.New(os.Stdout, "socketmode: ", log.Lshortfile|log.LstdFlags)), ) ctx, cancel := context.WithCancel(context.Background()) defer cancel()
  • 32. go func(ctx context.Context, client *slack.Client, socketClient *socketmode.Client) { for { select { case <-ctx.Done(): log.Println("Shutting down socketmode listener") return case event := <-socketClient.Events: switch event.Type { case socketmode.EventTypeEventsAPI: eventsAPI, ok := event.Data. (slackevents.EventsAPIEvent) if !ok { log.Printf("Could not type cast the event to the EventsAPI: %vn", event)
  • 33. } } } }(ctx, client, socketClient) socketClient.Run() } To test, run the program and enter the Slack app or web, and mention by bot by using @yourbotname. go run main.go You should be able to see the event being logged in the command line running the bot. The event we get is of the type event_callback, and that contains a payload with the actual event that was performed.
  • 34. Next, start to implement the HandleEventMessage , which will continue the type switching. We can use the type field to know how to handle the Event. Then we can reach the payload event by using the InnerEvent field. func HandleEventMessage(event slackevents.EventsAPIEvent, client *slack.Client) error { switch event.Type { case slackevents.CallbackEvent: innerEvent := event.InnerEvent switch evnt := innerEvent.Data.(type) { err := HandleAppMentionEventToBot(evnt,
  • 35. if err != nil { return err } } default: return errors.New("unsupported event type") } return nil } Replace the previous log in the main function that prints the event with the new HandleEventMessage function.
  • 36. log.Println(eventsAPI) replace with err := HandleEventMessage(eventsAPI, client) if err != nil { log.Fatal(err) } We need to make the bot respond to the user who mentioned it. Next start with logging into the application and adding the users:read scope to the bot token, as we did earlier. After adding the scope to the token, we will create the HandleAppMentionEventToBot
  • 37. This function will take a *slackevents.AppMentionEvent and a slack.Client as input so it can respond. The event contains the user ID in the event.User with which we can fetch user details. The channel response is also available during the event.Channel. The data we need is the actual message the user sent while mentioning, which we can fetch from the event.Text. func HandleAppMentionEventToBot(event *slackevents.AppMentionEvent, client *slack.Client) error { user, err := client.GetUserInfo(event.User) if err != nil { return err }
  • 38. text := strings.ToLower(event.Text) attachment := slack.Attachment{} if strings.Contains(text, "hello") || strings.Contains(text, "hi") { attachment.Text = fmt.Sprintf("Hello %s", user.Name) attachment.Color = "#4af030" } else if strings.Contains(text, "weather") { attachment.Text = fmt.Sprintf("Weather is sunny today. %s", user.Name) attachment.Color = "#4af030" } else { attachment.Text = fmt.Sprintf("I am good. How are you %s?", user.Name) attachment.Color = "#4af030"
  • 39. } _, _, err = client.PostMessage(event.Channel, slack.MsgOptionAttachments(attachment )) if err != nil { return fmt.Errorf("failed to post message: %w", err) } return nil } Now restart the program and say hello or hi and say something else to see whether it works as expected. You have missed some scope if you get a “missing_scope” error.
  • 40.
  • 42. Here is the output of my currently running a bot
  • 44. If you want to visit the source code, please clone the repository and set up the project on your system. You can try playing around with the demo application and explore more. Here’s the github repository: slack-bot- using-golang-example
  • 45. Conclusion I hope the purpose of this tutorial: How to Develop Slack Bot using Golang is served as expected. This is a basic step-by-step guide to get you started with implementing slack bot with the go-slack package. Write us back if you have any questions, suggestions, or feedback. Feel free to clone the repository and play around with the code.