DEV Community

Cover image for A really simple Slack integration in Rails
Neil Bartley
Neil Bartley

Posted on • Originally published at neil.bar on

A really simple Slack integration in Rails

I’m a big fan of Slack. One of its strengths is the large list of integrations that it provides ‘out of the box’. I’ll cover another strength later (when I get my soap box out!).

Clearly, there isn’t likely to be an integration for ‘my bespoke rails webapp’ but Slack have you covered by supplying a framework to allow incoming notifications.

I’m going to take advantage of this to send event details from ‘my bespoke rails webapp’ to Slack.

Real life use case

The application which I develop, has a bunch of internal mailers hanging off it. These send mails to specified people when certain actions have occurred. In this example we’ll take the case of ‘someone clicking the wibble button’.

Soap Box

Creative Commons by Brandon C. No changes were made.

Email sucks. I get too much of it (I probably send too much as well). By allowing these mailers to exist (and by adding new ones), I’m perpetuating this pain.

Setup

In the ‘DIY Integrations’ section of the Slack admin interface you’ll see the option to add ‘Incoming Webhooks’. Select this and choose the default channel you’d like your notifications to appear in (this can be overriden on a case by case basis).

What we need from this is a unique ‘Webhook URL’. Once we have this, we can start putting together a payload.

Integration

Specification

I’m not going to copy-paste the fine documentation produced by Slack. Instead, here are some links!

At last, some code!

Add your webhook URL and test channel to your development application.yml.

The webhook URL will likely stay the same in your production environment, but you may want to update the channel name.

{gist https://gist.github.com/neilbartley/f1ac92cf40f79a789e64 %}

I’ve created a service for our our SlackBot, which could simply be called from the controller.

{gist https://gist.github.com/neilbartley/87bbcb97c67617d16344 %}

To demonstrate, lets call from rails console:

{gist https://gist.github.com/neilbartley/21d1d6e1d4ffb09700c9 %}

Line two will produce the following notification in the #events_test channel:

Lines four and six illustrate overriding the default channel to another channel or user.


Top comments (0)