Fully Automating Chrisfrew.in Productions - Part 4 of ??? - Building a Slack Bot

Fully Automating Chrisfrew.in Productions - Part 4 of ??? - Building a Slack Bot

Posted on July 21, 2018

Slack Bot!

You may have read Part 3 of my giant automation undertaking about. Maybe not.

Anyway, near the bottom of Part 3, I discuss a messageHub() function that sends a string message to all the places I want it to, one of them being a Slack Bot. This is actually really, really easy to put together. The heroes at Slack are definitely doing a nice job with ease of use for developers.

Step 1: Set Up Your Slack Bot

  • Go to 'Your Apps' on https://api.slack.com: https://api.slack.com/apps
  • Click the green button 'Create New App'
  • Provide a name and pick a workspace you want that bot
  • Under the 'Add features and functionality', click 'Incoming Webhooks'
  • Click the switch to turn the service on
  • Click Add New Webhook to Workspace
  • Select a channel from your slack workspace you want the bot to post to
  • copy the https://hooks.slack.com/blahblahblahblah endpoint!

Step 2: Use POST in Nodejs with Your Link

Now that you have your POST link, sending a message as a slack bot is as easy as sending JSON with a text key filled with your desired message string.

Using the axios library for example, that is as simple as:

axios.post(process.env.CHRISFREW_IN_SLACK_BOT_WEBHOOK_URL, {
  text: "Hello Word"
});

EDIT: time warp all the way to 2021!

I no longer use the axios API, since the fetch API is supported nearly everywhere now. That snippet above can be ported to TypeScript or JavaScript like so:


sendSlackMessage()

sendSlackMessage.ts
typescript
export const sendSlackMessage = (message: string): void => {
process.env.SLACK_WEBHOOK_URL &&
fetch(process.env.SLACK_WEBHOOK_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
text: message,
}),
})
}

Usage

Step 3: Just kidding, there is no step 3!

That's really all there is too it. Of course you can build out more features, but this is really the jist of it. I'll be working on the other direction over the next few weeks - instead of the bot sending information, sending, or asking the bot for information. This will be a very nice way of interacting with my server without the command line :)

Next / Previous Post:

Find more posts by tag:

-~{/* */}~-