socketmode

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2022 License: BSD-2-Clause Imports: 16 Imported by: 0

Documentation

Index

Constants

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

	// The following event types are for events emitted by socketmode.Client itself and
	// does not originate from Slack.
	EventTypeConnecting       = EventType("connecting")
	EventTypeInvalidAuth      = EventType("invalid_auth")
	EventTypeConnectionError  = EventType("connection_error")
	EventTypeConnected        = EventType("connected")
	EventTypeIncomingError    = EventType("incoming_error")
	EventTypeErrorWriteFailed = EventType("write_error")
	EventTypeErrorBadMessage  = EventType("error_bad_message")

	EventTypeHello        = EventType("hello")
	EventTypeDisconnect   = EventType("disconnect")
	EventTypeEventsAPI    = EventType("events_api")
	EventTypeInteractive  = EventType("interactive")
	EventTypeSlashCommand = EventType("slash_commands")
)

Variables

This section is empty.

Functions

func OptionDebug

func OptionDebug(b bool) func(*Client)

OptionDebug enable debugging for the client

func OptionLog

func OptionLog(l logger) func(*Client)

OptionLog set logging for client.

Types

type Client

type Client struct {
	// Client is the main API, embedded
	slack.Client

	// Connection life-cycle
	Events chan Event
	// contains filtered or unexported fields
}

Client is a Socket Mode client that allows programs to use [Events API](https://api.slack.com/events-api) and [interactive components](https://api.slack.com/interactivity) over WebSocket. Please see [Intro to Socket Mode](https://api.slack.com/apis/connections/socket) for more information on Socket Mode.

The implementation is highly inspired by https://www.npmjs.com/package/@slack/socket-mode, but the structure and the design has been adapted as much as possible to that of our RTM client for consistency within the library.

You can instantiate the socket mode client with Client's New() and call Run() to start it. Please see examples/socketmode for the usage.

func New

func New(api *slack.Client, options ...Option) *Client

New returns a Socket Mode client which provides a fully managed connection to Slack's Websocket-based Socket Mode.

func (*Client) Ack

func (smc *Client) Ack(req Request, payload ...interface{})

Ack acknowledges the Socket Mode request with the payload.

This tells Slack that the we have received the request denoted by the envelope ID, by sending back the envelope ID over the WebSocket connection.

func (*Client) Debugf

func (smc *Client) Debugf(format string, v ...interface{})

func (*Client) Debugln

func (smc *Client) Debugln(v ...interface{})

func (*Client) Open

func (smc *Client) Open() (info *slack.SocketModeConnection, websocketURL string, err error)

Open calls the "apps.connections.open" endpoint and returns the provided URL and the full Info block.

To have a fully managed Websocket connection, use `New`, and call `Run()` on it.

func (*Client) OpenContext

func (smc *Client) OpenContext(ctx context.Context) (info *slack.SocketModeConnection, websocketURL string, err error)

OpenContext calls the "apps.connections.open" endpoint and returns the provided URL and the full Info block.

To have a fully managed Websocket connection, use `New`, and call `Run()` on it.

func (*Client) Run

func (smc *Client) Run() error

Run is a blocking function that connects the Slack Socket Mode API and handles all incoming requests and outgoing responses.

The consumer of the Client and this function should read the Client.Events channel to receive `socketmode.Event`s that includes the client-specific events that may or may not wrap Socket Mode requests.

Note that this function automatically reconnect on requested by Slack through a `disconnect` message. This function exists with an error only when a reconnection is failued due to some reason. If you want to retry even on reconnection failure, you'd need to write your own wrapper for this function to do so.

func (*Client) RunContext

func (smc *Client) RunContext(ctx context.Context) error

RunContext is a blocking function that connects the Slack Socket Mode API and handles all incoming requests and outgoing responses.

The consumer of the Client and this function should read the Client.Events channel to receive `socketmode.Event`s that includes the client-specific events that may or may not wrap Socket Mode requests.

Note that this function automatically reconnect on requested by Slack through a `disconnect` message. This function exists with an error only when a reconnection is failued due to some reason. If you want to retry even on reconnection failure, you'd need to write your own wrapper for this function to do so.

func (*Client) Send

func (smc *Client) Send(res Response)

Send sends the Socket Mode response over a WebSocket connection. This is usually used for acknowledging requests, but if you need more control over Client.Ack(). It's normally recommended to use Client.Ack() instead of this.

type ConnectedEvent

type ConnectedEvent struct {
	ConnectionCount int // 1 = first time, 2 = second time
	Info            *slack.SocketModeConnection
}

type ConnectionInfo

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

type DebugInfo

type DebugInfo struct {
	// Host is the name of the host name on the Slack end, that can be something like `applink-7fc4fdbb64-4x5xq`
	Host string `json:"host"`

	// `hello` type only
	BuildNumber               int `json:"build_number"`
	ApproximateConnectionTime int `json:"approximate_connection_time"`
}

type ErrorBadMessage

type ErrorBadMessage struct {
	Cause   error
	Message json.RawMessage
}

type ErrorWriteFailed

type ErrorWriteFailed struct {
	Cause    error
	Response *Response
}

type Event

type Event struct {
	Type EventType
	Data interface{}

	// Request is the json-decoded raw WebSocket message that is received via the Slack Socket Mode
	// WebSocket connection.
	Request *Request
}

Event is the event sent to the consumer of Client

type EventType

type EventType string

EventType is the type of events that are emitted by scoketmode.Client. You receive and handle those events from a socketmode.Client.Events channel. Those event types does not necessarily match 1:1 to those of Slack Events API events.

type Option

type Option func(client *Client)

Option options for the managed Client.

func OptionDialer

func OptionDialer(d *websocket.Dialer) Option

OptionDialer takes a gorilla websocket Dialer and uses it as the Dialer when opening the websocket for the Socket Mode connection.

func OptionPingInterval

func OptionPingInterval(d time.Duration) Option

OptionPingInterval determines how often we expect Slack to deliver WebSocket ping to us. If no ping is delivered to us within this interval after the last ping, we assumes the WebSocket connection is dead and needs to be reconnected.

type Request

type Request struct {
	Type string `json:"type"`

	// `hello` type only
	NumConnections int            `json:"num_connections"`
	ConnectionInfo ConnectionInfo `json:"connection_info"`

	// Reason can be "warning" or else
	Reason string `json:"reason"`

	// `hello` and `disconnect` types only
	DebugInfo DebugInfo `json:"debug_info"`

	// `events_api` type only
	EnvelopeID string `json:"envelope_id"`
	// TODO Can it really be a non-object type?
	// See https://github.com/slackapi/python-slack-sdk/blob/3f1c4c6e27bf7ee8af57699b2543e6eb7848bcf9/slack_sdk/socket_mode/request.py#L26-L31
	Payload                json.RawMessage `json:"payload"`
	AcceptsResponsePayload bool            `json:"accepts_response_payload"`
	RetryAttempt           int             `json:"retry_attempt"`
	RetryReason            string          `json:"retry_reason"`
}

Request maps to the content of each WebSocket message received via a Socket Mode WebSocket connection

We call this a "request" rather than e.g. a WebSocket message or an Socket Mode "event" following python-slack-sdk:

https://github.com/slackapi/python-slack-sdk/blob/3f1c4c6e27bf7ee8af57699b2543e6eb7848bcf9/slack_sdk/socket_mode/request.py#L6

We know that node-slack-sdk calls it an "event", that makes it hard for us to distinguish our client's own event that wraps both internal events and Socket Mode "events", vs node-slack-sdk's is for the latter only.

https://github.com/slackapi/node-slack-sdk/blob/main/packages/socket-mode/src/SocketModeClient.ts#L537

type Response

type Response struct {
	EnvelopeID string      `json:"envelope_id"`
	Payload    interface{} `json:"payload,omitempty"`
}

type SocketModeMessagePayload

type SocketModeMessagePayload struct {
	Event json.RawMessage `json:"event"`
}

type SocketmodeHandler

type SocketmodeHandler struct {
	Client *Client

	//lvl 1 - the most generic type of event
	EventMap map[EventType][]SocketmodeHandlerFunc
	//lvl 2 - Manage event by inner type
	InteractionEventMap map[slack.InteractionType][]SocketmodeHandlerFunc
	EventApiMap         map[slackevents.EventsAPIType][]SocketmodeHandlerFunc
	//lvl 3 - the most userfriendly way of managing event
	InteractionBlockActionEventMap map[string]SocketmodeHandlerFunc
	SlashCommandMap                map[string]SocketmodeHandlerFunc

	Default SocketmodeHandlerFunc
}

func NewSocketmodeHandler

func NewSocketmodeHandler(client *Client) *SocketmodeHandler

Initialization constructor for SocketmodeHandler

func (*SocketmodeHandler) Handle

Register a middleware or handler for an Event from socketmode This most general entrypoint

func (*SocketmodeHandler) HandleDefault

func (r *SocketmodeHandler) HandleDefault(f SocketmodeHandlerFunc)

Register a middleware or handler to use as a last resort

func (*SocketmodeHandler) HandleEvents

Register a middleware or handler for an Event (from slackevents)

func (*SocketmodeHandler) HandleInteraction

func (r *SocketmodeHandler) HandleInteraction(et slack.InteractionType, f SocketmodeHandlerFunc)

Register a middleware or handler for an Interaction There is several types of interactions, decated functions lets you better handle them See * HandleInteractionBlockAction * (Not Implemented) HandleShortcut * (Not Implemented) HandleView

func (*SocketmodeHandler) HandleInteractionBlockAction

func (r *SocketmodeHandler) HandleInteractionBlockAction(actionID string, f SocketmodeHandlerFunc)

Register a middleware or handler for a Block Action referenced by its ActionID

func (*SocketmodeHandler) HandleSlashCommand

func (r *SocketmodeHandler) HandleSlashCommand(command string, f SocketmodeHandlerFunc)

Register a middleware or handler for a Slash Command

func (*SocketmodeHandler) RunEventLoop

func (r *SocketmodeHandler) RunEventLoop() error

RunSlackEventLoop receives the event via the socket

type SocketmodeHandlerFunc

type SocketmodeHandlerFunc func(*Event, *Client)

Handler have access to the event and socketmode client

type SocketmodeMiddlewareFunc

type SocketmodeMiddlewareFunc func(SocketmodeHandlerFunc) SocketmodeHandlerFunc

Middleware accept SocketmodeHandlerFunc, and return SocketmodeHandlerFunc

Jump to

Keyboard shortcuts

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