Slack Node



The webhook allows you to customize the HTTP Agent used to create the connection to Slack. Using this option is the best way to make all requests from your app through a proxy, which is a common requirement in many corporate settings. Slack Interactive Messages for Node. The @slack/interactive-messages helps your app respond to interactions from Slack’s interactive messages, actions, and dialogs.This package will help you start with convenient and secure defaults. Installation $ npm install @slack/interactive-messages.

Edit on GitHub

Community Discussion

  • The GitHub issues list is the place for discussion of Node.js core features.
  • For real-time chat about Node.js development use one of the platforms below
    • For IRC, go to irc.freenode.net in the #node.js channel with an IRC client or connect in your web browser to the channel using freenode's WebChat.
    • For Slack, there are two options:
      • Node Slackers is a Node.js-focused Slack community. Some Working Groups have discussion channels there.
      • The OpenJSF Slack is a Foundation run Slack with several Node.js channels (channels prefixed by #nodejs- are related to the project). Some Working Groups have discussion channels there.
  • The official Node.js Twitter account is nodejs.
  • The Node.js Foundation calendar with all public team meetings.
  • Node.js Collection is a collection of community-curated content on Medium.
  • The Community Committee is a top-level committee in the Node.js Foundation focused on community-facing efforts.

Learning

  • Official API reference documentation details the Node.js API.
  • NodeSchool.io will teach you Node.js concepts via interactive command-line games.
  • Stack Overflow Node.js tag collects new information every day.
  • The DEV Community Node.js tag is a place to share Node.js projects, articles and tutorials as well as start discussions and ask for feedback on Node.js-related topics. Developers of all skill-levels are welcome to take part.
  • Nodeiflux is a friendly community of Node.js backend developers supporting each other on Discord.

International community sites and projects

The @slack/rtm-api package contains a simple, convenient, and configurable client for receiving events and sending simple messages to Slack’s Real Time Messaging API. Use it in yourapp to stay connected to the Slack platform over a persistent Websocket connection.

Note: RTM isn’t available for modern scoped apps anymore. We recommend using the Events API and Web API instead. If you need to use RTM (possibly due to corporate firewall limitations), you can do so by creating a legacy scoped app. If you have an existing RTM app, do not update its scopes as it will be updated to a modern scoped app and stop working with RTM.

Installation

Initialize the client

The package exports an RTMClient class. Your app will create an instance of the class for each workspace itcommunicates with. Creating an instance requires a token from Slack. Apps typically connect to the RTM API using a bottoken, which start with xoxb. These tokens are created for apps that have a Bot User, so to connect to the RTM API besure to add a Bot User in your app configuration page. Once the app is installed to the development workspace, you’llhave a bot token.

Connect to Slack

Data from Slack will begin to flow to your program once the client is connected. You’ll also be able to send data toSlack after the connection is established. Connecting is as easy as calling the .start() method. This method returns aPromise that resolves to the data returned from the rtm.connect Web APImethod.

It’s useful in many apps to keep information about the bot user who you’ve connected as, as well as the workspace you’veconnected to. That information has been destructured into the variables self and team above. If you only need theuser ID and team ID, you can look those up any time the client is connected as the rtm.activeUserId andrtm.activeTeamId properties. In fact, if you need to know whether the client is connected or not, you can check thertm.connected property.

Additional connection options

Options passed to the .start() method are passed through as arguments to the rtm.connect Web APImethod. These arguments deal with presence, which is discussed in moredetail on the documentation website.

Listen for an event

Apps register functions, called listeners, to be triggered when an event of a specific type is received by the client.If you’ve used Node’s EventEmitter patternbefore, then you’re already familiar with how this works, since the client is an EventEmitter.

The event argument passed to the listener is an object. It’s contents corresponds to the type ofevent its registered for.

Listen for message subtypes

The message event type has a special property called subtype to help organize all the messages inside Slack. Theclient has a convenient shorthand for listening to events of type message, but filtered to a specific subtype.The shorthand is to add the :: characters, followed by the name of the subtype, to the event type.

Send a message

Your app can send simple messages to Slack over the client’s connection. In this case, simple means that it cannotsend messages that include attachments or blocks, but it can include text, mentions, and links which unfurl.The client has a .sendMessage(text, conversationId) method for sending messages to Slack. That method returns aPromise which resolves once Slack has acknowledged the message with areply. The resolved value contains information about the sent message,such as the ts identifier. See error handling for details on how your app should deal with aPromise rejection.

Send rich messages using the WebClient

The Web API’s chat.postMessage method is capable of sending richmessages more advanced layout and interactions. These rich messagesare more attractive and useful for users of your app. Install and import the @slack/web-api package into your app,initialize the WebClient class, and use the .chat.postMessage(options) method to send a rich message. The exampleabove can be rewritten using the following code:

Send a typing indicator

Over the RTM API, your bot user can appear to be typing in Slack before it sends a message (“{Bot Display Name} istyping” is shown near the text input). The client has a .sendTyping(conversationId) method to allow your bot totrigger the typing indicator. The method returns a Promise that resolves when Slack has acknowledged the message. ThePromise doesn’t have a resolved value.

If you decide to use this method, make sure your bot follows up with an actual message. Otherwise, the bot user mayappear to be typing for a very long time.

Lifecycle events

The client’s connection to Slack has a lifecycle. This means the client can be seen as a state machine which transitionsthrough a few states as it connects, disconnects, reconnects, and synchronizes with Slack. The client emits an eventfor each state it transitions to throughout its lifecycle. If your app simply needs to know whether the client isconnected or not, the .connected boolean property can be checked.

In the table below, the client’s states are listed, which are also the names of the events you can use to observethe transition to that state. The table also includes description for the state, and arguments that a listener wouldreceive.

Event NameArgumentsDescription
connectingThe client is in the process of connecting to the platform.
authenticated(connectData) - the response from rtm.connect or rtm.startThe client has authenticated with the platform. This is a sub-state of connecting.
connectedThe client is connected to the platform and incoming events will start being emitted.
readyThe client is ready to send outgoing messages. This is a sub-state of connected
disconnectingThe client is no longer connected to the platform and cleaning up its resources. It will soon transition to disconnected.
reconnectingThe client is no longer connected to the platform and cleaning up its resources. It will soon transition to connecting.
disconnected(error)The client is not connected to the platform. This is a steady state - no attempt to connect is occurring. The error argument will be undefined when the client initiated the disconnect (normal).

The client also emits events that are part of its lifecycle, but aren’t states. Instead, they represent specificmoments that might be interesting to your app. The following table lists these events, their description, and includesthe arguments that a listener would receive.

Event NameArgumentsDescription
error(error)An error has occurred. See error handling for details.
slack_event(eventType, event)An incoming Slack event has been received.
unable_to_rtm_start(error)A problem occurred while connecting, a reconnect may or may not occur.

Handle errors

Errors can happen for many reasons: maybe the token isn’t valid, maybe you tried to send a message while the client isdisconnected, or maybe you just used a bad argument. In these cases, the returned Promise will reject with an Error.You should catch the error and use the information it contains to decide how your app can proceed.

Each error contains a code property, which you can check against the ErrorCode export to understand the kind oferror you’re dealing with. For example, when Slack responds to your app with an error, that is anErrorCode.SendMessagePlatformError. These types of errors provide Slack’s response body as the data property.

More error types

There are a few more types of errors that you might encounter, each with one of these codes:

  • ErrorCode.NoReplyReceivedError: A message was sent, but because either the connection was reset the there was noreply acknowledging it from the server. You may want to send this message again.
  • ErrorCode.SendWhileDisconnectedError: You’ve attempted to send a message while the client was not connected.
  • ErrorCode.SendWhileNotReadyError: You’ve attempted to send a message when the client was authenticated but not readyfor outgoing messages.
  • ErrorCode.WebsocketError: The Websocket transport underlying the connection has emitted an error.
Slack Node

Logging

The RTMClient will log interesting information to the console by default. You can use the logLevel to decide howmuch information, or how interesting the information needs to be, in order for it to be output. There are a few possiblelog levels, which you can find in the LogLevel export. By default, the value is set to LogLevel.INFO. While you’rein development, its sometimes helpful to set this to the most verbose: LogLevel.DEBUG.

All the log levels, in order of most to least information are: DEBUG, INFO, WARN, and ERROR.

Sending log output somewhere besides the console

You can also choose to have logs sent to a custom logger using the logger option. A custom logger needs to implementspecific methods (known as the Logger interface):

MethodParametersReturn type
setLevel()level: LogLevelvoid
setName()name: stringvoid
debug()...msgs: any[]void
info()...msgs: any[]void
warn()...msgs: any[]void
error()...msgs: any[]void

A very simple custom logger might ignore the name and level, and write all messages to a file.

Presence

A user’s presence can take one of two values: activeor away. Your app may be interested in known when a user in a workspace’s presence changes. The client helps your appset up presence subscriptions to track the changes inpresence for a list of users. In order to track presence, you need to know each user’s user ID, and call the.subscribePresence(userIds) method.

The userIds argument is an array, and it must include the entire list of user IDs that your app is interested in receiving updates regarding. This means that if you’ve subscribed to any userspreviously, and you’re trying to add subscriptions for new users, you should include the users from the previous callto .subscribePresence(userIds) in the next call.

If instead of being informed when a user’s presence changes (reactively), your app needs to know what the user’s statusis currently (proactively), then your app should use the WebClient’susers.getPresence method. In general, its easier to deal with user presence proactively than to keep track of all thechanges to understand the current presence of a user.

The following example shows how you might try to track the presence of all members of a specific channel. This exampledoes not try to track members who were already in the channel when the bot joined or the app started running, onlyusers who joined the channel after the app started.

Batch presence updates

Your app can receive even more efficient presence updates, by batching many users’ updates into the same event. Thebatch_presence_aware start option can be set to true and will allow Slack to send presence_change events with anarray of users instead of one event for each individual user. This means your app will spend less time processing eventswhen many users change their presence at around the same time.

The example above can be rewritten to take advantage of this efficiency as follows.

Proxy requests with a custom agent

The client allows you to customize the HTTPAgent used to create the connection to Slack.Using this option is the best way to make all requests from your app through a proxy, which is a common requirement inmany corporate settings.

In order to create an Agent from some proxy information (such as a host, port, username, and password), you can useone of many npm packages. We recommend https-proxy-agent. Startby installing this package and saving it to your package.json.

Import the HttpsProxyAgent class, and create an instance that can be used as the agent option of the RTMClient.

Reconnect automatically

Slack Node Definition

If the client’s connection to Slack is interrupted, the client will attempt to reconnect to Slack automatically, bydefault. Your app can choose to monitor when this occurs using the lifecycle events, specificallythe reconnecting and connected events.

If you’d like to turn the automatic reconnection behavior off, the autoReconnect option can be set to false.

Custom TLS configuration

Each connection to Slack starts with a handshake that allows your app to trust that it is actually Slack you areconnecting to. The system for establishing this trust is called TLS. In order for TLS to work, the host running your appkeeps a list of trusted certificate authorities, that it can use to verify a signature Slack produces. You don’tusually see this list, its usually a part of the operating system you’re running on. In very special cases, like certaintesting techniques, you might want to send a request to another party that doesn’t have a valid TLS signature that yourcertificate authority would verify. In these cases, you can provide alternative TLS settings, in order to change how theoperating system might determine whether the signature is valid. You can use the tls option to describe the settingsyou want (these settings are the most common and useful from the standard NodeAPI).

Slack Node Api

tls propertyDescription
caOptionally override the trusted CA certificates. Any string or Buffer can contain multiple PEM CAs concatenated together.
keyPrivate keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with passphrase.
certCert chains in PEM format. One cert chain should be provided per private key.
pfxPFX or PKCS12 encoded private key and certificate chain. pfx is an alternative to providing key and cert individually. PFX is usually encrypted, if it is, passphrase will be used to decrypt it.
passphraseShared passphrase used for a single private key and/or a PFX.

Custom API URL

The URLs for requests to Slack always begin with https://slack.com/api/. In very special cases, such as certaintesting techniques, you might want to send these requests to a different URL. The slackApiUrl option allows you toreplace this prefix with another.

Workspace state snapshot

Slack Node Js Webhook

The client can receive a snapshot of a portion of the workspace’s state while its connecting. This can be useful if yourapp needs to keep track of some data as it changes while the app runs, but it needs the initial start to get started.However, this can also cause the client to fail to connect on large teams. Our recommendation is to call the WebAPI to retrieve workspace state while your app is connecting, instead ofrelying on the cache. See sending rich messages for an example of using the WebClient class insideyour app, and use some of the other methods to get data.

Webhook Nodejs

If you’re certain that you’d like to receive the snapshot, you can set the useRtmConnect option to false. Thisconfigures the client to use the rtm.start method (instead ofrtm.connect), and emit the snapshot on the authenticated event.