socketmode

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 20, 2023 License: MIT Imports: 9 Imported by: 0

README

slack-socketmode

Go Reference

Client and Router for Slack's Socketmode

Introduction

slack-socketmode provides a client and router that interact with Slack in socketmode. It makes use of the community supported slack api client in the slack-go/slack repo. This was mostly driven out of the desire to have middleware support for the router.

Quick Start

Below is a quick example of using the client and router.

package main

import (
	"context"
	"fmt"

	"github.com/mimikwang/slack-socketmode/router"
	"github.com/mimikwang/slack-socketmode/socket"
	"github.com/slack-go/slack"
)

const (
	appToken = "YOUR_APP_TOKEN"
	botToken = "YOUR_BOT_TOKEN"
)

func main() {
    // Set up Client
	api := slack.New(botToken, slack.OptionAppLevelToken(appToken))
	client := socket.New(api, socket.OptDebugReconnects{})

    // Set up Router
	r := router.New(client)
	r.Use(dummyMiddleware)
	r.Handle("hello", dummyHandler)

    // Start
	if err := r.Start(context.Background()); err != nil {
		panic(err)
	}
}

func dummyMiddleware(next router.Handler) router.Handler {
	return func(evt *socket.Event, clt *socket.Client) {
		fmt.Println("Stuck in the Middle")
		next(evt, clt)
	}
}

func dummyHandler(evt *socket.Event, clt *socket.Client) {
	fmt.Println("With You")
	clt.Ack(&evt.Request, nil)
}

Documentation

Index

Constants

View Source
const (
	RequestTypeDisconnect    = "disconnect"
	RequestTypeHello         = "hello"
	RequestTypeEventsAPI     = "events_api"
	RequestTypeInteractive   = "interactive"
	RequestTypeSlashCommands = "slash_commands"
)

Variables

View Source
var (
	ErrPingTimeout           = fmt.Errorf("timeout waiting for pings from Slack")
	ErrDisconnectRequest     = fmt.Errorf("received disconnected request from Slack")
	ErrNilRequest            = fmt.Errorf("received nil request")
	ErrUnexpectedRequestType = fmt.Errorf("unexpected Request type")
	ErrConnClosed            = fmt.Errorf("websocket connection is closed")
)

Functions

This section is empty.

Types

type Client

type Client struct {
	// Slack's API Client
	Api *slack.Client
	// contains filtered or unexported fields
}

Client interacts with Slack in socketmode.

func NewClient

func NewClient(api *slack.Client, opts ...clientOpt) *Client

New creates a new socketmode client given a slack api client

func (*Client) Ack

func (c *Client) Ack(evt *Event, payload any) error

Ack sends an acknowledge response to slack. This can be called concurrently.

func (*Client) Close

func (c *Client) Close() error

Close cleans up resources

func (*Client) Read

func (c *Client) Read() (*Event, error)

Read returns the incoming event. This is the external API for accessing events. This function is concurrency safe.

func (*Client) Start

func (c *Client) Start(ctx context.Context) error

Start starts the client. It contains logic for retries.

type ClientOptDebugReconnects added in v0.1.3

type ClientOptDebugReconnects struct{}

ClientOptDebugReconnects sets the `debugReconnects` flag to true

type ClientOptDialerTimeout added in v0.1.3

type ClientOptDialerTimeout struct {
	Timeout time.Duration
}

ClientOptDialerTimeout sets the timeout duration for the websocket dialer. 0 or negative durations are ignored.

type ClientOptLogLevel added in v0.1.3

type ClientOptLogLevel struct {
	Level slog.Level
}

ClientOptLogLevel sets the log level. Level should be of type `slog.Level`.

type ClientOptMaxRetries added in v0.1.3

type ClientOptMaxRetries struct {
	MaxRetries int
}

ClientOptMaxRetries sets the number of times to retry connecting to Slack before giving up. 0 or negative numbers are ignored.

type ClientOptPingTimeout added in v0.1.3

type ClientOptPingTimeout struct {
	Timeout time.Duration
}

ClientOptPingTimeout sets the maximum duration between pings from Slack before timing out. 0 or negative durations are ignored.

type ClientOptRetryWaitTime added in v0.1.3

type ClientOptRetryWaitTime struct {
	WaitTime time.Duration
}

ClientOptRetryWaitTime sets the duration between retries. 0 or negative durations are ignored.

type ConnectionInfo

type ConnectionInfo struct {
	AppId string `json:"app_id"`
}

ConnectionInfo is the `connection_info` portion of the incoming Request from Slack

type DebugInfo

type DebugInfo struct {
	Host                      string `json:"host"`
	BuildNumber               int    `json:"build_number"`
	ApproximateConnectionTime int    `json:"approximate_connection_time"`
}

DebugInfo is the `debug_info` portion of the incoming Request from Slack

type Event

type Event struct {
	Request Request
	Payload any
	Context context.Context
	// contains filtered or unexported fields
}

Event contains the original request from Slack as well as the appropriately typed payload. It also contains a cancellable context that allows the enforcement that each Event be acknowledged at most once.

type Handler

type Handler func(evt *Event, clt *Client)

Handler handles incoming events

type Middleware

type Middleware func(Handler) Handler

Middleware modifies a handler

type OptDebugReconnects

type OptDebugReconnects struct{}

OptDebugReconnects sets the `debugReconnects` flag to true.

type OptLogLevel

type OptLogLevel struct {
	Level slog.Level
}

OptLogLevel sets the log level

type Request

type Request struct {
	Type            RequestType     `json:"type"`
	Reason          string          `json:"reason"`
	NumConnections  int             `json:"num_connections"`
	DebugInfo       DebugInfo       `json:"debug_info"`
	ConnectionInfo  ConnectionInfo  `json:"connection_info"`
	EnvelopeId      string          `json:"envelope_id"`
	Payload         json.RawMessage `json:"payload"`
	ResponsePayload bool            `json:"response_paload"`
	RetryAttempt    int             `json:"retry_attempt"`
	RetryReason     string          `json:"retry_reason"`
}

Request is the incoming request from slack

type RequestType

type RequestType string

type Response

type Response struct {
	EnvelopeId string          `json:"envelope_id"`
	Payload    json.RawMessage `json:"payload"`
}

Response is what slack expects as a response. It should be called with `Ack` once.

type Router

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

Router routes incoming requests from slack

func NewRouter

func NewRouter(clt *Client) *Router

NewRouter constructs a Router given a socketmode Client

func (*Router) Close

func (r *Router) Close() error

Close cleans up resources

func (*Router) Handle

func (r *Router) Handle(requestType RequestType, handler Handler, m ...Middleware)

Handle registers generic handlers

func (*Router) HandleBlockAction added in v0.1.3

func (r *Router) HandleBlockAction(actionId string, handler Handler, m ...Middleware)

HandleBlockAction registers block actions handlers

func (*Router) HandleEventsApi

func (r *Router) HandleEventsApi(eventType slackevents.EventsAPIType, handler Handler, m ...Middleware)

HandleEventsApi registers events api handlers

func (*Router) HandleInteractive added in v0.1.3

func (r *Router) HandleInteractive(interactionType slack.InteractionType, handler Handler, m ...Middleware)

HandleInteractive registers interactive handlers

func (*Router) HandleShortcut added in v0.1.3

func (r *Router) HandleShortcut(callbackId string, handler Handler, m ...Middleware)

HandleShortcut registers shortcuts handlers

func (*Router) HandleSlashCommand

func (r *Router) HandleSlashCommand(command string, handler Handler, m ...Middleware)

HandleSlashCommand registers slash command handlers

func (*Router) Start

func (r *Router) Start(ctx context.Context) error

Start listening to incoming requests

func (*Router) Use

func (r *Router) Use(m Middleware)

Use registers middlewares

type RouterOptParralel added in v0.1.3

type RouterOptParralel struct {
	Parralel int
}

RouterOptParralel sets the number of concurrent workers for the router. This is ignored if the number is 0 or negative.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL