Skip to main content

Integrating Slack with Drupal

Back-end Development
Drupal

We recently switched to Slack for our team collaboration needs. It's great software, and has good for both productivity and fun. We are experimenting with ways to extend and enhance what it can do, and one of the avenues we're exploring is setting up integrations between Slack and Drupal.

Slack provides a generic Incoming WebHooks integration for this. Once you have created the integration, you can start sending messages into Slack from anywhere. In this post, I'll give a brief example of how we send a message to Slack from Drupal. I won't go into specific use cases right now, just the framework for sending a message.

function _rdg_slack_send($text, $attachments = array(), $channel = 'general', $username = 'RDG') {
  $token = '****';
  $url = 'https://rapiddg.slack.com/services/hooks/incoming-webhook?token='. $token;
  
  $json = drupal_json_encode(array(
    'text' => $text,
    'attachments' => $attachments,
    'channel' => '#'. $channel,
    'username' => $username,
  ));
  drupal_http_request($url, array('data' => $json));
}

This little helper function is all you need to start sending messages. You'll need to place your account's specific API token in the $token variable, and update the $url variable to match your account. If I were building this as a reusable module, I'd use the Drupal variable_get() system to manage these and place them in the site's settings file.

Drupal handles formatting and issuing the request, via the drupal_http_request() function. Since Slack uses a JSON API, we can use drupal_json_encode() to prepare all of the parameters we send along.

Now we can just call:

_rdg_slack_send('http://i0.kym-cdn.com/photos/images/newsfeed/000/183/128/ZeR46.jpg');

And in Slack we almost instantly see:

Slack image URL notification