### Example Commit Message Format Source: https://github.com/slack-io/slacker/blob/main/CONTRIBUTING.md This example demonstrates the recommended format for commit messages in Slacker. It includes a type prefix (e.g., 'feat'), a concise subject line, a detailed body explaining the change, and a reference to closed issues. ```markdown feat: Add support for a custom command channel size Create an additional functional option `WithCommandChanSize(int)` that may be passed into `NewClient(...)` that lets the user specify the size of the channel used to hold incoming commands to be processed. This may be useful to expand for high-volume bots. Closes #319 ``` -------------------------------- ### Use Command Groups in Slacker Go Source: https://context7.com/slack-io/slacker/llms.txt Demonstrates how to organize Slack bot commands into groups using the slacker library in Go. This example shows creating an 'admin' command group, applying middleware to all commands within that group (e.g., logging), and adding commands that are automatically prefixed with the group name. ```go package main import ( "context" "log" "os" "github.com/slack-io/slacker" ) func main() { bot := slacker.NewClient(os.Getenv("SLACK_BOT_TOKEN"), os.Getenv("SLACK_APP_TOKEN")) // Create admin command group with prefix adminGroup := bot.AddCommandGroup("admin") // Add middleware that applies to all commands in group adminGroup.AddCommandMiddleware(loggingMiddleware()) // Commands in group automatically get "admin" prefix adminGroup.AddCommand(&slacker.CommandDefinition{ Command: "restart", Description: "Restart the service", Handler: func(ctx *slacker.CommandContext) { ctx.Response().Reply("Service restarting...") }, }) adminGroup.AddCommand(&slacker.CommandDefinition{ Command: "status", Description: "Check service status", Handler: func(ctx *slacker.CommandContext) { ctx.Response().Reply("Service is running") }, }) ctx, cancel := context.WithCancel(context.Background()) defer cancel() err := bot.Listen(ctx) if err != nil { log.Fatal(err) } } func loggingMiddleware() slacker.CommandMiddlewareHandler { return func(next slacker.CommandHandler) slacker.CommandHandler { return func(ctx *slacker.CommandContext) { log.Printf("Command executed by %s", ctx.Event().UserProfile.DisplayName) next(ctx) } } } ``` -------------------------------- ### Schedule Cron Jobs with Slacker Go Source: https://context7.com/slack-io/slacker/llms.txt Demonstrates how to schedule recurring tasks (cron jobs) in a Slack bot using the slacker library. It shows examples of jobs that run every minute and daily at a specific time. Cron expressions follow the standard format: minute, hour, day, month, weekday. ```go package main import ( "context" "log" "os" "github.com/slack-io/slacker" ) func main() { bot := slacker.NewClient(os.Getenv("SLACK_BOT_TOKEN"), os.Getenv("SLACK_APP_TOKEN")) bot.AddCommand(&slacker.CommandDefinition{ Command: "ping", Handler: func(ctx *slacker.CommandContext) { ctx.Response().Reply("pong") }, }) // Cron job that runs every minute // Format: minute hour day month weekday // ┌───────────── minute (0 - 59) // │ ┌───────────── hour (0 - 23) // │ │ ┌───────────── day of the month (1 - 31) // │ │ │ ┌───────────── month (1 - 12) // │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday) bot.AddJob(&slacker.JobDefinition{ CronExpression: "*/1 * * * *", Name: "MinutelyGreeting", Description: "Posts a greeting every minute", Handler: func(ctx *slacker.JobContext) { ctx.Response().Post("#test", "Hello from scheduled job!") }, }) // Job that runs every day at 9 AM bot.AddJob(&slacker.JobDefinition{ CronExpression: "0 9 * * *", Name: "DailyReport", Description: "Daily morning report", Handler: func(ctx *slacker.JobContext) { ctx.Response().Post("#general", "Good morning! Here's your daily report.") }, }) ctx, cancel := context.WithCancel(context.Background()) defer cancel() err := bot.Listen(ctx) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Create Basic Slack Bot with Slacker Source: https://context7.com/slack-io/slacker/llms.txt Demonstrates how to initialize a Slacker bot client with environment variables for tokens and add a simple 'ping' command that replies with 'pong'. It uses context for graceful shutdown and listens for incoming events. ```go package main import ( "context" "log" "os" "github.com/slack-io/slacker" ) func main() { // Initialize bot with Bot Token and App Token from environment bot := slacker.NewClient(os.Getenv("SLACK_BOT_TOKEN"), os.Getenv("SLACK_APP_TOKEN")) // Add a simple command that responds to "ping" bot.AddCommand(&slacker.CommandDefinition{ Command: "ping", Handler: func(ctx *slacker.CommandContext) { ctx.Response().Reply("pong") }, }) // Create cancellable context ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Start listening for events (blocking call) err := bot.Listen(ctx) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Configure Slacker Bot Options Go Source: https://context7.com/slack-io/slacker/llms.txt Illustrates how to configure a Slack bot using slacker with custom options. This includes enabling debug logging, ignoring messages from the app itself, and setting the timezone for cron jobs. It also shows how to define a handler for unsupported commands and connection lifecycle events. ```go package main import ( "context" "log" "os" "time" "github.com/slack-io/slacker" ) func main() { // Create bot with custom options bot := slacker.NewClient( os.Getenv("SLACK_BOT_TOKEN"), os.Getenv("SLACK_APP_TOKEN"), slacker.WithDebug(true), // Enable debug logging slacker.WithBotMode(slacker.BotModeIgnoreApp), // Ignore messages from this app slacker.WithCronLocation(time.UTC), // Set timezone for cron jobs ) bot.AddCommand(&slacker.CommandDefinition{ Command: "ping", Handler: func(ctx *slacker.CommandContext) { ctx.Response().Reply("pong") }, }) // Custom handler for unsupported commands bot.UnsupportedCommandHandler(func(ctx *slacker.CommandContext) { ctx.Response().Reply("I don't understand that command. Type 'help' for available commands.") }) // Connection lifecycle handlers bot.OnConnected(func(event socketmode.Event) { log.Println("Bot connected to Slack") }) bot.OnDisconnected(func(event socketmode.Event) { log.Println("Bot disconnected from Slack") }) ctx, cancel := context.WithCancel(context.Background()) defer cancel() err := bot.Listen(ctx) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Slacker Commands with Parameter Extraction Source: https://context7.com/slack-io/slacker/llms.txt Illustrates how to define Slacker commands that accept various types of parameters. It shows single-word, greedy sentence, and multiple typed parameters with default values, demonstrating robust command parsing capabilities. ```go package main import ( "context" "log" "os" "github.com/slack-io/slacker" ) func main() { bot := slacker.NewClient(os.Getenv("SLACK_BOT_TOKEN"), os.Getenv("SLACK_APP_TOKEN")) // Single word parameter using {word} syntax bot.AddCommand(&slacker.CommandDefinition{ Command: "echo {word}", Description: "Echo a word!", Examples: []string{"echo hello"}, Handler: func(ctx *slacker.CommandContext) { word := ctx.Request().Param("word") ctx.Response().Reply(word) }, }) // Greedy parameter using syntax - captures everything bot.AddCommand(&slacker.CommandDefinition{ Command: "say ", Description: "Say a sentence!", Examples: []string{"say hello there everyone!"}, Handler: func(ctx *slacker.CommandContext) { sentence := ctx.Request().Param("sentence") ctx.Response().Reply(sentence) }, }) // Multiple typed parameters with default values bot.AddCommand(&slacker.CommandDefinition{ Command: "repeat {word} {number}", Description: "Repeat a word a number of times!", Examples: []string{"repeat hello 10"}, Handler: func(ctx *slacker.CommandContext) { word := ctx.Request().StringParam("word", "Hello!") number := ctx.Request().IntegerParam("number", 1) for i := 0; i < number; i++ { ctx.Response().Reply(word) } }, }) ctx, cancel := context.WithCancel(context.Background()) defer cancel() err := bot.Listen(ctx) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Go: Advanced Slack Bot Response Options with Slacker Source: https://context7.com/slack-io/slacker/llms.txt Demonstrates advanced response capabilities in a Slack bot using the Slacker library in Go. This includes replying in threads, sending ephemeral messages, scheduling future messages, using attachments for rich formatting, posting to specific channels, and deleting messages. It requires the `github.com/slack-go/slack` and `github.com/slack-io/slacker` Go modules. ```go package main import ( "context" "log" "os" "time" "strconv" "github.com/slack-go/slack" "github.com/slack-io/slacker" ) func main() { bot := slacker.NewClient(os.Getenv("SLACK_BOT_TOKEN"), os.Getenv("SLACK_APP_TOKEN")) bot.AddCommand(&slacker.CommandDefinition{ Command: "demo ", Description: "Demonstrate various response options", Handler: func(ctx *slacker.CommandContext) { message := ctx.Request().Param("message") // Reply in thread ctx.Response().Reply("This is a threaded reply", slacker.WithInThread(true)) // Send ephemeral message (only visible to user) ctx.Response().Reply("This is private", slacker.WithEphemeral()) // Schedule message for later (24 hours from now) scheduleTime := time.Now().Add(24 * time.Hour) ctx.Response().Reply("Scheduled message", slacker.WithSchedule(scheduleTime)) // Reply with attachments attachments := []slack.Attachment{ { Color: "#36a64f", Title: "Message Title", Text: message, FooterIcon: "https://platform.slack-edge.com/img/default_application_icon.png", Footer: "Slacker Bot", Ts: json.Number(strconv.FormatInt(time.Now().Unix(), 10)), }, } ctx.Response().Reply("", slacker.WithAttachments(attachments)) // Post to specific channel (not as reply) ctx.Response().Post("#general", "Posted to general channel") // Delete a message ctx.Response().Delete(ctx.Event().ChannelID, ctx.Event().TimeStamp) }, }) ctx, cancel := context.WithCancel(context.Background()) defer cancel() err := bot.Listen(ctx) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Go: Create Interactive Messages with Buttons for Slack Source: https://context7.com/slack-io/slacker/llms.txt This Go code demonstrates how to create interactive messages with buttons in Slack using the slacker and slack libraries. A command 'mood' is defined to display a message with 'Happy' and 'Sad' buttons. An interaction handler then processes the button clicks and replies with a corresponding message, replacing the original interactive message. ```go package main import ( "context" "log" "os" "github.com/slack-go/slack" "github.com/slack-io/slacker" ) func main() { bot := slacker.NewClient(os.Getenv("SLACK_BOT_TOKEN"), os.Getenv("SLACK_APP_TOKEN")) // Command that displays interactive buttons bot.AddCommand(&slacker.CommandDefinition{ Command: "mood", Handler: func(ctx *slacker.CommandContext) { happyBtn := slack.NewButtonBlockElement( "happy", "true", slack.NewTextBlockObject("plain_text", "Happy 🙂", true, false), ) happyBtn.Style = slack.StylePrimary sadBtn := slack.NewButtonBlockElement( "sad", "false", slack.NewTextBlockObject("plain_text", "Sad ☹️", true, false), ) sadBtn.Style = slack.StyleDanger ctx.Response().ReplyBlocks([]slack.Block{ slack.NewSectionBlock( slack.NewTextBlockObject(slack.PlainTextType, "What is your mood today?", true, false), nil, nil, ), slack.NewActionBlock("mood", happyBtn, sadBtn), }) }, }) // Interaction handler for button clicks bot.AddInteraction(&slacker.InteractionDefinition{ InteractionID: "mood", Type: slack.InteractionTypeBlockActions, Handler: func(ctx *slacker.InteractionContext) { text := "" action := ctx.Callback().ActionCallback.BlockActions[0] switch action.ActionID { case "happy": text = "I'm happy to hear you are happy!" case "sad": text = "I'm sorry to hear you are sad." default: text = "I don't understand your mood..." } // Replace original message with response ctx.Response().Reply(text, slacker.WithReplace(ctx.Callback().Message.Timestamp)) }, }) ctx, cancel := context.WithCancel(context.Background()) defer cancel() err := bot.Listen(ctx) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Go: Accessing Slack API Directly with Slacker Source: https://context7.com/slack-io/slacker/llms.txt Shows how to access the underlying Slack API client directly within a Slacker bot handler in Go. This allows for the use of any Slack API method, such as retrieving user information. It requires the `github.com/slack-io/slacker` Go module. ```go package main import ( "context" "log" "os" "github.com/slack-io/slacker" ) func main() { bot := slacker.NewClient(os.Getenv("SLACK_BOT_TOKEN"), os.Getenv("SLACK_APP_TOKEN")) bot.AddCommand(&slacker.CommandDefinition{ Command: "userinfo {username}", Description: "Get user information", Handler: func(ctx *slacker.CommandContext) { username := ctx.Request().Param("username") // Access underlying Slack API client client := ctx.SlackClient() // Use any Slack API method users, err := client.GetUsers() if err != nil { ctx.Response().ReplyError(err) return } for _, user := range users { if user.Name == username { ctx.Response().Reply("User found: " + user.RealName) return } } ctx.Response().Reply("User not found") }, }) ctx, cancel := context.WithCancel(context.Background()) defer cancel() err := bot.Listen(ctx) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Go: Implement Authorization Middleware for Slack Commands Source: https://context7.com/slack-io/slacker/llms.txt This Go code demonstrates how to implement authorization middleware for Slack commands using the slacker library. It checks if a user's display name is in a list of authorized users before allowing them to execute a command. The middleware function `authorizationMiddleware` takes a handler and returns a new handler that performs the authorization check. ```go package main import ( "context" "log" "os" "github.com/slack-io/slacker" ) var authorizedUserNames = []string{"admin", "developer"} func main() { bot := slacker.NewClient(os.Getenv("SLACK_BOT_TOKEN"), os.Getenv("SLACK_APP_TOKEN")) // Command with middleware for authorization bot.AddCommand(&slacker.CommandDefinition{ Command: "secret", Description: "Very secret stuff", Examples: []string{"secret"}, Middlewares: []slacker.CommandMiddlewareHandler{authorizationMiddleware()}, Handler: func(ctx *slacker.CommandContext) { ctx.Response().Reply("You are authorized!") }, }) ctx, cancel := context.WithCancel(context.Background()) defer cancel() err := bot.Listen(ctx) if err != nil { log.Fatal(err) } } // Authorization middleware checks user permissions func authorizationMiddleware() slacker.CommandMiddlewareHandler { return func(next slacker.CommandHandler) slacker.CommandHandler { return func(ctx *slacker.CommandContext) { userName := ctx.Event().UserProfile.DisplayName if contains(authorizedUserNames, userName) { next(ctx) // User authorized, proceed to handler } else { ctx.Response().Reply("Unauthorized access denied") } } } } func contains(list []string, element string) bool { for _, value := range list { if value == element { return true } } return false } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.