Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

messaging-api-slack

Package Overview
Dependencies
Maintainers
3
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

messaging-api-slack

Messaging API client for Slack

  • 1.0.0-beta.7
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.7K
decreased by-22.69%
Maintainers
3
Weekly downloads
 
Created
Source

messaging-api-slack

Messaging API client for Slack

Slack

Table of Contents

  • Installation
  • OAuth Client
  • Webhook Client
  • Debug Tips
  • Test

Installation

npm i --save messaging-api-slack

or

yarn add messaging-api-slack

OAuth Client

Usage

Get your bot user OAuth access token by setup OAuth & Permissions function to your app or check the Using OAuth 2.0 document.

const { SlackOAuthClient } = require('messaging-api-slack');

// get access token by setup OAuth & Permissions function to your app.
// https://api.slack.com/docs/oauth
const client = SlackOAuthClient.connect(
  'xoxb-000000000000-xxxxxxxxxxxxxxxxxxxxxxxx'
);
Error Handling

messaging-api-slack uses axios as HTTP client. We use axios-error package to wrap API error instances for better formatting error messages. Directly console.log on the error instance will return formatted message. If you'd like to get the axios request, response, or config, you can still get them via those keys on the error instance.

client.callMethod(method, body).catch(error => {
  console.log(error); // formatted error message
  console.log(error.stack); // error stack trace
  console.log(error.config); // axios request config
  console.log(error.request); // HTTP request
  console.log(error.response); // HTTP response
});

API Reference

All methods return a Promise.


Call available methods

callMethod(method, body) - Official docs

Calling any API methods which follow slack calling conventions.

ParamTypeDescription
methodStringOne of API Methods
bodyObjectBody that the method needs.

Example:

client.callMethod('chat.postMessage', { channel: 'C8763', text: 'Hello!' });

Chat API

postMessage(channel, message [, options]) - Official docs

Sends a message to a channel.

ParamTypeDescription
channelStringChannel, private group, or IM channel to send message to. Can be an encoded ID, or a name.
messageString | ObjectThe message to be sent, can be text message or attachment message.
optionsObjectOther optional parameters.
options.accessTokenStringCustom access token of the request.

Example:

client.postMessage('C8763', { text: 'Hello!' });
client.postMessage('C8763', { attachments: [someAttachments] });
client.postMessage('C8763', 'Hello!');
client.postMessage('C8763', 'Hello!', { as_user: true });

If you send message with attachments, messaging-api-slack will automatically stringify the attachments field for you.

client.postMessage(
  'C8763',
  {
    text: 'Hello!',
    attachments: [
      {
        text: 'Choose a game to play',
        fallback: 'You are unable to choose a game',
        callback_id: 'wopr_game',
        color: '#3AA3E3',
        attachment_type: 'default',
        actions: [
          {
            name: 'game',
            text: 'Chess',
            type: 'button',
            value: 'chess',
          },
        ],
      },
    ],
  },
  {
    as_user: true,
  }
);

postEphemeral(channel, user, message [, options]) - Official docs

Sends an ephemeral message to a user in a channel.

ParamTypeDescription
channelStringChannel, private group, or IM channel to send message to. Can be an encoded ID, or a name.
userStringid of the user who will receive the ephemeral message. The user should be in the channel specified by the channel argument.
messageString | ObjectThe message to be sent, can be text message or attachment message.
optionsObjectOther optional parameters.
options.accessTokenStringCustom access token of the request.

Example:

client.postEphemeral('C8763', 'U56781234', { text: 'Hello!' });
client.postEphemeral('C8763', 'U56781234', { attachments: [someAttachments] });
client.postEphemeral('C8763', 'U56781234', 'Hello!');
client.postEphemeral('C8763', 'U56781234', 'Hello!', { as_user: true });

Users API

getUserList(options?) - Official docs

Lists all users in a Slack team.

ParamTypeDescription
optionsObjectOther optional parameters.
options.cursorStringPaginate through collections of data by setting the cursor parameter to a next_cursor attribute returned by a previous request's response_metadata.
options.accessTokenStringCustom access token of the request.

Example:

client.getUserList({ cursor }).then(res => {
  console.log(res);
  // {
  //   members: [
  //     { ... },
  //     { ... },
  //   ],
  //   next: 'abcdefg',
  // }
});

getAllUserList(options?) - Official docs

Recursively lists all users in a Slack team using cursor.

ParamTypeDescription
optionsObjectOther optional parameters.
options.accessTokenStringCustom access token of the request.

Example:

client.getAllUserList().then(res => {
  console.log(res);
  // [
  //   { ... },
  //   { ... },
  // ]
});

getUserInfo(userId, options?) - Official docs

Gets information about an user.

ParamTypeDescription
userIdStringUser to get info on.
optionsObjectOther optional parameters.
options.accessTokenStringCustom access token of the request.

Example:

client.getUserInfo(userId).then(res => {
  console.log(res);
  // {
  //   id: 'U123456',
  //   name: 'bobby',
  //   ...
  // }
});

Channels API

getChannelList(options?) - Official docs

ParamTypeDescription
optionsObjectOther optional parameters.
options.accessTokenStringCustom access token of the request.

Lists all channels in a Slack team.

Example:

client.getChannelList().then(res => {
  console.log(res);
  // [
  //   { ... },
  //   { ... },
  // ]
});

getChannelInfo(channelId, options?) - Official docs

Gets information about a channel.

ParamTypeDescription
channelIdStringChannel to get info on.
optionsObjectOther optional parameters.
options.accessTokenStringCustom access token of the request.

Example:

client.getChannelInfo(channelId).then(res => {
  console.log(res);
  // {
  //   id: 'C8763',
  //   name: 'fun',
  //   ...
  // }
});

Conversasions API

getConversationInfo(channelId, options?) - Official docs

Retrieve information about a conversation.

ParamTypeDescription
channelIdStringChannel to get info on.
optionsObjectOther optional parameters.
options.accessTokenStringCustom access token of the request.

Example:

client.getConversationInfo(channelId).then(res => {
  console.log(res);
  // {
  //   id: 'C8763',
  //   name: 'fun',
  //   ...
  // }
});

getConversationMembers(channelId, options?) - Official docs

Retrieve members of a conversation.

ParamTypeDescription
channelIdStringChannel to get info on.
optionsObjectOptional arguments.
options.accessTokenStringCustom access token of the request.

Example:

client.getConversationMembers(channelId, { cursor: 'xxx' });
client.getConversationMembers(channelId).then(res => {
  console.log(res);
  // {
  //   members: ['U061F7AUR', 'U0C0NS9HN'],
  //   next: 'cursor',
  // }
});

getAllConversationMembers(channelId, options?) - Official docs

Recursively retrieve members of a conversation using cursor.

ParamTypeDescription
channelIdStringChannel to get info on.
optionsObjectOther optional parameters.
options.accessTokenStringCustom access token of the request.

Example:

client.getAllConversationMembers(channelId).then(res => {
  console.log(res);
  // ['U061F7AUR', 'U0C0NS9HN', ...]
});

getConversationList(options?) - Official docs

Lists all channels in a Slack team.

ParamTypeDescription
optionsObjectOptional arguments.
options.accessTokenStringCustom access token of the request.

Example:

client.getConversationList({ cursor: 'xxx' });
client.getConversationList().then(res => {
  console.log(res);
  // {
  //   channels: [
  //     {
  //       id: 'C012AB3CD',
  //       name: 'general',
  //       ...
  //     },
  //     {
  //       id: 'C012AB3C5',
  //       name: 'random',
  //       ...
  //     },
  //   ],
  //   next: 'cursor',
  // }
});

getAllConversationList(options?) - Official docs

Recursively lists all channels in a Slack team using cursor.

ParamTypeDescription
optionsObjectOptional arguments.
options.accessTokenStringCustom access token of the request.

Example:

client.getAllConversationList().then(res => {
  console.log(res);
  // [
  //   {
  //     id: 'C012AB3CD',
  //     name: 'general',
  //     ...
  //   },
  //   {
  //     id: 'C012AB3C5',
  //     name: 'random',
  //     ...
  //   },
  // ],
});

Webhook Client

Usage

Get your webhook url by adding a Incoming Webhooks integration to your team or setup Incoming Webhooks function to your app.

const { SlackWebhookClient } = require('messaging-api-slack');

// get webhook URL by adding a Incoming Webhook integration to your team.
// https://my.slack.com/services/new/incoming-webhook/
const client = SlackWebhookClient.connect(
  'https://hooks.slack.com/services/XXXXXXXX/YYYYYYYY/zzzzzZZZZZ'
);

API Reference

All methods return a Promise.


Send API - Official docs

sendRawBody(body)

ParamTypeDescription
bodyObjectRaw data to be sent.

Example:

client.sendRawBody({ text: 'Hello!' });

sendText(text)

ParamTypeDescription
textStringText of the message to be sent.

Example:

client.sendText('Hello!');

sendAttachments(attachments) - Official docs

Send multiple attachments which let you add more context to a message.

ParamTypeDescription
attachmentsArray<Object>Messages are attachments, defined as an array. Each object contains the parameters to customize the appearance of a message attachment.

Example:

client.sendAttachments([
  {
    fallback: 'some text',
    pretext: 'some pretext',
    color: 'good',
    fields: [
      {
        title: 'aaa',
        value: 'bbb',
        short: false,
      },
    ],
  },
  {
    fallback: 'some other text',
    pretext: 'some pther pretext',
    color: '#FF0000',
    fields: [
      {
        title: 'ccc',
        value: 'ddd',
        short: false,
      },
    ],
  },
]);

sendAttachment(attachment) - Official docs

Send only one attachment.

ParamTypeDescription
attachmentsObjectMessage is an attachment. The object contains the parameters to customize the appearance of a message attachment.

Example:

client.sendAttachment({
  fallback: 'some text',
  pretext: 'some pretext',
  color: 'good',
  fields: [
    {
      title: 'aaa',
      value: 'bbb',
      short: false,
    },
  ],
});

Debug Tips

Log requests details

To enable default request debugger, use following DEBUG env variable:

DEBUG=messaging-api-slack

If you want to use custom request logging function, just define your own onRequest:

// for SlackOAuthClient
const client = SlackOAuthClient.connect({
  accessToken: ACCESS_TOKEN,
  onRequest: ({ method, url, headers, body }) => {
    /* */
  },
});

// for SlackWebhookClient
const client = SlackWebhookClient.connect({
  url: URL,
  onRequest: ({ method, url, headers, body }) => {
    /* */
  },
});

Test

Point requests to your dummy server

To avoid sending requests to real Slack server, specify origin option when constructing your client:

const { SlackOAuthClient } = require('messaging-api-slack');

const client = SlackOAuthClient.connect({
  accessToken: ACCESS_TOKEN,
  origin: 'https://mydummytestserver.com',
});

Warning: Don't do this on production server.

Manual Mock with Jest

create __mocks__/messaging-api-slack.js in your project root:

// __mocks__/messaging-api-slack.js
const jestMock = require('jest-mock');
const { SlackOAuthClient, SlackWebhookClient } = require.requireActual(
  'messaging-api-slack'
);

module.exports = {
  SlackOAuthClient: {
    connect: jest.fn(() => {
      const Mock = jestMock.generateFromMetadata(
        jestMock.getMetadata(SlackOAuthClient)
      );
      return new Mock();
    }),
  },
  SlackWebhookClient: {
    connect: jest.fn(() => {
      const Mock = jestMock.generateFromMetadata(
        jestMock.getMetadata(SlackWebhookClient)
      );
      return new Mock();
    }),
  },
};

Then, mock messaging-api-slack package in your tests:

// __tests__/mytest.spec.js
jest.mock('messaging-api-slack');

Keywords

FAQs

Package last updated on 03 Dec 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc