How to Develop Slack Bot Using Golang.pdf

Katy Slemon
Katy SlemonSr. Tech Consultant at Bacancy Technology à Bacancy Technology

Want to set up and build a bot that can interact with Slack channels? Checkout this step-by-step tutorial to Develop Slack Bot Using Golang.

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.
How to Develop Slack Bot Using Golang.pdf
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.
How to Develop Slack Bot Using Golang.pdf
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.

Recommandé

How to build twitter bot using golang from scratch par
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchKaty Slemon
129 vues57 diapositives
Google Wave API: Now and Beyond par
Google Wave API: Now and BeyondGoogle Wave API: Now and Beyond
Google Wave API: Now and BeyondMarakana Inc.
1.3K vues43 diapositives
How to implement sso using o auth in golang application par
How to implement sso using o auth in golang applicationHow to implement sso using o auth in golang application
How to implement sso using o auth in golang applicationKaty Slemon
236 vues39 diapositives
Slack Integration Noida Meetup.pptx par
Slack Integration Noida Meetup.pptxSlack Integration Noida Meetup.pptx
Slack Integration Noida Meetup.pptxShiva Sahu
257 vues16 diapositives
Programming For Google Wave par
Programming For Google WaveProgramming For Google Wave
Programming For Google WaveRodrigo Borges
617 vues37 diapositives
Build apps for slack par
Build apps for slackBuild apps for slack
Build apps for slackBinod Jung Bogati
200 vues89 diapositives

Contenu connexe

Similaire à How to Develop Slack Bot Using Golang.pdf

Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017 par
Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017
Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017Rafael Antonio Gutiérrez Turullols
488 vues75 diapositives
How to create a real time chat application using socket.io, golang, and vue js- par
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
144 vues34 diapositives
Real-time Automation Result in Slack Channel par
Real-time Automation Result in Slack ChannelReal-time Automation Result in Slack Channel
Real-time Automation Result in Slack ChannelRapidValue
440 vues5 diapositives
Swiss army knife Spring par
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
1.7K vues24 diapositives
Wave Workshop par
Wave WorkshopWave Workshop
Wave WorkshopJason Dinh
363 vues17 diapositives
Google Wave 20/20: Product, Protocol, Platform par
Google Wave 20/20: Product, Protocol, PlatformGoogle Wave 20/20: Product, Protocol, Platform
Google Wave 20/20: Product, Protocol, PlatformPamela Fox
1.7K vues20 diapositives

Similaire à How to Develop Slack Bot Using Golang.pdf(20)

How to create a real time chat application using socket.io, golang, and vue js- par Katy Slemon
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 Slemon144 vues
Real-time Automation Result in Slack Channel par RapidValue
Real-time Automation Result in Slack ChannelReal-time Automation Result in Slack Channel
Real-time Automation Result in Slack Channel
RapidValue440 vues
Swiss army knife Spring par Mario Fusco
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
Mario Fusco1.7K vues
Google Wave 20/20: Product, Protocol, Platform par Pamela Fox
Google Wave 20/20: Product, Protocol, PlatformGoogle Wave 20/20: Product, Protocol, Platform
Google Wave 20/20: Product, Protocol, Platform
Pamela Fox1.7K vues
How to Implement Token Authentication Using the Django REST Framework par Katy Slemon
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
Katy Slemon100 vues
JSF 2.0 (JavaEE Webinar) par Roger Kitain
JSF 2.0 (JavaEE Webinar)JSF 2.0 (JavaEE Webinar)
JSF 2.0 (JavaEE Webinar)
Roger Kitain1.5K vues
StackMob & Appcelerator Module Part One par Aaron Saunders
StackMob & Appcelerator Module Part OneStackMob & Appcelerator Module Part One
StackMob & Appcelerator Module Part One
Aaron Saunders699 vues
M365 global developer bootcamp 2019 PA par Thomas Daly
M365 global developer bootcamp 2019  PAM365 global developer bootcamp 2019  PA
M365 global developer bootcamp 2019 PA
Thomas Daly152 vues
Implementation of Push Notification in React Native Android app using Firebas... par naseeb20
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...
naseeb2011 vues
Creating Sentiment Line Chart with Watson par Dev_Events
Creating Sentiment Line Chart with Watson Creating Sentiment Line Chart with Watson
Creating Sentiment Line Chart with Watson
Dev_Events485 vues
The Mobile ToolChain with Fastlane - Code Red Talk at RedBlackTree par 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
RedBlackTree540 vues
How to implement golang jwt authentication and authorization par Katy Slemon
How to implement golang jwt authentication and authorizationHow to implement golang jwt authentication and authorization
How to implement golang jwt authentication and authorization
Katy Slemon93 vues
How to build a chat application with react js, nodejs, and socket.io par Katy Slemon
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
Katy Slemon622 vues
OpenSocial Intro par Pamela Fox
OpenSocial IntroOpenSocial Intro
OpenSocial Intro
Pamela Fox2.7K vues

Plus de Katy Slemon

Data Science Use Cases in Retail & Healthcare Industries.pdf par
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
117 vues37 diapositives
How Much Does It Cost To Hire Golang Developer.pdf par
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
78 vues31 diapositives
What’s New in Flutter 3.pdf par
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfKaty Slemon
85 vues24 diapositives
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf par
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
72 vues36 diapositives
How to Implement Middleware Pipeline in VueJS.pdf par
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfKaty Slemon
116 vues32 diapositives
How to Build Laravel Package Using Composer.pdf par
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfKaty Slemon
68 vues32 diapositives

Plus de Katy Slemon(20)

Data Science Use Cases in Retail & Healthcare Industries.pdf par Katy Slemon
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
Katy Slemon117 vues
How Much Does It Cost To Hire Golang Developer.pdf par Katy Slemon
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
Katy Slemon78 vues
What’s New in Flutter 3.pdf par Katy Slemon
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon85 vues
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf par Katy Slemon
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
Katy Slemon72 vues
How to Implement Middleware Pipeline in VueJS.pdf par Katy Slemon
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon116 vues
How to Build Laravel Package Using Composer.pdf par Katy Slemon
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon68 vues
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf par Katy Slemon
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
Katy Slemon53 vues
IoT Based Battery Management System in Electric Vehicles.pdf par Katy Slemon
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
Katy Slemon930 vues
Understanding Flexbox Layout in React Native.pdf par Katy Slemon
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon128 vues
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf par Katy Slemon
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
Katy Slemon178 vues
New Features in iOS 15 and Swift 5.5.pdf par Katy Slemon
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
Katy Slemon114 vues
Choose the Right Battery Management System for Lithium Ion Batteries.pdf par Katy Slemon
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
Katy Slemon116 vues
Angular Universal How to Build Angular SEO Friendly App.pdf par Katy Slemon
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
Katy Slemon110 vues
Ruby On Rails Performance Tuning Guide.pdf par Katy Slemon
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon122 vues
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf par Katy Slemon
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
Katy Slemon39 vues
Unit Testing Using Mockito in Android (1).pdf par Katy Slemon
Unit Testing Using Mockito in Android (1).pdfUnit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdf
Katy Slemon114 vues
Why Use React Js A Complete Guide (1).pdf par Katy Slemon
Why Use React Js A Complete Guide (1).pdfWhy Use React Js A Complete Guide (1).pdf
Why Use React Js A Complete Guide (1).pdf
Katy Slemon161 vues
Why Use Ruby on Rails for eCommerce Project Proven Case Study.pdf par Katy Slemon
Why Use Ruby on Rails for eCommerce Project Proven Case Study.pdfWhy Use Ruby on Rails for eCommerce Project Proven Case Study.pdf
Why Use Ruby on Rails for eCommerce Project Proven Case Study.pdf
Katy Slemon535 vues
Bacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdf par Katy Slemon
Bacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdfBacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdf
Bacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdf
Katy Slemon71 vues
How to Integrate Google Adwords API in Laravel App.pdf par Katy Slemon
How to Integrate Google Adwords API in Laravel App.pdfHow to Integrate Google Adwords API in Laravel App.pdf
How to Integrate Google Adwords API in Laravel App.pdf
Katy Slemon426 vues

Dernier

Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze par
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng TszeDigital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng TszeNUS-ISS
19 vues47 diapositives
SAP Automation Using Bar Code and FIORI.pdf par
SAP Automation Using Bar Code and FIORI.pdfSAP Automation Using Bar Code and FIORI.pdf
SAP Automation Using Bar Code and FIORI.pdfVirendra Rai, PMP
19 vues38 diapositives
Black and White Modern Science Presentation.pptx par
Black and White Modern Science Presentation.pptxBlack and White Modern Science Presentation.pptx
Black and White Modern Science Presentation.pptxmaryamkhalid2916
14 vues21 diapositives
20231123_Camunda Meetup Vienna.pdf par
20231123_Camunda Meetup Vienna.pdf20231123_Camunda Meetup Vienna.pdf
20231123_Camunda Meetup Vienna.pdfPhactum Softwareentwicklung GmbH
23 vues73 diapositives
Future of Learning - Yap Aye Wee.pdf par
Future of Learning - Yap Aye Wee.pdfFuture of Learning - Yap Aye Wee.pdf
Future of Learning - Yap Aye Wee.pdfNUS-ISS
38 vues11 diapositives
[2023] Putting the R! in R&D.pdf par
[2023] Putting the R! in R&D.pdf[2023] Putting the R! in R&D.pdf
[2023] Putting the R! in R&D.pdfEleanor McHugh
38 vues127 diapositives

Dernier(20)

Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze par NUS-ISS
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng TszeDigital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze
NUS-ISS19 vues
Black and White Modern Science Presentation.pptx par maryamkhalid2916
Black and White Modern Science Presentation.pptxBlack and White Modern Science Presentation.pptx
Black and White Modern Science Presentation.pptx
Future of Learning - Yap Aye Wee.pdf par NUS-ISS
Future of Learning - Yap Aye Wee.pdfFuture of Learning - Yap Aye Wee.pdf
Future of Learning - Yap Aye Wee.pdf
NUS-ISS38 vues
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum... par NUS-ISS
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
NUS-ISS28 vues
Spesifikasi Lengkap ASUS Vivobook Go 14 par Dot Semarang
Spesifikasi Lengkap ASUS Vivobook Go 14Spesifikasi Lengkap ASUS Vivobook Go 14
Spesifikasi Lengkap ASUS Vivobook Go 14
Dot Semarang35 vues
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor... par Vadym Kazulkin
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
Vadym Kazulkin70 vues
Combining Orchestration and Choreography for a Clean Architecture par ThomasHeinrichs1
Combining Orchestration and Choreography for a Clean ArchitectureCombining Orchestration and Choreography for a Clean Architecture
Combining Orchestration and Choreography for a Clean Architecture
Emerging & Future Technology - How to Prepare for the Next 10 Years of Radica... par NUS-ISS
Emerging & Future Technology - How to Prepare for the Next 10 Years of Radica...Emerging & Future Technology - How to Prepare for the Next 10 Years of Radica...
Emerging & Future Technology - How to Prepare for the Next 10 Years of Radica...
NUS-ISS15 vues
.conf Go 2023 - Data analysis as a routine par Splunk
.conf Go 2023 - Data analysis as a routine.conf Go 2023 - Data analysis as a routine
.conf Go 2023 - Data analysis as a routine
Splunk90 vues
Attacking IoT Devices from a Web Perspective - Linux Day par Simone Onofri
Attacking IoT Devices from a Web Perspective - Linux Day Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day
Simone Onofri15 vues
The details of description: Techniques, tips, and tangents on alternative tex... par BookNet Canada
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...
BookNet Canada110 vues
STPI OctaNE CoE Brochure.pdf par madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb12 vues

How to Develop Slack Bot Using Golang.pdf

  • 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.
  • 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.
  • 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.