npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@shgysk8zer0/slack

v0.0.7

Published

An npm package for sending messages in Slack

Downloads

75

Readme

@shgysk8zer0/slack

An npm package for sending messages in Slack using Incoming Webhooks

CodeQL Node CI Lint Code Base

GitHub license GitHub last commit GitHub release GitHub Sponsors

npm node-current npm bundle size gzipped npm

GitHub followers GitHub forks GitHub stars Twitter Follow

Donate using Liberapay


Installation

NPM

npm i @shgysk8zer0/slack

ESModule / unpkg

This package also works in browsers and can be imported from unpkg.com from https://unpkg.com/@shgys8zer0/slack/*.

About

@shgysk8zer0/slack is a JavaScript library that simplifies sending messages to Slack channels using Incoming Webhooks. Whether you're building a web app, a Node.js script, or experimenting with Deno, this library makes Slack messaging a breeze.

Why This Library?

  • Simplicity: Easily create Slack messages with user-friendly classes.
  • Error Help: Get detailed error messages for easier debugging.
  • Versatile: Use it in web apps, Node.js, and, to some extent, Deno.
  • Customizable: Tailor it to your needs.

While this library is designed to be versatile, please note that full Deno support is not thoroughly tested. While many features work across different JavaScript environments, certain features, such as SlackError.openInBlockKitBuilder(), may not be fully compatible in Deno.

This library adapts to your JavaScript environment, making Slack messaging a snap without being tied to a specific platform.

Important Note: While this library can be used in both server-side (Node.js) and client-side (browser) JavaScript applications, it's strongly recommended to avoid exposing webhook URLs in client-side code. Exposing sensitive information like webhook URLs to the public can pose security risks. For client-side applications, consider using this library within a server-side context or handling the Slack integration server-side to keep your webhook URLs secure.

Getting Started

This package uses Slack's Incoming Webhooks, which requires a little setup.

  1. Create a Slack App
  2. Enable Incoming Webhooks
  3. Create an Incoming Webhook

See Sending messages using Incoming Webhooks | Slack for full details.

Environment Setup

In a Node.js environment, you can set the SLACK_WEBHOOK_URL environment variable in your .env file or directly in your environment to avoid passing the URL to the constructor every time.

# .env file
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/xxxxxxxxx/xxxxxxxxxxx/xxxxxxxx

When using this package in a browser, you'll need to provide the webhook URL directly when constructing the SlackMessage instance.

Example

Import the classes

Option 1 - Import from Individual Class Files

import { SlackMessage } from '@shgysk8zer0/slack/message.js';
import { SlackHeaderBlock } from '@shgysk8zer0/slack/block/header.js';
import { SlackPlainTextElement } from '@shgysk8zer0/slack/element/plain-text.js';
import { SlackMarkdownElement } from '@shgysk8zer0/slack/element/markdown.js';
import { SlackImageBlock } from '@shgysk8zer0/slack/block/image.js';
import { SlackDividerBlock } from '@shgysk8zer0/slack/block/divider.js';
import { SlackButtonElement } from '@shgysk8zer0/slack/element/button.js';
import { SlackSectionBlock } from '@shgysk8zer0/slack/block/section.js';
import { SlackError } from '@shgysk8zer0/slack/error.js';

Option 2 - Import the Entire Package

import {
	SlackHeader,
	SlackPlainText,
	SlackMarkdownElement,
	SlackImageBlock,
	SlackDividerBlock,
	SlackButtonElement,
	SlackSectionBlock,
	SlackError,
} from '@shgysk8zer0/slack';

Build and Send the Message

Class-Based Approach

// Create a new SlackMessage instance with the specified webhook URL.
// This is set to `process.env.SLACK_WEBHOOK_URL` as a default in node
new SlackMessage(SLACK_WEBHOOK_URL)
	.add(
		// Add a header block with a plain text element.
		new SlackHeaderBlock(new SlackPlainTextElement('New Message from Slack Bot')),
		// Add a divider block to separate content.
		new SlackDividerBlock(),
		// Add an image block with a title and alt text.
		new SlackImageBlock('https://example.com/img.png', {
			title: new SlackPlainTextElement('Here is some image'),
			alt: 'Some image',
		}),
		// Add a section block with Markdown-formatted text.
		new SlackSectionBlock(
			new SlackMarkdownElement('This is some example <markdown | https://en.wikipedia.org/wiki/Markdown>'), {
				// Add a button accessory with a primary style and a URL.
				accessory: new SlackButtonElement('Open link!', {
					style: 'primary',
					url: 'https://example.com',
				}),
				// Add plain text fields and a Markdown field for email and phone number.
				fields: [
					new SlackPlainTextElement('Reply'),
					new SlackMarkdownElement('*Email:* <mailto:[email protected] | [email protected]>'),
					new SlackMarkdownElement('*Phone:* <tel:+1-555-555-5555 | 555-555-5555>'),
				],
			}
		)
	)
	// Send the constructed Slack message with a timeout of 5000 milliseconds using an AbortSignal.
	.send({ signal: AbortSignal.timeout(5000) })
	.then(() => {
		// Log a success message when the message is sent.
		console.log('Message sent');
	})
	// An error (a custom SlackError) was thrown
	.catch(async err => {
		console.error(err);
		
		// Status code of the response - 0 if there was a network error or aborted signal
		if (err.status !== 0) {
			// Open the message body in Slack's Block Kit Builder to show where any errors are.
			await err.openInBlockKitBuilder();
		}
	});

Function-Based Approach

Note: Both the "Class-Based" and "Function-Based" approaches are functionally equivalent. In the "Function-Based" approach, functions serve as convenient wrappers around the class constructors. They accept the same arguments as the constructors and simply create instances of the respective classes using the provided arguments.

import { createSlackMessage } from '@shgysk8zer0/slack/message.js';
import { createSlackHeaderBlock } from '@shgysk8zer0/slack/block/header.js';
import { createSlackPlainTextElement } from '@shgysk8zer0/slack/element/plain-text.js';
import { createSlackMarkdownElement } from '@shgysk8zer0/slack/element/markdown.js';
import { createSlackImageBlock } from '@shgysk8zer0/slack/block/image.js';
import { createSlackDividerBlock } from '@shgysk8zer0/slack/block/divider.js';
import { createSlackButtonElement } from '@shgysk8zer0/slack/element/button.js';
import { createSlackSectionBlock } from '@shgysk8zer0/slack/block/section.js';

createSlackMessage(undefined,
	createSlackHeaderBlock(createSlackPlainTextElement('New Message on from Slack Bot')),
	createSlackDividerBlock(),
	createSlackImageBlock('https://example.com/img.png', {
		title: createSlackPlainTextElement('Here is some image'),
		alt: 'Missing Image',
	}),
	createSlackSectionBlock(
		createSlackMarkdownElement('This is some example <markdown | https://en.wikipedia.org/wiki/Markdown>'),
		{
			accessory: createSlackButtonElement('Open link!', {
				style: 'primary',
				url: 'https://example.com',
			}),
			fields: [
				createSlackPlainTextElement('Click Something!'),
				createSlackMarkdownElement('*Email:* <mailto:[email protected] | [email protected]>'),
				createSlackMarkdownElement('*phone:* <tel:+1-555-555-5555 | 555-555-5555>'),
			]
		},
	),
).send({ signal: AbortSignal.timeout(5000) }).then(
	() => console.log('Message sent'),
	async err => {
		console.error(err);

		if (err.status !== 0) {
			await err.openInBlockKitBuilder();
		}
	}
);

To-Do (Work in Progress)

This package is a work in progress, and there are some areas that are still under development. Here's what's on the to-do list:

  • [ ] Complete missing Block and Element types: Some Slack Blocks and Elements are not yet implemented in this package. We'll be adding support for additional types in future updates.
  • [ ] Implement missing properties: While the core functionality is in place, there may be some properties on existing classes that are not yet fully implemented. We'll be working on adding support for these properties in upcoming releases.
  • [ ] Additional documentation: While we provide documentation for the classes and methods introduced in this package, we'll also be adding @see links in comments to the relevant Slack API documentation on api.slack.com for reference.