README

Slash

A router for Slack's slash commands.

Preparations

  1. Go to Slack's overview of Your Apps and create a new App.
  2. Under Add features and functionality, select Slash Commands (or go to Slash Commands under Features in the sidebar).
    Register the slash command(s) that you're building. You can use the same Request URL for all of them. The URL of the example below ends with /slash.
  3. Under Install your app to your workspace click the button to Install App to Workspace (or go to Install App in the sidebar).
  4. Go back to Basic Information and find the Signing Secret in the App Credentials section.
    This is what you'll need for the SLACK_SIGNING_SECRET environment variable later.

Usage

  1. Import the package:
    import "htdvisser.dev/slash"
    
  2. Create a new Router:
    r := slash.NewRouter(os.Getenv("SLACK_SIGNING_SECRET"))
    
  3. Register a slash commands, for example /ping:
    r.RegisterCommand("/ping", func(ctx context.Context, req slash.Request) interface{} {
            // ...
    })
    
  4. Register the router to your ServeMux:
    http.Handle("/slash", r)
    

See the example on Godoc for more.

Next Steps

  • Go build something cool and showcase it on the wiki.

Documentation

Overview

Package slash implements a simple router for Slack's slash commands.

Example
package main

import (
	"context"
	"fmt"
	"math/rand"
	"net/http"
	"os"
	"strconv"

	"htdvisser.dev/slash"
)

func main() {
	// This is an extremely simple response to a slash command.
	// You'll want to add "blocks" for more advanced responses.
	// See also https://api.slack.com/messaging/composing/layouts.
	type response struct {
		ResponseType string `json:"response_type"`
		Text         string `json:"text"`
	}

	// We set up the slash command router with the Signing secret we got from Slack.
	r := slash.NewRouter(os.Getenv("SLACK_SIGNING_SECRET"))

	// We register the /pseudorandom command that generates a pseudorandom number for the user.
	r.RegisterCommand("/pseudorandom", func(ctx context.Context, req slash.Request) interface{} {
		n := 10
		if req.Text() != "" {
			var err error
			n, err = strconv.Atoi(req.Text())
			if err != nil {
				// We send a response to the user to inform them about errors.
				return response{
					ResponseType: "ephemeral",
					Text:         "Please give me a number",
				}
			}
		}
		if n <= 1 {
			return response{
				ResponseType: "ephemeral",
				Text:         "Please give me a number _larger than one_",
			}
		}
		return response{
			ResponseType: "in_channel",
			Text:         fmt.Sprintf("%s got %d", req.UserName(), rand.Intn(n)),
		}
	})

	http.Handle("/slash", r)
	http.ListenAndServe(":8080", nil)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type HandlerFunc

type HandlerFunc func(ctx context.Context, req Request) interface{}

HandlerFunc is a function that handles a slash command.

type Logger

type Logger interface {
	Print(v ...interface{})
	Printf(format string, v ...interface{})
}

Logger is the logger interface used by the slash command Router.

type MiddlewareFunc

type MiddlewareFunc func(next HandlerFunc) HandlerFunc

MiddlewareFunc is a function that can be used as middleware in slash command handling.

type Request

type Request url.Values

Request is the request message for a slash command.

func (Request) ChannelID

func (r Request) ChannelID() string

ChannelID returns the `channel_id` field from the slash request.

func (Request) ChannelName

func (r Request) ChannelName() string

ChannelName returns the `channel_name` field from the slash request.

func (Request) Command

func (r Request) Command() string

Command returns the `command` field from the slash request.

func (Request) EnterpriseID

func (r Request) EnterpriseID() string

EnterpriseID returns the `enterprise_id` field from the slash request.

func (Request) EnterpriseName

func (r Request) EnterpriseName() string

EnterpriseName returns the `enterprise_name` field from the slash request.

func (Request) ResponseURL

func (r Request) ResponseURL() string

ResponseURL returns the `response_url` field from the slash request.

func (Request) TeamDomain

func (r Request) TeamDomain() string

TeamDomain returns the `team_domain` field from the slash request.

func (Request) TeamID

func (r Request) TeamID() string

TeamID returns the `team_id` field from the slash request.

func (Request) Text

func (r Request) Text() string

Text returns the `text` field from the slash request.

func (Request) Token

func (r Request) Token() string

Token returns the `token` field from the slash request.

func (Request) TriggerID

func (r Request) TriggerID() string

TriggerID returns the `trigger_id` field from the slash request.

func (Request) UserID

func (r Request) UserID() string

UserID returns the `user_id` field from the slash request.

func (Request) UserName

func (r Request) UserName() string

UserName returns the `user_name` field from the slash request.

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router routes slash commands to their handlers.

func NewRouter

func NewRouter(signingSecret string, opts ...RouterOption) *Router

NewRouter creates a new router for slash commands.

func (*Router) HandleCommand

func (sr *Router) HandleCommand(ctx context.Context, header http.Header, body []byte) (s int, h http.Header, b []byte, err error)

HandleCommand reads the command from the request header+body and returns a response.

func (*Router) RegisterCommand

func (sr *Router) RegisterCommand(command string, handler HandlerFunc)

RegisterCommand registers a slash command and its handler to the Router.

func (*Router) ServeHTTP

func (sr *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

type RouterOption

type RouterOption interface {
	// contains filtered or unexported methods
}

RouterOption sets options on the Router.

func WithCommandFailedHandler

func WithCommandFailedHandler(f HandlerFunc) RouterOption

WithCommandFailedHandler returns a RouterOption that sets the handler for failed commands.

func WithCommandUnknownHandler

func WithCommandUnknownHandler(f HandlerFunc) RouterOption

WithCommandUnknownHandler returns a RouterOption that sets the handler for unknown commands.

func WithLogger

func WithLogger(logger Logger) RouterOption

WithLogger returns a RouterOption that sets the logger.

func WithMiddleware

func WithMiddleware(f MiddlewareFunc) RouterOption

WithMiddleware returns a RouterOption that sets the middleware that will be called with the matched command handler.

func WithoutLogger

func WithoutLogger() RouterOption

WithoutLogger returns a RouterOption that disables logging.