Skip to content

Instantly share code, notes, and snippets.

@lakshmantgld
Last active February 7, 2024 03:57
Show Gist options
  • Save lakshmantgld/42b32a38af2a64b5b683bbc92aae8d8e to your computer and use it in GitHub Desktop.
Save lakshmantgld/42b32a38af2a64b5b683bbc92aae8d8e to your computer and use it in GitHub Desktop.
Configuring slack webhook

A Webhook, in simple terms, is a user-defined HTTP callback. It is a mechanism for the system to notify you about an event. In our case, we need to send messages to a particular channel in slack. Slack calls in Incoming Webhook. It is a mechanism to send messages to your Slack Channel from external sources. These external sources could be any application or service that is capable of sending a JSON payload over HTTP into a Slack Channel. Each Channel will be identified by a unique Incoming Webhook URL to which you can post the message from outside. This configuration is done via the Integrations for your channel.

Steps to create a incoming webhook in Slack:

  1. Naviagte to the Incoming Webhook URL. Click the hyper link incoming webhook integration below the heading Incoming Webhooks.
  2. You will be asked to enter your team URL, followed by your slack credentials.
  3. Once you have completed the above step, you will see the wizard kind of webpage to create a new webhook. First, Select the channel to which you want to post. If you want to create a new channel click the create a new channel hyperlink.
  4. Then, click the green button Add Incoming Webhook. You will see a unique URL generated which can be used to send notifications to that channel.
  5. Other seetings like changing the icon of the slack bot or other settings can be done by scrolling down the form.
  6. Now, you can test it by sending messages to the channel using CURL. curl -X POST --data-urlencode 'payload={"channel": "#general", "username": "webhookbot", "text": "This is posted to #general and comes from a bot named webhookbot.", "icon_emoji": ":ghost:"}' https://hooks.slack.com/services/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.
  7. You can also axios and here is the snippet for that:
import axios from 'axios';

const options = {
  text: "Message from slack bot!!",
};

axios.post('<SLACK_WEBHOOK_URL>', JSON.stringify(options))
.then((response) => {
  console.log('SUCCEEDED: Sent slack webhook: \n', response.data);
  resolve(response.data);
})
.catch((error) => {
  console.log('FAILED: Send slack webhook', error);
  reject(new Error('FAILED: Send slack webhook'));
});

By following above steps, one can create a slack webHook to a particular channel and send notifications to it from any sources.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment