Movatterモバイル変換


[0]ホーム

URL:


Katy Slemon, profile picture
Uploaded byKaty Slemon
110 views

How to Develop Slack Bot Using Golang.pdf

This document provides a tutorial on how to develop a Slack bot using Golang. It discusses setting up a Slack workspace and creating a Slack app. It then covers installing Golang and the go-slack package to connect the bot to Slack. The tutorial demonstrates sending simple messages and handling events when the bot is mentioned. It includes code examples for connecting to Slack, posting messages, and responding to mention events.

Embed presentation

Download to read offline
How toDevelopSlack BotUsingGolang?https://www.bacancytechnology.com
Introduction
Want to learn to build a slack bot usingGolang? Not sure where you can start? Herewe are to lessen your frustration and easeyour struggles. With the help of the go-slackpackage, we will see how to set up a slackworkspace and connect the slack bot withGolang.In this tutorial, we will mainly focus onsetting up and creating a bot that caninteract with Slack channels andworkspace. The guide is mainly divided intotwo sections:
Slack Set Up: Workspace setup and adda bot app to itGolang Set Up and Installation: Codingpart setup in which the bot app will besending requests to a Go backend viaWeb Socket, termed Socket Mode in theslack world.Without further ado, let’s get started withour tutorial: How to develop Slack Bot usingGolang.
Create SlackWorkspace
Go to slack and click Create a Workspace.
Add required details, a team or companyname, a channel name, and invite otherteammates who can interact with the bot.Want the best? Demand the best! Get thebest!Contact Bacancy and hire Golangdeveloper from us today to meet yourproduct requirements. All you need is ourhighly skilled Golang experts. Period.
Create SlackApplication
Create a Slack application, visit the slackwebsite and select From scratch option.Add an application name that will beallowed by Workspace for further use.Create a bot with the application.
Click on Bots; this will redirect to the HelpPage, select Add Scopes, and addpermissions to the application.
Click on Review Scopes to Add and add fourmain scopes, which make the bot work withthe application.Now install the application; if you’re not theowner, then you have to request permissionfrom an Admin.
The next step is to select a channel the botcan use to post on as an application.
Click Allow and get the OAuth token andWebhook URL required for theauthentication process.
Invite the app to a channel. In my case, Iused a channel name slack-bot-golang.Now, type a command message startingwith this /.; now we can invite the bot bytyping /invite @NameOfYourbot.
Basic GolangSet-Up andInstallation
Create a new directory where we attachall code further, set up communicationwith the Slack channel, and write a codewith the authentication token.We use the go-slack package that supportsthe regular REST API, WebSockets, RTM,and Events, and we use the godotenvpackage to read environment variables.
Develop SlackBot usingGolan
First, create a .env file used to store slackcredentials, including channel ID. Find theToken in the web UI where the applicationis created; channel ID can be found in theUI; go to Get channel details by clicking onthe dropdown arrow of the channel.
Let’s start coding. Create main.go. Startwith connecting to the workspace and posta simple message to check if everything isworking.Next, create a slack attachment, whichincludes a message that we send to thechannel and add some fields to send extracontextual data; it’s totally on us if we wantto add this data or not.// main.gopackage mainimport ("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 theprogram. You can see a new message inthe slack channel.go run main.go
Slack EventsAPI Call
Now, use slack events API and handleevents in the Slack channels. Our bot listento only mentioned events; if anyonementions the bot, it will receive a triggeredevent. These events are delivered viaWebSocket.First, we need to activate the section SocketMode; this allows the bot to connect viaWebSocket.
Now, add Event Subscriptions. Find it in theFeatures tab, and toggle the button toactivate it. Then add the app_mentionscope to event subscriptions. This willtrigger mentioned new event in theapplication.
The final thing is to generate an applicationtoken. Currently, we have a bot token only,but for events, we need an applicationtoken.Go to Settings->Basic Information andscroll down to section App-Level Tokensand click on Generate Tokens and Scopeand give a name for your Token.
On the app side, we need to addconnections:write scope to that token,make sure to save the token by adding it tothe .env file as SLACK_APP_TOKEN.To use Socket Mode, add a sub package ofslack-go called socketmode.Next, create a new client for the socketmode; with this, we have two clients, onefor regular API and one for WebSocketevents.
Now connect the WebSocket client bycalling socketmode.New and forward theregular client as input and addOptionAppLevelToken to the regular clientas is now required to connect to the Socket.At last, we call socketClient.Run() , whichwill block and process new WebSocketmessages on a channel atsocketClient.Events. We Put a for loop thatwill continuously check for new events andadd a type switch to handle differentevents. We attach a go-routine that willhandle incoming messages in thebackground to listen to new events. Andwith this, we trigger an event on theEventAPI in Slack.
package mainimport ("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 downsocketmode listener")returncase event := <-socketClient.Events:switch event.Type {casesocketmode.EventTypeEventsAPI:eventsAPI, ok := event.Data.(slackevents.EventsAPIEvent)if !ok {log.Printf("Could not type castthe event to the EventsAPI: %vn", event)
}}}}(ctx, client, socketClient)socketClient.Run()}To test, run the program and enter the Slackapp or web, and mention by bot by using@yourbotname.go run main.goYou should be able to see the event beinglogged in the command line running thebot. The event we get is of the typeevent_callback, and that contains a payloadwith the actual event that was performed.
Next, start to implement theHandleEventMessage , which will continuethe type switching. We can use the typefield to know how to handle the Event. Thenwe can reach the payload event by using theInnerEvent field.func HandleEventMessage(eventslackevents.EventsAPIEvent, client*slack.Client) error {switch event.Type {case slackevents.CallbackEvent:innerEvent := event.InnerEventswitch evnt := innerEvent.Data.(type) {err :=HandleAppMentionEventToBot(evnt,
if err != nil {return err}}default:return errors.New("unsupported eventtype")}return nil}Replace the previous log in the mainfunction that prints the event with the newHandleEventMessage function.
log.Println(eventsAPI)replace witherr := HandleEventMessage(eventsAPI,client)if err != nil {log.Fatal(err)}We need to make the bot respond to theuser who mentioned it.Next start with logging into the applicationand adding the users:read scope to the bottoken, as we did earlier. After adding thescope to the token, we will create theHandleAppMentionEventToBot
This function will take a*slackevents.AppMentionEvent and aslack.Client as input so it can respond.The event contains the user ID in theevent.User with which we can fetch userdetails. The channel response is alsoavailable during the event.Channel. Thedata we need is the actual message the usersent while mentioning, which we can fetchfrom the event.Text.funcHandleAppMentionEventToBot(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 amgood. 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 postmessage: %w", err)}return nil}Now restart the program and say hello or hiand say something else to see whether itworks as expected. You have missed somescope if you get a “missing_scope” error.
Run theApplication
Here is the output of my currently runninga bot
GithubRepository:Slack Bot UsingGolangExample
If you want to visit the source code, pleaseclone the repository and set up theproject on your system. You can tryplaying around with the demo applicationand explore more.Here’s the github repository: slack-bot-using-golang-example
ConclusionI hope the purpose of this tutorial: How toDevelop Slack Bot using Golang is servedas expected. This is a basic step-by-stepguide to get you started withimplementing slack bot with the go-slackpackage. Write us back if you have anyquestions, suggestions, or feedback. Feelfree to clone the repository and playaround with the code.

Recommended

PDF
Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017
PDF
Introduction to Slack App Development
PDF
Chat Bots and how to build a Slack bot
PPTX
Slack Integration Noida Meetup.pptx
PDF
Build apps for slack
PDF
Identifying and solving enterprise problems
PDF
Building Enterprise Chat Bots
PPTX
Building a slack bot
PPTX
ChatGPT and Slack Integration with MuleSoft
PPTX
Slack and ChatGPT Integration using MuleSoft | MuleSoft Mysore Meetup #30
PDF
Building Slack Apps with Ruby – Kirill Shevchenko
PPTX
The Journey to conversational interfaces
PPTX
Slack apps
PPTX
How to build a slack bot
PDF
Slack bot v0.4
PDF
How to build twitter bot using golang from scratch
PPTX
Automatic Test Results Publishing using Slack
PPTX
Slack meetup 16 02-2020
PDF
[2019 south bay meetup] Building more contextual message with Block Kit
PDF
Writing a slack chatbot mxlos
PDF
Writing a slack chatbot DrupalCampLA
PDF
Introductions of Messaging bot 做聊天機器人
PDF
Writing a slack chatbot seattle
PPTX
How to build a slack-hubot with js
PDF
Bots and News
PPTX
Use Slack in software development processes
PDF
Slack の過去ログ倉庫を建てよう (2017 合宿 LT)
PDF
Building a slackbot
PDF
Angular Universal How to Build Angular SEO Friendly App.pdf
PDF
How to Build Laravel Package Using Composer.pdf

More Related Content

PDF
Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017
PDF
Introduction to Slack App Development
PDF
Chat Bots and how to build a Slack bot
PPTX
Slack Integration Noida Meetup.pptx
PDF
Build apps for slack
PDF
Identifying and solving enterprise problems
PDF
Building Enterprise Chat Bots
PPTX
Building a slack bot
Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017
Introduction to Slack App Development
Chat Bots and how to build a Slack bot
Slack Integration Noida Meetup.pptx
Build apps for slack
Identifying and solving enterprise problems
Building Enterprise Chat Bots
Building a slack bot

Similar to How to Develop Slack Bot Using Golang.pdf

PPTX
ChatGPT and Slack Integration with MuleSoft
PPTX
Slack and ChatGPT Integration using MuleSoft | MuleSoft Mysore Meetup #30
PDF
Building Slack Apps with Ruby – Kirill Shevchenko
PPTX
The Journey to conversational interfaces
PPTX
Slack apps
PPTX
How to build a slack bot
PDF
Slack bot v0.4
PDF
How to build twitter bot using golang from scratch
PPTX
Automatic Test Results Publishing using Slack
PPTX
Slack meetup 16 02-2020
PDF
[2019 south bay meetup] Building more contextual message with Block Kit
PDF
Writing a slack chatbot mxlos
PDF
Writing a slack chatbot DrupalCampLA
PDF
Introductions of Messaging bot 做聊天機器人
PDF
Writing a slack chatbot seattle
PPTX
How to build a slack-hubot with js
PDF
Bots and News
PPTX
Use Slack in software development processes
PDF
Slack の過去ログ倉庫を建てよう (2017 合宿 LT)
PDF
Building a slackbot
ChatGPT and Slack Integration with MuleSoft
Slack and ChatGPT Integration using MuleSoft | MuleSoft Mysore Meetup #30
Building Slack Apps with Ruby – Kirill Shevchenko
The Journey to conversational interfaces
Slack apps
How to build a slack bot
Slack bot v0.4
How to build twitter bot using golang from scratch
Automatic Test Results Publishing using Slack
Slack meetup 16 02-2020
[2019 south bay meetup] Building more contextual message with Block Kit
Writing a slack chatbot mxlos
Writing a slack chatbot DrupalCampLA
Introductions of Messaging bot 做聊天機器人
Writing a slack chatbot seattle
How to build a slack-hubot with js
Bots and News
Use Slack in software development processes
Slack の過去ログ倉庫を建てよう (2017 合宿 LT)
Building a slackbot

More from Katy Slemon

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

Recently uploaded

PDF
December Patch Tuesday
 
PPTX
Software Analysis &Design ethiopia chap-2.pptx
PDF
Security Technologys: Access Control, Firewall, VPN
PDF
Unlocking the Power of Salesforce Architecture: Frameworks for Effective Solu...
PDF
The year in review - MarvelClient in 2025
PPT
software-security-intro in information security.ppt
PDF
DevFest El Jadida 2025 - Product Thinking
PPTX
Coded Agents – with UiPath SDK + LangGraph [Virtual Hands-on Workshop]
PDF
GPUS and How to Program Them by Manya Bansal
PPTX
Kanban India 2025 | Daksh Gupta | Modeling the Models, Generative AI & Kanban
PDF
Decoding the DNA: The Digital Networks Act, the Open Internet, and IP interco...
PPTX
Building Cyber Resilience for 2026: Best Practices for a Secure, AI-Driven Bu...
PDF
TrustArc Webinar - Looking Ahead: The 2026 Privacy Landscape
PPTX
cybercrime in Information security .pptx
PPTX
Cybercrime in the Digital Age: Risks, Impact & Protection
PPTX
Protecting Data in an AI Driven World - Cybersecurity in 2026
PPTX
AI's Impact on Cybersecurity - Challenges and Opportunities
DOCX
Introduction to the World of Computers (Hardware & Software)
PPTX
From Backup to Resilience: How MSPs Are Preparing for 2026
 
PPTX
Data Privacy and Protection: Safeguarding Information in a Connected World
December Patch Tuesday
 
Software Analysis &Design ethiopia chap-2.pptx
Security Technologys: Access Control, Firewall, VPN
Unlocking the Power of Salesforce Architecture: Frameworks for Effective Solu...
The year in review - MarvelClient in 2025
software-security-intro in information security.ppt
DevFest El Jadida 2025 - Product Thinking
Coded Agents – with UiPath SDK + LangGraph [Virtual Hands-on Workshop]
GPUS and How to Program Them by Manya Bansal
Kanban India 2025 | Daksh Gupta | Modeling the Models, Generative AI & Kanban
Decoding the DNA: The Digital Networks Act, the Open Internet, and IP interco...
Building Cyber Resilience for 2026: Best Practices for a Secure, AI-Driven Bu...
TrustArc Webinar - Looking Ahead: The 2026 Privacy Landscape
cybercrime in Information security .pptx
Cybercrime in the Digital Age: Risks, Impact & Protection
Protecting Data in an AI Driven World - Cybersecurity in 2026
AI's Impact on Cybersecurity - Challenges and Opportunities
Introduction to the World of Computers (Hardware & Software)
From Backup to Resilience: How MSPs Are Preparing for 2026
 
Data Privacy and Protection: Safeguarding Information in a Connected World

How to Develop Slack Bot Using Golang.pdf

  • 1.
  • 2.
  • 3.
    Want to learnto build a slack bot usingGolang? Not sure where you can start? Herewe are to lessen your frustration and easeyour struggles. With the help of the go-slackpackage, we will see how to set up a slackworkspace and connect the slack bot withGolang.In this tutorial, we will mainly focus onsetting up and creating a bot that caninteract with Slack channels andworkspace. The guide is mainly divided intotwo sections:
  • 4.
    Slack Set Up:Workspace setup and adda bot app to itGolang Set Up and Installation: Codingpart setup in which the bot app will besending requests to a Go backend viaWeb Socket, termed Socket Mode in theslack world.Without further ado, let’s get started withour tutorial: How to develop Slack Bot usingGolang.
  • 5.
  • 6.
    Go to slackand click Create a Workspace.
  • 7.
    Add required details,a team or companyname, a channel name, and invite otherteammates who can interact with the bot.Want the best? Demand the best! Get thebest!Contact Bacancy and hire Golangdeveloper from us today to meet yourproduct requirements. All you need is ourhighly skilled Golang experts. Period.
  • 8.
  • 9.
    Create a Slackapplication, visit the slackwebsite and select From scratch option.Add an application name that will beallowed by Workspace for further use.Create a bot with the application.
  • 10.
    Click on Bots;this will redirect to the HelpPage, select Add Scopes, and addpermissions to the application.
  • 11.
    Click on ReviewScopes to Add and add fourmain scopes, which make the bot work withthe application.Now install the application; if you’re not theowner, then you have to request permissionfrom an Admin.
  • 12.
    The next stepis to select a channel the botcan use to post on as an application.
  • 13.
    Click Allow andget the OAuth token andWebhook URL required for theauthentication process.
  • 14.
    Invite the appto a channel. In my case, Iused a channel name slack-bot-golang.Now, type a command message startingwith this /.; now we can invite the bot bytyping /invite @NameOfYourbot.
  • 16.
  • 17.
    Create a newdirectory where we attachall code further, set up communicationwith the Slack channel, and write a codewith the authentication token.We use the go-slack package that supportsthe regular REST API, WebSockets, RTM,and Events, and we use the godotenvpackage to read environment variables.
  • 18.
  • 19.
    First, create a.env file used to store slackcredentials, including channel ID. Find theToken in the web UI where the applicationis created; channel ID can be found in theUI; go to Get channel details by clicking onthe dropdown arrow of the channel.
  • 20.
    Let’s start coding.Create main.go. Startwith connecting to the workspace and posta simple message to check if everything isworking.Next, create a slack attachment, whichincludes a message that we send to thechannel and add some fields to send extracontextual data; it’s totally on us if we wantto add this data or not.// main.gopackage mainimport ("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 belowcommand to execute theprogram. You can see a new message inthe slack channel.go run main.go
  • 24.
  • 25.
    Now, use slackevents API and handleevents in the Slack channels. Our bot listento only mentioned events; if anyonementions the bot, it will receive a triggeredevent. These events are delivered viaWebSocket.First, we need to activate the section SocketMode; this allows the bot to connect viaWebSocket.
  • 26.
    Now, add EventSubscriptions. Find it in theFeatures tab, and toggle the button toactivate it. Then add the app_mentionscope to event subscriptions. This willtrigger mentioned new event in theapplication.
  • 27.
    The final thingis to generate an applicationtoken. Currently, we have a bot token only,but for events, we need an applicationtoken.Go to Settings->Basic Information andscroll down to section App-Level Tokensand click on Generate Tokens and Scopeand give a name for your Token.
  • 28.
    On the appside, we need to addconnections:write scope to that token,make sure to save the token by adding it tothe .env file as SLACK_APP_TOKEN.To use Socket Mode, add a sub package ofslack-go called socketmode.Next, create a new client for the socketmode; with this, we have two clients, onefor regular API and one for WebSocketevents.
  • 29.
    Now connect theWebSocket client bycalling socketmode.New and forward theregular client as input and addOptionAppLevelToken to the regular clientas is now required to connect to the Socket.At last, we call socketClient.Run() , whichwill block and process new WebSocketmessages on a channel atsocketClient.Events. We Put a for loop thatwill continuously check for new events andadd a type switch to handle differentevents. We attach a go-routine that willhandle incoming messages in thebackground to listen to new events. Andwith this, we trigger an event on theEventAPI in Slack.
  • 30.
  • 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 downsocketmode listener")returncase event := <-socketClient.Events:switch event.Type {casesocketmode.EventTypeEventsAPI:eventsAPI, ok := event.Data.(slackevents.EventsAPIEvent)if !ok {log.Printf("Could not type castthe event to the EventsAPI: %vn", event)
  • 33.
    }}}}(ctx, client, socketClient)socketClient.Run()}Totest, run the program and enter the Slackapp or web, and mention by bot by using@yourbotname.go run main.goYou should be able to see the event beinglogged in the command line running thebot. The event we get is of the typeevent_callback, and that contains a payloadwith the actual event that was performed.
  • 34.
    Next, start toimplement theHandleEventMessage , which will continuethe type switching. We can use the typefield to know how to handle the Event. Thenwe can reach the payload event by using theInnerEvent field.func HandleEventMessage(eventslackevents.EventsAPIEvent, client*slack.Client) error {switch event.Type {case slackevents.CallbackEvent:innerEvent := event.InnerEventswitch evnt := innerEvent.Data.(type) {err :=HandleAppMentionEventToBot(evnt,
  • 35.
    if err !=nil {return err}}default:return errors.New("unsupported eventtype")}return nil}Replace the previous log in the mainfunction that prints the event with the newHandleEventMessage function.
  • 36.
    log.Println(eventsAPI)replace witherr :=HandleEventMessage(eventsAPI,client)if err != nil {log.Fatal(err)}We need to make the bot respond to theuser who mentioned it.Next start with logging into the applicationand adding the users:read scope to the bottoken, as we did earlier. After adding thescope to the token, we will create theHandleAppMentionEventToBot
  • 37.
    This function willtake a*slackevents.AppMentionEvent and aslack.Client as input so it can respond.The event contains the user ID in theevent.User with which we can fetch userdetails. The channel response is alsoavailable during the event.Channel. Thedata we need is the actual message the usersent while mentioning, which we can fetchfrom the event.Text.funcHandleAppMentionEventToBot(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 amgood. 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 postmessage: %w", err)}return nil}Now restart the program and say hello or hiand say something else to see whether itworks as expected. You have missed somescope if you get a “missing_scope” error.
  • 41.
  • 42.
    Here is theoutput of my currently runninga bot
  • 43.
  • 44.
    If you wantto visit the source code, pleaseclone the repository and set up theproject on your system. You can tryplaying around with the demo applicationand explore more.Here’s the github repository: slack-bot-using-golang-example
  • 45.
    ConclusionI hope thepurpose of this tutorial: How toDevelop Slack Bot using Golang is servedas expected. This is a basic step-by-stepguide to get you started withimplementing slack bot with the go-slackpackage. Write us back if you have anyquestions, suggestions, or feedback. Feelfree to clone the repository and playaround with the code.

[8]ページ先頭

©2009-2025 Movatter.jp